Fish completion using Go completion (#1048)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Marc Khouzam · committed by GitHub · parent 7fead4b · Browse files · 7 files·+552 added−27 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca>
Diff stats
7 files+552 added−27 removed
- other:+552 added−27 removed
Provenance
- Commit
a684a6d- Tree
706bc69- Author
Marc Khouzam <marc.khouzam@montreal.ca>- Committer
GitHub <noreply@github.com>- Parent
7fead4b
7 files changed+552 added−27 removed
modified:args.go+9 added-1 removed
1 package cobra2 3 import (4 "fmt"5+ "strings"6 )7 8 type PositionalArgs func(cmd *Command, args []string) error9 24 unmodified lines34 35 // OnlyValidArgs returns an error if any args are not in the list of ValidArgs.36 func OnlyValidArgs(cmd *Command, args []string) error {37 if len(cmd.ValidArgs) > 0 {38+ // Remove any description that may be included in ValidArgs.39+ // A description is following a tab character.40+ var validArgs []string41+ for _, v := range cmd.ValidArgs {42+ validArgs = append(validArgs, strings.Split(v, "\t")[0])43+ }44+45 for _, v := range args {38- if !stringInSlice(v, cmd.ValidArgs) {46+ if !stringInSlice(v, validArgs) {47 return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0]))48 }49 }50 }59 unmodified linesmodified:bash_completions.go+4 added-1 removed
342 unmodified lines343 fi344 __%[1]s_handle_word345 }346 347-`, name, ShellCompRequestCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp))347+`, name, ShellCompNoDescRequestCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp))348 }349 350 func writePostscript(buf *bytes.Buffer, name string) {351 name = strings.Replace(name, ":", "__", -1)195 unmodified lines547 func writeRequiredNouns(buf *bytes.Buffer, cmd *Command) {548 buf.WriteString(" must_have_one_noun=()\n")549 sort.Sort(sort.StringSlice(cmd.ValidArgs))550 for _, value := range cmd.ValidArgs {551+ // Remove any description that may be included following a tab character.552+ // Descriptions are not supported by bash completion.553+ value = strings.Split(value, "\t")[0]554 buf.WriteString(fmt.Sprintf(" must_have_one_noun+=(%q)\n", value))555 }556 if cmd.ValidArgsFunction != nil {557 buf.WriteString(" has_completion_function=1\n")84 unmodified linesmodified:bash_completions.md+4 added
113 unmodified lines114 ### Dynamic completion of nouns115 116 In some cases it is not possible to provide a list of possible completions in advance. Instead, the list of completions must be determined at execution-time. Cobra provides two ways of defining such dynamic completion of nouns. Note that both these methods can be used along-side each other as long as they are not both used for the same command.117 118+**Note**: *Custom Completions written in Go* will automatically work for other shell-completion scripts (e.g., Fish shell), while *Custom Completions written in Bash* will only work for Bash shell-completion. It is therefore recommended to use *Custom Completions written in Go*.119+120 #### 1. Custom completions of nouns written in Go121 122 In a similar fashion as for static completions, you can use the `ValidArgsFunction` field to provide a Go function that Cobra will execute when it needs the list of completion choices for the nouns of a command. Note that either `ValidArgs` or `ValidArgsFunction` can be used for a single cobra command, but not both.123 Simplified code from `helm status` looks like:178 unmodified lines302 # Specify custom flag completion303 304 As for nouns, Cobra provides two ways of defining dynamic completion of flags. Note that both these methods can be used along-side each other as long as they are not both used for the same flag.305 306+**Note**: *Custom Completions written in Go* will automatically work for other shell-completion scripts (e.g., Fish shell), while *Custom Completions written in Bash* will only work for Bash shell-completion. It is therefore recommended to use *Custom Completions written in Go*.307+308 ## 1. Custom completions of flags written in Go309 310 To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function in the following manner:311 72 unmodified linesmodified:custom_completions_test.go+268 added-22 removed
10 unmodified lines11 return nil, ShellCompDirectiveNoFileComp12 }13 14 var completions []string15- for _, comp := range []string{"one", "two"} {15+ for _, comp := range []string{"one\tThe first", "two\tThe second"} {16 if strings.HasPrefix(comp, toComplete) {17 completions = append(completions, comp)18 }19 }5 unmodified lines25 return nil, ShellCompDirectiveNoFileComp26 }27 28 var completions []string29- for _, comp := range []string{"three", "four"} {29+ for _, comp := range []string{"three\tThe third", "four\tThe fourth"} {30 if strings.HasPrefix(comp, toComplete) {31 completions = append(completions, comp)32 }33 }7 unmodified lines41 Run: emptyRun,42 }43 44 // Test completing an empty string45- output, err := executeCommand(rootCmd, ShellCompRequestCmd, "")45+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")46 if err != nil {47 t.Errorf("Unexpected error: %v", err)48 }49 7 unmodified lines57 t.Errorf("expected: %q, got: %q", expected, output)58 }59 60 // Check completing with a prefix61- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "t")61+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")62 if err != nil {63 t.Errorf("Unexpected error: %v", err)64 }65 19 unmodified lines85 Run: emptyRun,86 }87 88 // Check completing with wrong number of args89- output, err := executeCommand(rootCmd, ShellCompRequestCmd, "unexpectedArg", "t")89+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "unexpectedArg", "t")90 if err != nil {91 t.Errorf("Unexpected error: %v", err)92 }93 20 unmodified lines114 }115 rootCmd.AddCommand(child1Cmd, child2Cmd)116 117 // Test completion of first sub-command with empty argument118- output, err := executeCommand(rootCmd, ShellCompRequestCmd, "child1", "")118+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child1", "")119 if err != nil {120 t.Errorf("Unexpected error: %v", err)121 }122 7 unmodified lines130 t.Errorf("expected: %q, got: %q", expected, output)131 }132 133 // Test completion of first sub-command with a prefix to complete134- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child1", "t")134+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child1", "t")135 if err != nil {136 t.Errorf("Unexpected error: %v", err)137 }138 6 unmodified lines145 t.Errorf("expected: %q, got: %q", expected, output)146 }147 148 // Check completing with wrong number of args149- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child1", "unexpectedArg", "t")149+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child1", "unexpectedArg", "t")150 if err != nil {151 t.Errorf("Unexpected error: %v", err)152 }153 5 unmodified lines159 t.Errorf("expected: %q, got: %q", expected, output)160 }161 162 // Test completion of second sub-command with empty argument163- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "")163+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child2", "")164 if err != nil {165 t.Errorf("Unexpected error: %v", err)166 }167 6 unmodified lines174 if output != expected {175 t.Errorf("expected: %q, got: %q", expected, output)176 }177 178- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "t")178+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child2", "t")179 if err != nil {180 t.Errorf("Unexpected error: %v", err)181 }182 6 unmodified lines189 t.Errorf("expected: %q, got: %q", expected, output)190 }191 192 // Check completing with wrong number of args193- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "unexpectedArg", "t")193+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child2", "unexpectedArg", "t")194 if err != nil {195 t.Errorf("Unexpected error: %v", err)196 }197 16 unmodified lines214 }215 rootCmd.AddCommand(child)216 217 // Test completion of first sub-command with empty argument218- output, err := executeCommand(rootCmd, ShellCompRequestCmd, "son", "")218+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "son", "")219 if err != nil {220 t.Errorf("Unexpected error: %v", err)221 }222 7 unmodified lines230 t.Errorf("expected: %q, got: %q", expected, output)231 }232 233 // Test completion of first sub-command with a prefix to complete234- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "daughter", "t")234+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "daughter", "t")235 if err != nil {236 t.Errorf("Unexpected error: %v", err)237 }238 6 unmodified lines245 t.Errorf("expected: %q, got: %q", expected, output)246 }247 248 // Check completing with wrong number of args249- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "son", "unexpectedArg", "t")249+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "son", "unexpectedArg", "t")250 if err != nil {251 t.Errorf("Unexpected error: %v", err)252 }253 5 unmodified lines259 t.Errorf("expected: %q, got: %q", expected, output)260 }261 }262 263-func TestValidArgsFuncInScript(t *testing.T) {263+func TestValidArgsFuncInBashScript(t *testing.T) {264 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}265 child := &Command{266 Use: "child",267 ValidArgsFunction: validArgsFunc,7 unmodified lines275 276 check(t, output, "has_completion_function=1")277 }278 279-func TestNoValidArgsFuncInScript(t *testing.T) {279+func TestNoValidArgsFuncInBashScript(t *testing.T) {280 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}281 child := &Command{282 Use: "child",283 Run: emptyRun,6 unmodified lines290 291 checkOmit(t, output, "has_completion_function=1")292 }293 294+func TestCompleteCmdInBashScript(t *testing.T) {295+ rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}296+ child := &Command{297+ Use: "child",298+ ValidArgsFunction: validArgsFunc,299+ Run: emptyRun,300+ }301+ rootCmd.AddCommand(child)302+303+ buf := new(bytes.Buffer)304+ rootCmd.GenBashCompletion(buf)305+ output := buf.String()306+307+ check(t, output, ShellCompNoDescRequestCmd)308+}309+310+func TestCompleteNoDesCmdInFishScript(t *testing.T) {311+ rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}312+ child := &Command{313+ Use: "child",314+ ValidArgsFunction: validArgsFunc,315+ Run: emptyRun,316+ }317+ rootCmd.AddCommand(child)318+319+ buf := new(bytes.Buffer)320+ rootCmd.GenFishCompletion(buf, false)321+ output := buf.String()322+323+ check(t, output, ShellCompNoDescRequestCmd)324+}325+326+func TestCompleteCmdInFishScript(t *testing.T) {327+ rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}328+ child := &Command{329+ Use: "child",330+ ValidArgsFunction: validArgsFunc,331+ Run: emptyRun,332+ }333+ rootCmd.AddCommand(child)334+335+ buf := new(bytes.Buffer)336+ rootCmd.GenFishCompletion(buf, true)337+ output := buf.String()338+339+ check(t, output, ShellCompRequestCmd)340+ checkOmit(t, output, ShellCompNoDescRequestCmd)341+}342+343 func TestFlagCompletionInGo(t *testing.T) {344 rootCmd := &Command{345 Use: "root",346 Run: emptyRun,347 }348 rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")349 rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {350 completions := []string{}302- for _, comp := range []string{"1", "2", "10"} {351+ for _, comp := range []string{"1\tThe first", "2\tThe second", "10\tThe tenth"} {352 if strings.HasPrefix(comp, toComplete) {353 completions = append(completions, comp)354 }355 }1 unmodified line357 })358 rootCmd.Flags().String("filename", "", "Enter a filename")359 rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {360 completions := []string{}312- for _, comp := range []string{"file.yaml", "myfile.json", "file.xml"} {361+ for _, comp := range []string{"file.yaml\tYAML format", "myfile.json\tJSON format", "file.xml\tXML format"} {362 if strings.HasPrefix(comp, toComplete) {363 completions = append(completions, comp)364 }365 }366 return completions, ShellCompDirectiveNoSpace | ShellCompDirectiveNoFileComp367 })368 369 // Test completing an empty string321- output, err := executeCommand(rootCmd, ShellCompRequestCmd, "--introot", "")370+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--introot", "")371 if err != nil {372 t.Errorf("Unexpected error: %v", err)373 }374 8 unmodified lines383 t.Errorf("expected: %q, got: %q", expected, output)384 }385 386 // Check completing with a prefix338- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--introot", "1")387+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--introot", "1")388 if err != nil {389 t.Errorf("Unexpected error: %v", err)390 }391 7 unmodified lines399 t.Errorf("expected: %q, got: %q", expected, output)400 }401 402 // Test completing an empty string354- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--filename", "")403+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--filename", "")404 if err != nil {405 t.Errorf("Unexpected error: %v", err)406 }407 8 unmodified lines416 t.Errorf("expected: %q, got: %q", expected, output)417 }418 419 // Check completing with a prefix371- output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--filename", "f")420+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--filename", "f")421 if err != nil {422 t.Errorf("Unexpected error: %v", err)423 }424 6 unmodified lines431 if output != expected {432 t.Errorf("expected: %q, got: %q", expected, output)433 }434 }435+436+func TestValidArgsFuncChildCmdsWithDesc(t *testing.T) {437+ rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}438+ child1Cmd := &Command{439+ Use: "child1",440+ ValidArgsFunction: validArgsFunc,441+ Run: emptyRun,442+ }443+ child2Cmd := &Command{444+ Use: "child2",445+ ValidArgsFunction: validArgsFunc2,446+ Run: emptyRun,447+ }448+ rootCmd.AddCommand(child1Cmd, child2Cmd)449+450+ // Test completion of first sub-command with empty argument451+ output, err := executeCommand(rootCmd, ShellCompRequestCmd, "child1", "")452+ if err != nil {453+ t.Errorf("Unexpected error: %v", err)454+ }455+456+ expected := strings.Join([]string{457+ "one\tThe first",458+ "two\tThe second",459+ ":0",460+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")461+462+ if output != expected {463+ t.Errorf("expected: %q, got: %q", expected, output)464+ }465+466+ // Test completion of first sub-command with a prefix to complete467+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child1", "t")468+ if err != nil {469+ t.Errorf("Unexpected error: %v", err)470+ }471+472+ expected = strings.Join([]string{473+ "two\tThe second",474+ ":0",475+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")476+477+ if output != expected {478+ t.Errorf("expected: %q, got: %q", expected, output)479+ }480+481+ // Check completing with wrong number of args482+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child1", "unexpectedArg", "t")483+ if err != nil {484+ t.Errorf("Unexpected error: %v", err)485+ }486+487+ expected = strings.Join([]string{488+ ":4",489+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")490+491+ if output != expected {492+ t.Errorf("expected: %q, got: %q", expected, output)493+ }494+495+ // Test completion of second sub-command with empty argument496+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "")497+ if err != nil {498+ t.Errorf("Unexpected error: %v", err)499+ }500+501+ expected = strings.Join([]string{502+ "three\tThe third",503+ "four\tThe fourth",504+ ":0",505+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")506+507+ if output != expected {508+ t.Errorf("expected: %q, got: %q", expected, output)509+ }510+511+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "t")512+ if err != nil {513+ t.Errorf("Unexpected error: %v", err)514+ }515+516+ expected = strings.Join([]string{517+ "three\tThe third",518+ ":0",519+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")520+521+ if output != expected {522+ t.Errorf("expected: %q, got: %q", expected, output)523+ }524+525+ // Check completing with wrong number of args526+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "unexpectedArg", "t")527+ if err != nil {528+ t.Errorf("Unexpected error: %v", err)529+ }530+531+ expected = strings.Join([]string{532+ ":4",533+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")534+535+ if output != expected {536+ t.Errorf("expected: %q, got: %q", expected, output)537+ }538+}539+540+func TestFlagCompletionInGoWithDesc(t *testing.T) {541+ rootCmd := &Command{542+ Use: "root",543+ Run: emptyRun,544+ }545+ rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")546+ rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {547+ completions := []string{}548+ for _, comp := range []string{"1\tThe first", "2\tThe second", "10\tThe tenth"} {549+ if strings.HasPrefix(comp, toComplete) {550+ completions = append(completions, comp)551+ }552+ }553+ return completions, ShellCompDirectiveDefault554+ })555+ rootCmd.Flags().String("filename", "", "Enter a filename")556+ rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {557+ completions := []string{}558+ for _, comp := range []string{"file.yaml\tYAML format", "myfile.json\tJSON format", "file.xml\tXML format"} {559+ if strings.HasPrefix(comp, toComplete) {560+ completions = append(completions, comp)561+ }562+ }563+ return completions, ShellCompDirectiveNoSpace | ShellCompDirectiveNoFileComp564+ })565+566+ // Test completing an empty string567+ output, err := executeCommand(rootCmd, ShellCompRequestCmd, "--introot", "")568+ if err != nil {569+ t.Errorf("Unexpected error: %v", err)570+ }571+572+ expected := strings.Join([]string{573+ "1\tThe first",574+ "2\tThe second",575+ "10\tThe tenth",576+ ":0",577+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")578+579+ if output != expected {580+ t.Errorf("expected: %q, got: %q", expected, output)581+ }582+583+ // Check completing with a prefix584+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--introot", "1")585+ if err != nil {586+ t.Errorf("Unexpected error: %v", err)587+ }588+589+ expected = strings.Join([]string{590+ "1\tThe first",591+ "10\tThe tenth",592+ ":0",593+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")594+595+ if output != expected {596+ t.Errorf("expected: %q, got: %q", expected, output)597+ }598+599+ // Test completing an empty string600+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--filename", "")601+ if err != nil {602+ t.Errorf("Unexpected error: %v", err)603+ }604+605+ expected = strings.Join([]string{606+ "file.yaml\tYAML format",607+ "myfile.json\tJSON format",608+ "file.xml\tXML format",609+ ":6",610+ "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")611+612+ if output != expected {613+ t.Errorf("expected: %q, got: %q", expected, output)614+ }615+616+ // Check completing with a prefix617+ output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--filename", "f")618+ if err != nil {619+ t.Errorf("Unexpected error: %v", err)620+ }621+622+ expected = strings.Join([]string{623+ "file.yaml\tYAML format",624+ "file.xml\tXML format",625+ ":6",626+ "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")627+628+ if output != expected {629+ t.Errorf("expected: %q, got: %q", expected, output)630+ }631+}modified:custom_completions.go+88 added-3 removed
7 unmodified lines8 9 "github.com/spf13/pflag"10 )11 12+const (12-// ShellCompRequestCmd is the name of the hidden command that is used to request13-// completion results from the program. It is used by the shell completion script.14-const ShellCompRequestCmd = "__complete"13+ // ShellCompRequestCmd is the name of the hidden command that is used to request14+ // completion results from the program. It is used by the shell completion scripts.15+ ShellCompRequestCmd = "__complete"16+ // ShellCompNoDescRequestCmd is the name of the hidden command that is used to request17+ // completion results without their description. It is used by the shell completion scripts.18+ ShellCompNoDescRequestCmd = "__completeNoDesc"19+)20 21 // Global map of flag completion functions.22 var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){}23 57 unmodified lines81 // Adds a special hidden command that can be used to request custom completions.82 func (c *Command) initCompleteCmd(args []string) {83 completeCmd := &Command{84 Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd),85+ Aliases: []string{ShellCompNoDescRequestCmd},86 DisableFlagsInUseLine: true,87 Hidden: true,88 DisableFlagParsing: true,89 Args: MinimumNArgs(1),8 unmodified lines98 // 1- There could be some valid completions even though there was an error99 // 2- Even without completions, we need to print the directive100 }101 102+ noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd)103 for _, comp := range completions {104+ if noDescriptions {105+ // Remove any description that may be included following a tab character.106+ comp = strings.Split(comp, "\t")[0]107+ }108 // Print each possible completion to stdout for the completion script to consume.109 fmt.Fprintln(finalCmd.OutOrStdout(), comp)110 }111 37 unmodified lines149 // Unable to find the real command. E.g., <program> someInvalidCmd <TAB>150 return c, completions, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)151 }152 153+ // When doing completion of a flag name, as soon as an argument starts with154+ // a '-' we know it is a flag. We cannot use isFlagArg() here as it requires155+ // the flag to be complete156+ if len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") {157+ // We are completing a flag name158+ finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {159+ completions = append(completions, getFlagNameCompletions(flag, toComplete)...)160+ })161+ finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {162+ completions = append(completions, getFlagNameCompletions(flag, toComplete)...)163+ })164+165+ directive := ShellCompDirectiveDefault166+ if len(completions) > 0 {167+ if strings.HasSuffix(completions[0], "=") {168+ directive = ShellCompDirectiveNoSpace169+ }170+ }171+ return finalCmd, completions, directive, nil172+ }173+174 var flag *pflag.Flag175 if !finalCmd.DisableFlagParsing {176 // We only do flag completion if we are allowed to parse flags177 // This is important for commands which have requested to do their own flag completion.3 unmodified lines181 return finalCmd, completions, ShellCompDirectiveDefault, err182 }183 }184 185+ if flag == nil {186+ // Complete subcommand names187+ for _, subCmd := range finalCmd.Commands() {188+ if subCmd.IsAvailableCommand() && strings.HasPrefix(subCmd.Name(), toComplete) {189+ completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))190+ }191+ }192+193+ if len(finalCmd.ValidArgs) > 0 {194+ // Always complete ValidArgs, even if we are completing a subcommand name.195+ // This is for commands that have both subcommands and ValidArgs.196+ for _, validArg := range finalCmd.ValidArgs {197+ if strings.HasPrefix(validArg, toComplete) {198+ completions = append(completions, validArg)199+ }200+ }201+202+ // If there are ValidArgs specified (even if they don't match), we stop completion.203+ // Only one of ValidArgs or ValidArgsFunction can be used for a single command.204+ return finalCmd, completions, ShellCompDirectiveNoFileComp, nil205+ }206+207+ // Always let the logic continue so as to add any ValidArgsFunction completions,208+ // even if we already found sub-commands.209+ // This is for commands that have subcommands but also specify a ValidArgsFunction.210+ }211+212 // Parse the flags and extract the arguments to prepare for calling the completion function213 if err = finalCmd.ParseFlags(finalArgs); err != nil {214 return finalCmd, completions, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())215 }21 unmodified lines237 completions = append(completions, comps...)238 return finalCmd, completions, directive, nil239 }240 241+func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string {242+ if nonCompletableFlag(flag) {243+ return []string{}244+ }245+246+ var completions []string247+ flagName := "--" + flag.Name248+ if strings.HasPrefix(flagName, toComplete) {249+ // Flag without the =250+ completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))251+252+ if len(flag.NoOptDefVal) == 0 {253+ // Flag requires a value, so it can be suffixed with =254+ flagName += "="255+ completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))256+ }257+ }258+259+ flagName = "-" + flag.Shorthand260+ if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) {261+ completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))262+ }263+264+ return completions265+}266+267 func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) {268 var flagName string269 trimmedArgs := args270 flagWithEqual := false114 unmodified linesadded:fish_completions.go+172 added
1+package cobra2+3+import (4+ "bytes"5+ "fmt"6+ "io"7+ "os"8+)9+10+func genFishComp(buf *bytes.Buffer, name string, includeDesc bool) {11+ compCmd := ShellCompRequestCmd12+ if !includeDesc {13+ compCmd = ShellCompNoDescRequestCmd14+ }15+ buf.WriteString(fmt.Sprintf("# fish completion for %-36s -*- shell-script -*-\n", name))16+ buf.WriteString(fmt.Sprintf(`17+function __%[1]s_debug18+ set file "$BASH_COMP_DEBUG_FILE"19+ if test -n "$file"20+ echo "$argv" >> $file21+ end22+end23+24+function __%[1]s_perform_completion25+ __%[1]s_debug "Starting __%[1]s_perform_completion with: $argv"26+27+ set args (string split -- " " "$argv")28+ set lastArg "$args[-1]"29+30+ __%[1]s_debug "args: $args"31+ __%[1]s_debug "last arg: $lastArg"32+33+ set emptyArg ""34+ if test -z "$lastArg"35+ __%[1]s_debug "Setting emptyArg"36+ set emptyArg \"\"37+ end38+ __%[1]s_debug "emptyArg: $emptyArg"39+40+ set requestComp "$args[1] %[2]s $args[2..-1] $emptyArg"41+ __%[1]s_debug "Calling $requestComp"42+43+ set results (eval $requestComp 2> /dev/null)44+ set comps $results[1..-2]45+ set directiveLine $results[-1]46+47+ # For Fish, when completing a flag with an = (e.g., <program> -n=<TAB>)48+ # completions must be prefixed with the flag49+ set flagPrefix (string match -r -- '-.*=' "$lastArg")50+51+ __%[1]s_debug "Comps: $comps"52+ __%[1]s_debug "DirectiveLine: $directiveLine"53+ __%[1]s_debug "flagPrefix: $flagPrefix"54+55+ for comp in $comps56+ printf "%%s%%s\n" "$flagPrefix" "$comp"57+ end58+59+ printf "%%s\n" "$directiveLine"60+end61+62+# This function does three things:63+# 1- Obtain the completions and store them in the global __%[1]s_comp_results64+# 2- Set the __%[1]s_comp_do_file_comp flag if file completion should be performed65+# and unset it otherwise66+# 3- Return true if the completion results are not empty67+function __%[1]s_prepare_completions68+ # Start fresh69+ set --erase __%[1]s_comp_do_file_comp70+ set --erase __%[1]s_comp_results71+72+ # Check if the command-line is already provided. This is useful for testing.73+ if not set --query __%[1]s_comp_commandLine74+ set __%[1]s_comp_commandLine (commandline)75+ end76+ __%[1]s_debug "commandLine is: $__%[1]s_comp_commandLine"77+78+ set results (__%[1]s_perform_completion "$__%[1]s_comp_commandLine")79+ set --erase __%[1]s_comp_commandLine80+ __%[1]s_debug "Completion results: $results"81+82+ if test -z "$results"83+ __%[1]s_debug "No completion, probably due to a failure"84+ # Might as well do file completion, in case it helps85+ set --global __%[1]s_comp_do_file_comp 186+ return 087+ end88+89+ set directive (string sub --start 2 $results[-1])90+ set --global __%[1]s_comp_results $results[1..-2]91+92+ __%[1]s_debug "Completions are: $__%[1]s_comp_results"93+ __%[1]s_debug "Directive is: $directive"94+95+ if test -z "$directive"96+ set directive 097+ end98+99+ set compErr (math (math --scale 0 $directive / %[3]d) %% 2)100+ if test $compErr -eq 1101+ __%[1]s_debug "Received error directive: aborting."102+ # Might as well do file completion, in case it helps103+ set --global __%[1]s_comp_do_file_comp 1104+ return 0105+ end106+107+ set nospace (math (math --scale 0 $directive / %[4]d) %% 2)108+ set nofiles (math (math --scale 0 $directive / %[5]d) %% 2)109+110+ __%[1]s_debug "nospace: $nospace, nofiles: $nofiles"111+112+ # Important not to quote the variable for count to work113+ set numComps (count $__%[1]s_comp_results)114+ __%[1]s_debug "numComps: $numComps"115+116+ if test $numComps -eq 1; and test $nospace -ne 0117+ # To support the "nospace" directive we trick the shell118+ # by outputting an extra, longer completion.119+ __%[1]s_debug "Adding second completion to perform nospace directive"120+ set --append __%[1]s_comp_results $__%[1]s_comp_results[1].121+ end122+123+ if test $numComps -eq 0; and test $nofiles -eq 0124+ __%[1]s_debug "Requesting file completion"125+ set --global __%[1]s_comp_do_file_comp 1126+ end127+128+ # If we don't want file completion, we must return true even if there129+ # are no completions found. This is because fish will perform the last130+ # completion command, even if its condition is false, if no other131+ # completion command was triggered132+ return (not set --query __%[1]s_comp_do_file_comp)133+end134+135+# Remove any pre-existing completions for the program since we will be handling all of them136+# TODO this cleanup is not sufficient. Fish completions are only loaded once the user triggers137+# them, so the below deletion will not work as it is run too early. What else can we do?138+complete -c %[1]s -e139+140+# The order in which the below two lines are defined is very important so that __%[1]s_prepare_completions141+# is called first. It is __%[1]s_prepare_completions that sets up the __%[1]s_comp_do_file_comp variable.142+#143+# This completion will be run second as complete commands are added FILO.144+# It triggers file completion choices when __%[1]s_comp_do_file_comp is set.145+complete -c %[1]s -n 'set --query __%[1]s_comp_do_file_comp'146+147+# This completion will be run first as complete commands are added FILO.148+# The call to __%[1]s_prepare_completions will setup both __%[1]s_comp_results abd __%[1]s_comp_do_file_comp.149+# It provides the program's completion choices.150+complete -c %[1]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'151+152+`, name, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp))153+}154+155+// GenFishCompletion generates fish completion file and writes to the passed writer.156+func (c *Command) GenFishCompletion(w io.Writer, includeDesc bool) error {157+ buf := new(bytes.Buffer)158+ genFishComp(buf, c.Name(), includeDesc)159+ _, err := buf.WriteTo(w)160+ return err161+}162+163+// GenFishCompletionFile generates fish completion file.164+func (c *Command) GenFishCompletionFile(filename string, includeDesc bool) error {165+ outFile, err := os.Create(filename)166+ if err != nil {167+ return err168+ }169+ defer outFile.Close()170+171+ return c.GenFishCompletion(outFile, includeDesc)172+}added:fish_completions.md+7 added
1234567## Generating Fish Completions for your own cobra.Command
Cobra supports native Fish completions generated from the root `cobra.Command`. You can use the `command.GenFishCompletion()` or `command.GenFishCompletionFile()` functions. You must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users.
### Limitations
* Custom completions implemented using the `ValidArgsFunction` and `RegisterFlagCompletionFunc()` are supported automatically but the ones implemented in Bash scripting are not.