Skip to content
Myr

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

7 files+552 added−27 removed

modified:args.go+9 added-1 removed
1package cobra23import (4 "fmt"5 "strings"6)78type PositionalArgs func(cmd *Command, args []string) error9
24 unmodified lines
3435// OnlyValidArgs returns an error if any args are not in the list of ValidArgs.36func 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 }4445 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 lines
modified:bash_completions.go+4 added-1 removed
342 unmodified lines
343 fi344 __%[1]s_handle_word345}346347`, name, ShellCompRequestCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp))347`, name, ShellCompNoDescRequestCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp))348}349350func writePostscript(buf *bytes.Buffer, name string) {351 name = strings.Replace(name, ":", "__", -1)
195 unmodified lines
547func 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 lines
modified:bash_completions.md+4 added
113 unmodified lines
114### Dynamic completion of nouns115116In 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.117118**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*.119120#### 1. Custom completions of nouns written in Go121122In 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.123Simplified code from `helm status` looks like:
178 unmodified lines
302# Specify custom flag completion303304As 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.305306**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*.307308## 1. Custom completions of flags written in Go309310To 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 lines
modified:custom_completions_test.go+268 added-22 removed
10 unmodified lines
11 return nil, ShellCompDirectiveNoFileComp12 }1314 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 lines
25 return nil, ShellCompDirectiveNoFileComp26 }2728 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 lines
41 Run: emptyRun,42 }4344 // 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 lines
57 t.Errorf("expected: %q, got: %q", expected, output)58 }5960 // 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 lines
85 Run: emptyRun,86 }8788 // 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 lines
114 }115 rootCmd.AddCommand(child1Cmd, child2Cmd)116117 // 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 lines
130 t.Errorf("expected: %q, got: %q", expected, output)131 }132133 // 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 lines
145 t.Errorf("expected: %q, got: %q", expected, output)146 }147148 // 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 lines
159 t.Errorf("expected: %q, got: %q", expected, output)160 }161162 // 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 lines
174 if output != expected {175 t.Errorf("expected: %q, got: %q", expected, output)176 }177178 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 lines
189 t.Errorf("expected: %q, got: %q", expected, output)190 }191192 // 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 lines
214 }215 rootCmd.AddCommand(child)216217 // 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 lines
230 t.Errorf("expected: %q, got: %q", expected, output)231 }232233 // 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 lines
245 t.Errorf("expected: %q, got: %q", expected, output)246 }247248 // 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 lines
259 t.Errorf("expected: %q, got: %q", expected, output)260 }261}262263func TestValidArgsFuncInScript(t *testing.T) {263func TestValidArgsFuncInBashScript(t *testing.T) {264 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}265 child := &Command{266 Use: "child",267 ValidArgsFunction: validArgsFunc,
7 unmodified lines
275276 check(t, output, "has_completion_function=1")277}278279func TestNoValidArgsFuncInScript(t *testing.T) {279func TestNoValidArgsFuncInBashScript(t *testing.T) {280 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}281 child := &Command{282 Use: "child",283 Run: emptyRun,
6 unmodified lines
290291 checkOmit(t, output, "has_completion_function=1")292}293294func 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)302303 buf := new(bytes.Buffer)304 rootCmd.GenBashCompletion(buf)305 output := buf.String()306307 check(t, output, ShellCompNoDescRequestCmd)308}309310func 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)318319 buf := new(bytes.Buffer)320 rootCmd.GenFishCompletion(buf, false)321 output := buf.String()322323 check(t, output, ShellCompNoDescRequestCmd)324}325326func 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)334335 buf := new(bytes.Buffer)336 rootCmd.GenFishCompletion(buf, true)337 output := buf.String()338339 check(t, output, ShellCompRequestCmd)340 checkOmit(t, output, ShellCompNoDescRequestCmd)341}342343func 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 line
357 })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 })368369 // 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 lines
383 t.Errorf("expected: %q, got: %q", expected, output)384 }385386 // 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 lines
399 t.Errorf("expected: %q, got: %q", expected, output)400 }401402 // 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 lines
416 t.Errorf("expected: %q, got: %q", expected, output)417 }418419 // 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 lines
431 if output != expected {432 t.Errorf("expected: %q, got: %q", expected, output)433 }434}435436func 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)449450 // 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 }455456 expected := strings.Join([]string{457 "one\tThe first",458 "two\tThe second",459 ":0",460 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")461462 if output != expected {463 t.Errorf("expected: %q, got: %q", expected, output)464 }465466 // 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 }471472 expected = strings.Join([]string{473 "two\tThe second",474 ":0",475 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")476477 if output != expected {478 t.Errorf("expected: %q, got: %q", expected, output)479 }480481 // 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 }486487 expected = strings.Join([]string{488 ":4",489 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")490491 if output != expected {492 t.Errorf("expected: %q, got: %q", expected, output)493 }494495 // 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 }500501 expected = strings.Join([]string{502 "three\tThe third",503 "four\tThe fourth",504 ":0",505 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")506507 if output != expected {508 t.Errorf("expected: %q, got: %q", expected, output)509 }510511 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "t")512 if err != nil {513 t.Errorf("Unexpected error: %v", err)514 }515516 expected = strings.Join([]string{517 "three\tThe third",518 ":0",519 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")520521 if output != expected {522 t.Errorf("expected: %q, got: %q", expected, output)523 }524525 // 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 }530531 expected = strings.Join([]string{532 ":4",533 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")534535 if output != expected {536 t.Errorf("expected: %q, got: %q", expected, output)537 }538}539540func 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 })565566 // Test completing an empty string567 output, err := executeCommand(rootCmd, ShellCompRequestCmd, "--introot", "")568 if err != nil {569 t.Errorf("Unexpected error: %v", err)570 }571572 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")578579 if output != expected {580 t.Errorf("expected: %q, got: %q", expected, output)581 }582583 // Check completing with a prefix584 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--introot", "1")585 if err != nil {586 t.Errorf("Unexpected error: %v", err)587 }588589 expected = strings.Join([]string{590 "1\tThe first",591 "10\tThe tenth",592 ":0",593 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")594595 if output != expected {596 t.Errorf("expected: %q, got: %q", expected, output)597 }598599 // Test completing an empty string600 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--filename", "")601 if err != nil {602 t.Errorf("Unexpected error: %v", err)603 }604605 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")611612 if output != expected {613 t.Errorf("expected: %q, got: %q", expected, output)614 }615616 // Check completing with a prefix617 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--filename", "f")618 if err != nil {619 t.Errorf("Unexpected error: %v", err)620 }621622 expected = strings.Join([]string{623 "file.yaml\tYAML format",624 "file.xml\tXML format",625 ":6",626 "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")627628 if output != expected {629 t.Errorf("expected: %q, got: %q", expected, output)630 }631}
modified:custom_completions.go+88 added-3 removed
7 unmodified lines
89 "github.com/spf13/pflag"10)1112const (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.14const 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)2021// Global map of flag completion functions.22var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){}23
57 unmodified lines
81// Adds a special hidden command that can be used to request custom completions.82func (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 lines
98 // 1- There could be some valid completions even though there was an error99 // 2- Even without completions, we need to print the directive100 }101102 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 lines
149 // 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 }152153 // 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 })164165 directive := ShellCompDirectiveDefault166 if len(completions) > 0 {167 if strings.HasSuffix(completions[0], "=") {168 directive = ShellCompDirectiveNoSpace169 }170 }171 return finalCmd, completions, directive, nil172 }173174 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 lines
181 return finalCmd, completions, ShellCompDirectiveDefault, err182 }183 }184185 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 }192193 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 }201202 // 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 }206207 // 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 }211212 // 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 lines
237 completions = append(completions, comps...)238 return finalCmd, completions, directive, nil239}240241func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string {242 if nonCompletableFlag(flag) {243 return []string{}244 }245246 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))251252 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 }258259 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 }263264 return completions265}266267func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) {268 var flagName string269 trimmedArgs := args270 flagWithEqual := false
114 unmodified lines
added:fish_completions.go+172 added
1package cobra23import (4 "bytes"5 "fmt"6 "io"7 "os"8)910func 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(`17function __%[1]s_debug18 set file "$BASH_COMP_DEBUG_FILE"19 if test -n "$file"20 echo "$argv" >> $file21 end22end2324function __%[1]s_perform_completion25 __%[1]s_debug "Starting __%[1]s_perform_completion with: $argv"2627 set args (string split -- " " "$argv")28 set lastArg "$args[-1]"2930 __%[1]s_debug "args: $args"31 __%[1]s_debug "last arg: $lastArg"3233 set emptyArg ""34 if test -z "$lastArg"35 __%[1]s_debug "Setting emptyArg"36 set emptyArg \"\"37 end38 __%[1]s_debug "emptyArg: $emptyArg"3940 set requestComp "$args[1] %[2]s $args[2..-1] $emptyArg"41 __%[1]s_debug "Calling $requestComp"4243 set results (eval $requestComp 2> /dev/null)44 set comps $results[1..-2]45 set directiveLine $results[-1]4647 # 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")5051 __%[1]s_debug "Comps: $comps"52 __%[1]s_debug "DirectiveLine: $directiveLine"53 __%[1]s_debug "flagPrefix: $flagPrefix"5455 for comp in $comps56 printf "%%s%%s\n" "$flagPrefix" "$comp"57 end5859 printf "%%s\n" "$directiveLine"60end6162# 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 empty67function __%[1]s_prepare_completions68 # Start fresh69 set --erase __%[1]s_comp_do_file_comp70 set --erase __%[1]s_comp_results7172 # 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"7778 set results (__%[1]s_perform_completion "$__%[1]s_comp_commandLine")79 set --erase __%[1]s_comp_commandLine80 __%[1]s_debug "Completion results: $results"8182 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 end8889 set directive (string sub --start 2 $results[-1])90 set --global __%[1]s_comp_results $results[1..-2]9192 __%[1]s_debug "Completions are: $__%[1]s_comp_results"93 __%[1]s_debug "Directive is: $directive"9495 if test -z "$directive"96 set directive 097 end9899 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 end106107 set nospace (math (math --scale 0 $directive / %[4]d) %% 2)108 set nofiles (math (math --scale 0 $directive / %[5]d) %% 2)109110 __%[1]s_debug "nospace: $nospace, nofiles: $nofiles"111112 # Important not to quote the variable for count to work113 set numComps (count $__%[1]s_comp_results)114 __%[1]s_debug "numComps: $numComps"115116 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 end122123 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 end127128 # 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)133end134135# 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?138complete -c %[1]s -e139140# 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.145complete -c %[1]s -n 'set --query __%[1]s_comp_do_file_comp'146147# 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.150complete -c %[1]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'151152`, name, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp))153}154155// GenFishCompletion generates fish completion file and writes to the passed writer.156func (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}162163// GenFishCompletionFile generates fish completion file.164func (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()170171 return c.GenFishCompletion(outFile, includeDesc)172}
added:fish_completions.md+7 added