Skip to content
Myr

Create 'completion' command automatically (#1192)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Make it easier for programs to provide shell completion by creating the 'completion' command automatically. If a 'completion' command is already provided by the program, Cobra will use that one instead.

authored by Marc Khouzam · committed by GitHub · parent ded486a · Browse files · 6 files+2923 added−2520 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

6 files+2923 added−2520 removed

  • other:+2923 added−2520 removed

6 files+2923 added−2520 removed

modified:command.go+6 added-2 removed
166 unmodified lines
167168 //FParseErrWhitelist flag parse errors to be ignored169 FParseErrWhitelist FParseErrWhitelist170171 // CompletionOptions is a set of options to control the handling of shell completion172 CompletionOptions CompletionOptions173174 // commandsAreSorted defines, if command slice are sorted or not.175 commandsAreSorted bool176 // commandCalledAs is the name or alias value used to call this command.177 commandCalledAs struct {
738 unmodified lines
916 if preExecHookFn != nil {917 preExecHookFn(c)918 }919917 // initialize help as the last point possible to allow for user918 // overriding920 // initialize help at the last point to allow for user overriding921 c.InitDefaultHelpCmd()922 // initialize completion at the last point to allow for user overriding923 c.initDefaultCompletionCmd()924925 args := c.args926927 // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155
743 unmodified lines
added:completions_test.go+2160 added
1package cobra23import (4 "bytes"5 "strings"6 "testing"7)89func validArgsFunc(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {10 if len(args) != 0 {11 return nil, ShellCompDirectiveNoFileComp12 }1314 var completions []string15 for _, comp := range []string{"one\tThe first", "two\tThe second"} {16 if strings.HasPrefix(comp, toComplete) {17 completions = append(completions, comp)18 }19 }20 return completions, ShellCompDirectiveDefault21}2223func validArgsFunc2(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {24 if len(args) != 0 {25 return nil, ShellCompDirectiveNoFileComp26 }2728 var completions []string29 for _, comp := range []string{"three\tThe third", "four\tThe fourth"} {30 if strings.HasPrefix(comp, toComplete) {31 completions = append(completions, comp)32 }33 }34 return completions, ShellCompDirectiveDefault35}3637func TestCmdNameCompletionInGo(t *testing.T) {38 rootCmd := &Command{39 Use: "root",40 Run: emptyRun,41 }42 childCmd1 := &Command{43 Use: "firstChild",44 Short: "First command",45 Run: emptyRun,46 }47 childCmd2 := &Command{48 Use: "secondChild",49 Run: emptyRun,50 }51 hiddenCmd := &Command{52 Use: "testHidden",53 Hidden: true, // Not completed54 Run: emptyRun,55 }56 deprecatedCmd := &Command{57 Use: "testDeprecated",58 Deprecated: "deprecated", // Not completed59 Run: emptyRun,60 }61 aliasedCmd := &Command{62 Use: "aliased",63 Short: "A command with aliases",64 Aliases: []string{"testAlias", "testSynonym"}, // Not completed65 Run: emptyRun,66 }6768 rootCmd.AddCommand(childCmd1, childCmd2, hiddenCmd, deprecatedCmd, aliasedCmd)6970 // Test that sub-command names are completed71 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")72 if err != nil {73 t.Errorf("Unexpected error: %v", err)74 }7576 expected := strings.Join([]string{77 "aliased",78 "completion",79 "firstChild",80 "help",81 "secondChild",82 ":4",83 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")8485 if output != expected {86 t.Errorf("expected: %q, got: %q", expected, output)87 }8889 // Test that sub-command names are completed with prefix90 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "s")91 if err != nil {92 t.Errorf("Unexpected error: %v", err)93 }9495 expected = strings.Join([]string{96 "secondChild",97 ":4",98 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")99100 if output != expected {101 t.Errorf("expected: %q, got: %q", expected, output)102 }103104 // Test that even with no valid sub-command matches, hidden, deprecated and105 // aliases are not completed106 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "test")107 if err != nil {108 t.Errorf("Unexpected error: %v", err)109 }110111 expected = strings.Join([]string{112 ":4",113 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")114115 if output != expected {116 t.Errorf("expected: %q, got: %q", expected, output)117 }118119 // Test that sub-command names are completed with description120 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "")121 if err != nil {122 t.Errorf("Unexpected error: %v", err)123 }124125 expected = strings.Join([]string{126 "aliased\tA command with aliases",127 "completion\tgenerate the autocompletion script for the specified shell",128 "firstChild\tFirst command",129 "help\tHelp about any command",130 "secondChild",131 ":4",132 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")133134 if output != expected {135 t.Errorf("expected: %q, got: %q", expected, output)136 }137}138139func TestNoCmdNameCompletionInGo(t *testing.T) {140 rootCmd := &Command{141 Use: "root",142 Run: emptyRun,143 }144 rootCmd.Flags().String("localroot", "", "local root flag")145146 childCmd1 := &Command{147 Use: "childCmd1",148 Short: "First command",149 Args: MinimumNArgs(0),150 Run: emptyRun,151 }152 rootCmd.AddCommand(childCmd1)153 childCmd1.PersistentFlags().StringP("persistent", "p", "", "persistent flag")154 persistentFlag := childCmd1.PersistentFlags().Lookup("persistent")155 childCmd1.Flags().StringP("nonPersistent", "n", "", "non-persistent flag")156 nonPersistentFlag := childCmd1.Flags().Lookup("nonPersistent")157158 childCmd2 := &Command{159 Use: "childCmd2",160 Run: emptyRun,161 }162 childCmd1.AddCommand(childCmd2)163164 // Test that sub-command names are not completed if there is an argument already165 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "arg1", "")166 if err != nil {167 t.Errorf("Unexpected error: %v", err)168 }169170 expected := strings.Join([]string{171 ":0",172 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")173174 if output != expected {175 t.Errorf("expected: %q, got: %q", expected, output)176 }177178 // Test that sub-command names are not completed if a local non-persistent flag is present179 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "--nonPersistent", "value", "")180 if err != nil {181 t.Errorf("Unexpected error: %v", err)182 }183 // Reset the flag for the next command184 nonPersistentFlag.Changed = false185186 expected = strings.Join([]string{187 ":0",188 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")189190 if output != expected {191 t.Errorf("expected: %q, got: %q", expected, output)192 }193194 // Test that sub-command names are completed if a local non-persistent flag is present and TraverseChildren is set to true195 // set TraverseChildren to true on the root cmd196 rootCmd.TraverseChildren = true197198 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--localroot", "value", "")199 if err != nil {200 t.Errorf("Unexpected error: %v", err)201 }202 // Reset TraverseChildren for next command203 rootCmd.TraverseChildren = false204205 expected = strings.Join([]string{206 "childCmd1",207 "completion",208 "help",209 ":4",210 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")211212 if output != expected {213 t.Errorf("expected: %q, got: %q", expected, output)214 }215216 // Test that sub-command names from a child cmd are completed if a local non-persistent flag is present217 // and TraverseChildren is set to true on the root cmd218 rootCmd.TraverseChildren = true219220 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--localroot", "value", "childCmd1", "--nonPersistent", "value", "")221 if err != nil {222 t.Errorf("Unexpected error: %v", err)223 }224 // Reset TraverseChildren for next command225 rootCmd.TraverseChildren = false226 // Reset the flag for the next command227 nonPersistentFlag.Changed = false228229 expected = strings.Join([]string{230 "childCmd2",231 ":4",232 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")233234 if output != expected {235 t.Errorf("expected: %q, got: %q", expected, output)236 }237238 // Test that we don't use Traverse when we shouldn't.239 // This command should not return a completion since the command line is invalid without TraverseChildren.240 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--localroot", "value", "childCmd1", "")241 if err != nil {242 t.Errorf("Unexpected error: %v", err)243 }244245 expected = strings.Join([]string{246 ":0",247 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")248249 if output != expected {250 t.Errorf("expected: %q, got: %q", expected, output)251 }252253 // Test that sub-command names are not completed if a local non-persistent short flag is present254 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "-n", "value", "")255 if err != nil {256 t.Errorf("Unexpected error: %v", err)257 }258 // Reset the flag for the next command259 nonPersistentFlag.Changed = false260261 expected = strings.Join([]string{262 ":0",263 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")264265 if output != expected {266 t.Errorf("expected: %q, got: %q", expected, output)267 }268269 // Test that sub-command names are completed with a persistent flag270 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "--persistent", "value", "")271 if err != nil {272 t.Errorf("Unexpected error: %v", err)273 }274 // Reset the flag for the next command275 persistentFlag.Changed = false276277 expected = strings.Join([]string{278 "childCmd2",279 ":4",280 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")281282 if output != expected {283 t.Errorf("expected: %q, got: %q", expected, output)284 }285286 // Test that sub-command names are completed with a persistent short flag287 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "-p", "value", "")288 if err != nil {289 t.Errorf("Unexpected error: %v", err)290 }291 // Reset the flag for the next command292 persistentFlag.Changed = false293294 expected = strings.Join([]string{295 "childCmd2",296 ":4",297 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")298299 if output != expected {300 t.Errorf("expected: %q, got: %q", expected, output)301 }302}303304func TestValidArgsCompletionInGo(t *testing.T) {305 rootCmd := &Command{306 Use: "root",307 ValidArgs: []string{"one", "two", "three"},308 Args: MinimumNArgs(1),309 }310311 // Test that validArgs are completed312 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")313 if err != nil {314 t.Errorf("Unexpected error: %v", err)315 }316317 expected := strings.Join([]string{318 "one",319 "two",320 "three",321 ":4",322 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")323324 if output != expected {325 t.Errorf("expected: %q, got: %q", expected, output)326 }327328 // Test that validArgs are completed with prefix329 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "o")330 if err != nil {331 t.Errorf("Unexpected error: %v", err)332 }333334 expected = strings.Join([]string{335 "one",336 ":4",337 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")338339 if output != expected {340 t.Errorf("expected: %q, got: %q", expected, output)341 }342343 // Test that validArgs don't repeat344 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "one", "")345 if err != nil {346 t.Errorf("Unexpected error: %v", err)347 }348349 expected = strings.Join([]string{350 ":0",351 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")352353 if output != expected {354 t.Errorf("expected: %q, got: %q", expected, output)355 }356}357358func TestValidArgsAndCmdCompletionInGo(t *testing.T) {359 rootCmd := &Command{360 Use: "root",361 ValidArgs: []string{"one", "two"},362 Run: emptyRun,363 }364365 childCmd := &Command{366 Use: "thechild",367 Run: emptyRun,368 }369370 rootCmd.AddCommand(childCmd)371372 // Test that both sub-commands and validArgs are completed373 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")374 if err != nil {375 t.Errorf("Unexpected error: %v", err)376 }377378 expected := strings.Join([]string{379 "completion",380 "help",381 "thechild",382 "one",383 "two",384 ":4",385 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")386387 if output != expected {388 t.Errorf("expected: %q, got: %q", expected, output)389 }390391 // Test that both sub-commands and validArgs are completed with prefix392 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")393 if err != nil {394 t.Errorf("Unexpected error: %v", err)395 }396397 expected = strings.Join([]string{398 "thechild",399 "two",400 ":4",401 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")402403 if output != expected {404 t.Errorf("expected: %q, got: %q", expected, output)405 }406}407408func TestValidArgsFuncAndCmdCompletionInGo(t *testing.T) {409 rootCmd := &Command{410 Use: "root",411 ValidArgsFunction: validArgsFunc,412 Run: emptyRun,413 }414415 childCmd := &Command{416 Use: "thechild",417 Short: "The child command",418 Run: emptyRun,419 }420421 rootCmd.AddCommand(childCmd)422423 // Test that both sub-commands and validArgsFunction are completed424 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")425 if err != nil {426 t.Errorf("Unexpected error: %v", err)427 }428429 expected := strings.Join([]string{430 "completion",431 "help",432 "thechild",433 "one",434 "two",435 ":0",436 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")437438 if output != expected {439 t.Errorf("expected: %q, got: %q", expected, output)440 }441442 // Test that both sub-commands and validArgs are completed with prefix443 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")444 if err != nil {445 t.Errorf("Unexpected error: %v", err)446 }447448 expected = strings.Join([]string{449 "thechild",450 "two",451 ":0",452 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")453454 if output != expected {455 t.Errorf("expected: %q, got: %q", expected, output)456 }457458 // Test that both sub-commands and validArgs are completed with description459 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "t")460 if err != nil {461 t.Errorf("Unexpected error: %v", err)462 }463464 expected = strings.Join([]string{465 "thechild\tThe child command",466 "two\tThe second",467 ":0",468 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")469470 if output != expected {471 t.Errorf("expected: %q, got: %q", expected, output)472 }473}474475func TestFlagNameCompletionInGo(t *testing.T) {476 rootCmd := &Command{477 Use: "root",478 Run: emptyRun,479 }480 childCmd := &Command{481 Use: "childCmd",482 Run: emptyRun,483 }484 rootCmd.AddCommand(childCmd)485486 rootCmd.Flags().IntP("first", "f", -1, "first flag")487 rootCmd.PersistentFlags().BoolP("second", "s", false, "second flag")488 childCmd.Flags().String("subFlag", "", "sub flag")489490 // Test that flag names are not shown if the user has not given the '-' prefix491 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")492 if err != nil {493 t.Errorf("Unexpected error: %v", err)494 }495496 expected := strings.Join([]string{497 "childCmd",498 "completion",499 "help",500 ":4",501 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")502503 if output != expected {504 t.Errorf("expected: %q, got: %q", expected, output)505 }506507 // Test that flag names are completed508 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-")509 if err != nil {510 t.Errorf("Unexpected error: %v", err)511 }512513 expected = strings.Join([]string{514 "--first",515 "-f",516 "--second",517 "-s",518 ":4",519 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")520521 if output != expected {522 t.Errorf("expected: %q, got: %q", expected, output)523 }524525 // Test that flag names are completed when a prefix is given526 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--f")527 if err != nil {528 t.Errorf("Unexpected error: %v", err)529 }530531 expected = strings.Join([]string{532 "--first",533 ":4",534 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")535536 if output != expected {537 t.Errorf("expected: %q, got: %q", expected, output)538 }539540 // Test that flag names are completed in a sub-cmd541 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd", "-")542 if err != nil {543 t.Errorf("Unexpected error: %v", err)544 }545546 expected = strings.Join([]string{547 "--second",548 "-s",549 "--subFlag",550 ":4",551 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")552553 if output != expected {554 t.Errorf("expected: %q, got: %q", expected, output)555 }556}557558func TestFlagNameCompletionInGoWithDesc(t *testing.T) {559 rootCmd := &Command{560 Use: "root",561 Run: emptyRun,562 }563 childCmd := &Command{564 Use: "childCmd",565 Short: "first command",566 Run: emptyRun,567 }568 rootCmd.AddCommand(childCmd)569570 rootCmd.Flags().IntP("first", "f", -1, "first flag\nlonger description for flag")571 rootCmd.PersistentFlags().BoolP("second", "s", false, "second flag")572 childCmd.Flags().String("subFlag", "", "sub flag")573574 // Test that flag names are not shown if the user has not given the '-' prefix575 output, err := executeCommand(rootCmd, ShellCompRequestCmd, "")576 if err != nil {577 t.Errorf("Unexpected error: %v", err)578 }579580 expected := strings.Join([]string{581 "childCmd\tfirst command",582 "completion\tgenerate the autocompletion script for the specified shell",583 "help\tHelp about any command",584 ":4",585 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")586587 if output != expected {588 t.Errorf("expected: %q, got: %q", expected, output)589 }590591 // Test that flag names are completed592 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "-")593 if err != nil {594 t.Errorf("Unexpected error: %v", err)595 }596597 expected = strings.Join([]string{598 "--first\tfirst flag",599 "-f\tfirst flag",600 "--second\tsecond flag",601 "-s\tsecond flag",602 ":4",603 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")604605 if output != expected {606 t.Errorf("expected: %q, got: %q", expected, output)607 }608609 // Test that flag names are completed when a prefix is given610 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--f")611 if err != nil {612 t.Errorf("Unexpected error: %v", err)613 }614615 expected = strings.Join([]string{616 "--first\tfirst flag",617 ":4",618 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")619620 if output != expected {621 t.Errorf("expected: %q, got: %q", expected, output)622 }623624 // Test that flag names are completed in a sub-cmd625 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "childCmd", "-")626 if err != nil {627 t.Errorf("Unexpected error: %v", err)628 }629630 expected = strings.Join([]string{631 "--second\tsecond flag",632 "-s\tsecond flag",633 "--subFlag\tsub flag",634 ":4",635 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")636637 if output != expected {638 t.Errorf("expected: %q, got: %q", expected, output)639 }640}641642func TestFlagNameCompletionRepeat(t *testing.T) {643 rootCmd := &Command{644 Use: "root",645 Run: emptyRun,646 }647 childCmd := &Command{648 Use: "childCmd",649 Short: "first command",650 Run: emptyRun,651 }652 rootCmd.AddCommand(childCmd)653654 rootCmd.Flags().IntP("first", "f", -1, "first flag")655 firstFlag := rootCmd.Flags().Lookup("first")656 rootCmd.Flags().BoolP("second", "s", false, "second flag")657 secondFlag := rootCmd.Flags().Lookup("second")658 rootCmd.Flags().StringArrayP("array", "a", nil, "array flag")659 arrayFlag := rootCmd.Flags().Lookup("array")660 rootCmd.Flags().IntSliceP("slice", "l", nil, "slice flag")661 sliceFlag := rootCmd.Flags().Lookup("slice")662 rootCmd.Flags().BoolSliceP("bslice", "b", nil, "bool slice flag")663 bsliceFlag := rootCmd.Flags().Lookup("bslice")664665 // Test that flag names are not repeated unless they are an array or slice666 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--first", "1", "--")667 if err != nil {668 t.Errorf("Unexpected error: %v", err)669 }670 // Reset the flag for the next command671 firstFlag.Changed = false672673 expected := strings.Join([]string{674 "--array",675 "--bslice",676 "--second",677 "--slice",678 ":4",679 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")680681 if output != expected {682 t.Errorf("expected: %q, got: %q", expected, output)683 }684685 // Test that flag names are not repeated unless they are an array or slice686 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--first", "1", "--second=false", "--")687 if err != nil {688 t.Errorf("Unexpected error: %v", err)689 }690 // Reset the flag for the next command691 firstFlag.Changed = false692 secondFlag.Changed = false693694 expected = strings.Join([]string{695 "--array",696 "--bslice",697 "--slice",698 ":4",699 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")700701 if output != expected {702 t.Errorf("expected: %q, got: %q", expected, output)703 }704705 // Test that flag names are not repeated unless they are an array or slice706 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--slice", "1", "--slice=2", "--array", "val", "--bslice", "true", "--")707 if err != nil {708 t.Errorf("Unexpected error: %v", err)709 }710 // Reset the flag for the next command711 sliceFlag.Changed = false712 arrayFlag.Changed = false713 bsliceFlag.Changed = false714715 expected = strings.Join([]string{716 "--array",717 "--bslice",718 "--first",719 "--second",720 "--slice",721 ":4",722 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")723724 if output != expected {725 t.Errorf("expected: %q, got: %q", expected, output)726 }727728 // Test that flag names are not repeated unless they are an array or slice, using shortname729 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-l", "1", "-l=2", "-a", "val", "-")730 if err != nil {731 t.Errorf("Unexpected error: %v", err)732 }733 // Reset the flag for the next command734 sliceFlag.Changed = false735 arrayFlag.Changed = false736737 expected = strings.Join([]string{738 "--array",739 "-a",740 "--bslice",741 "-b",742 "--first",743 "-f",744 "--second",745 "-s",746 "--slice",747 "-l",748 ":4",749 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")750751 if output != expected {752 t.Errorf("expected: %q, got: %q", expected, output)753 }754755 // Test that flag names are not repeated unless they are an array or slice, using shortname with prefix756 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-l", "1", "-l=2", "-a", "val", "-a")757 if err != nil {758 t.Errorf("Unexpected error: %v", err)759 }760 // Reset the flag for the next command761 sliceFlag.Changed = false762 arrayFlag.Changed = false763764 expected = strings.Join([]string{765 "-a",766 ":4",767 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")768769 if output != expected {770 t.Errorf("expected: %q, got: %q", expected, output)771 }772}773774func TestRequiredFlagNameCompletionInGo(t *testing.T) {775 rootCmd := &Command{776 Use: "root",777 ValidArgs: []string{"realArg"},778 Run: emptyRun,779 }780 childCmd := &Command{781 Use: "childCmd",782 ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {783 return []string{"subArg"}, ShellCompDirectiveNoFileComp784 },785 Run: emptyRun,786 }787 rootCmd.AddCommand(childCmd)788789 rootCmd.Flags().IntP("requiredFlag", "r", -1, "required flag")790 assertNoErr(t, rootCmd.MarkFlagRequired("requiredFlag"))791 requiredFlag := rootCmd.Flags().Lookup("requiredFlag")792793 rootCmd.PersistentFlags().IntP("requiredPersistent", "p", -1, "required persistent")794 assertNoErr(t, rootCmd.MarkPersistentFlagRequired("requiredPersistent"))795 requiredPersistent := rootCmd.PersistentFlags().Lookup("requiredPersistent")796797 rootCmd.Flags().StringP("release", "R", "", "Release name")798799 childCmd.Flags().BoolP("subRequired", "s", false, "sub required flag")800 assertNoErr(t, childCmd.MarkFlagRequired("subRequired"))801 childCmd.Flags().BoolP("subNotRequired", "n", false, "sub not required flag")802803 // Test that a required flag is suggested even without the - prefix804 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")805 if err != nil {806 t.Errorf("Unexpected error: %v", err)807 }808809 expected := strings.Join([]string{810 "childCmd",811 "completion",812 "help",813 "--requiredFlag",814 "-r",815 "--requiredPersistent",816 "-p",817 "realArg",818 ":4",819 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")820821 if output != expected {822 t.Errorf("expected: %q, got: %q", expected, output)823 }824825 // Test that a required flag is suggested without other flags when using the '-' prefix826 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-")827 if err != nil {828 t.Errorf("Unexpected error: %v", err)829 }830831 expected = strings.Join([]string{832 "--requiredFlag",833 "-r",834 "--requiredPersistent",835 "-p",836 ":4",837 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")838839 if output != expected {840 t.Errorf("expected: %q, got: %q", expected, output)841 }842843 // Test that if no required flag matches, the normal flags are suggested844 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--relea")845 if err != nil {846 t.Errorf("Unexpected error: %v", err)847 }848849 expected = strings.Join([]string{850 "--release",851 ":4",852 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")853854 if output != expected {855 t.Errorf("expected: %q, got: %q", expected, output)856 }857858 // Test required flags for sub-commands859 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd", "")860 if err != nil {861 t.Errorf("Unexpected error: %v", err)862 }863864 expected = strings.Join([]string{865 "--requiredPersistent",866 "-p",867 "--subRequired",868 "-s",869 "subArg",870 ":4",871 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")872873 if output != expected {874 t.Errorf("expected: %q, got: %q", expected, output)875 }876877 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd", "-")878 if err != nil {879 t.Errorf("Unexpected error: %v", err)880 }881882 expected = strings.Join([]string{883 "--requiredPersistent",884 "-p",885 "--subRequired",886 "-s",887 ":4",888 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")889890 if output != expected {891 t.Errorf("expected: %q, got: %q", expected, output)892 }893894 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd", "--subNot")895 if err != nil {896 t.Errorf("Unexpected error: %v", err)897 }898899 expected = strings.Join([]string{900 "--subNotRequired",901 ":4",902 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")903904 if output != expected {905 t.Errorf("expected: %q, got: %q", expected, output)906 }907908 // Test that when a required flag is present, it is not suggested anymore909 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--requiredFlag", "1", "")910 if err != nil {911 t.Errorf("Unexpected error: %v", err)912 }913 // Reset the flag for the next command914 requiredFlag.Changed = false915916 expected = strings.Join([]string{917 "--requiredPersistent",918 "-p",919 "realArg",920 ":4",921 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")922923 if output != expected {924 t.Errorf("expected: %q, got: %q", expected, output)925 }926927 // Test that when a persistent required flag is present, it is not suggested anymore928 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--requiredPersistent", "1", "")929 if err != nil {930 t.Errorf("Unexpected error: %v", err)931 }932 // Reset the flag for the next command933 requiredPersistent.Changed = false934935 expected = strings.Join([]string{936 "childCmd",937 "completion",938 "help",939 "--requiredFlag",940 "-r",941 "realArg",942 ":4",943 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")944945 if output != expected {946 t.Errorf("expected: %q, got: %q", expected, output)947 }948949 // Test that when all required flags are present, normal completion is done950 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--requiredFlag", "1", "--requiredPersistent", "1", "")951 if err != nil {952 t.Errorf("Unexpected error: %v", err)953 }954 // Reset the flags for the next command955 requiredFlag.Changed = false956 requiredPersistent.Changed = false957958 expected = strings.Join([]string{959 "realArg",960 ":4",961 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")962963 if output != expected {964 t.Errorf("expected: %q, got: %q", expected, output)965 }966}967968func TestFlagFileExtFilterCompletionInGo(t *testing.T) {969 rootCmd := &Command{970 Use: "root",971 Run: emptyRun,972 }973974 // No extensions. Should be ignored.975 rootCmd.Flags().StringP("file", "f", "", "file flag")976 assertNoErr(t, rootCmd.MarkFlagFilename("file"))977978 // Single extension979 rootCmd.Flags().StringP("log", "l", "", "log flag")980 assertNoErr(t, rootCmd.MarkFlagFilename("log", "log"))981982 // Multiple extensions983 rootCmd.Flags().StringP("yaml", "y", "", "yaml flag")984 assertNoErr(t, rootCmd.MarkFlagFilename("yaml", "yaml", "yml"))985986 // Directly using annotation987 rootCmd.Flags().StringP("text", "t", "", "text flag")988 assertNoErr(t, rootCmd.Flags().SetAnnotation("text", BashCompFilenameExt, []string{"txt"}))989990 // Test that the completion logic returns the proper info for the completion991 // script to handle the file filtering992 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--file", "")993 if err != nil {994 t.Errorf("Unexpected error: %v", err)995 }996997 expected := strings.Join([]string{998 ":0",999 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")10001001 if output != expected {1002 t.Errorf("expected: %q, got: %q", expected, output)1003 }10041005 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--log", "")1006 if err != nil {1007 t.Errorf("Unexpected error: %v", err)1008 }10091010 expected = strings.Join([]string{1011 "log",1012 ":8",1013 "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")10141015 if output != expected {1016 t.Errorf("expected: %q, got: %q", expected, output)1017 }10181019 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--yaml", "")1020 if err != nil {1021 t.Errorf("Unexpected error: %v", err)1022 }10231024 expected = strings.Join([]string{1025 "yaml", "yml",1026 ":8",1027 "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")10281029 if output != expected {1030 t.Errorf("expected: %q, got: %q", expected, output)1031 }10321033 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--yaml=")1034 if err != nil {1035 t.Errorf("Unexpected error: %v", err)1036 }10371038 expected = strings.Join([]string{1039 "yaml", "yml",1040 ":8",1041 "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")10421043 if output != expected {1044 t.Errorf("expected: %q, got: %q", expected, output)1045 }10461047 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-y", "")1048 if err != nil {1049 t.Errorf("Unexpected error: %v", err)1050 }10511052 expected = strings.Join([]string{1053 "yaml", "yml",1054 ":8",1055 "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")10561057 if output != expected {1058 t.Errorf("expected: %q, got: %q", expected, output)1059 }10601061 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-y=")1062 if err != nil {1063 t.Errorf("Unexpected error: %v", err)1064 }10651066 expected = strings.Join([]string{1067 "yaml", "yml",1068 ":8",1069 "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")10701071 if output != expected {1072 t.Errorf("expected: %q, got: %q", expected, output)1073 }10741075 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--text", "")1076 if err != nil {1077 t.Errorf("Unexpected error: %v", err)1078 }10791080 expected = strings.Join([]string{1081 "txt",1082 ":8",1083 "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")10841085 if output != expected {1086 t.Errorf("expected: %q, got: %q", expected, output)1087 }1088}10891090func TestFlagDirFilterCompletionInGo(t *testing.T) {1091 rootCmd := &Command{1092 Use: "root",1093 Run: emptyRun,1094 }10951096 // Filter directories1097 rootCmd.Flags().StringP("dir", "d", "", "dir flag")1098 assertNoErr(t, rootCmd.MarkFlagDirname("dir"))10991100 // Filter directories within a directory1101 rootCmd.Flags().StringP("subdir", "s", "", "subdir")1102 assertNoErr(t, rootCmd.Flags().SetAnnotation("subdir", BashCompSubdirsInDir, []string{"themes"}))11031104 // Multiple directory specification get ignored1105 rootCmd.Flags().StringP("manydir", "m", "", "manydir")1106 assertNoErr(t, rootCmd.Flags().SetAnnotation("manydir", BashCompSubdirsInDir, []string{"themes", "colors"}))11071108 // Test that the completion logic returns the proper info for the completion1109 // script to handle the directory filtering1110 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--dir", "")1111 if err != nil {1112 t.Errorf("Unexpected error: %v", err)1113 }11141115 expected := strings.Join([]string{1116 ":16",1117 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")11181119 if output != expected {1120 t.Errorf("expected: %q, got: %q", expected, output)1121 }11221123 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-d", "")1124 if err != nil {1125 t.Errorf("Unexpected error: %v", err)1126 }11271128 expected = strings.Join([]string{1129 ":16",1130 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")11311132 if output != expected {1133 t.Errorf("expected: %q, got: %q", expected, output)1134 }11351136 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--subdir", "")1137 if err != nil {1138 t.Errorf("Unexpected error: %v", err)1139 }11401141 expected = strings.Join([]string{1142 "themes",1143 ":16",1144 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")11451146 if output != expected {1147 t.Errorf("expected: %q, got: %q", expected, output)1148 }11491150 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--subdir=")1151 if err != nil {1152 t.Errorf("Unexpected error: %v", err)1153 }11541155 expected = strings.Join([]string{1156 "themes",1157 ":16",1158 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")11591160 if output != expected {1161 t.Errorf("expected: %q, got: %q", expected, output)1162 }11631164 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-s", "")1165 if err != nil {1166 t.Errorf("Unexpected error: %v", err)1167 }11681169 expected = strings.Join([]string{1170 "themes",1171 ":16",1172 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")11731174 if output != expected {1175 t.Errorf("expected: %q, got: %q", expected, output)1176 }11771178 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-s=")1179 if err != nil {1180 t.Errorf("Unexpected error: %v", err)1181 }11821183 expected = strings.Join([]string{1184 "themes",1185 ":16",1186 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")11871188 if output != expected {1189 t.Errorf("expected: %q, got: %q", expected, output)1190 }11911192 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--manydir", "")1193 if err != nil {1194 t.Errorf("Unexpected error: %v", err)1195 }11961197 expected = strings.Join([]string{1198 ":16",1199 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")12001201 if output != expected {1202 t.Errorf("expected: %q, got: %q", expected, output)1203 }1204}12051206func TestValidArgsFuncSingleCmd(t *testing.T) {1207 rootCmd := &Command{1208 Use: "root",1209 ValidArgsFunction: validArgsFunc,1210 Run: emptyRun,1211 }12121213 // Test completing an empty string1214 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")1215 if err != nil {1216 t.Errorf("Unexpected error: %v", err)1217 }12181219 expected := strings.Join([]string{1220 "one",1221 "two",1222 ":0",1223 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")12241225 if output != expected {1226 t.Errorf("expected: %q, got: %q", expected, output)1227 }12281229 // Check completing with a prefix1230 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")1231 if err != nil {1232 t.Errorf("Unexpected error: %v", err)1233 }12341235 expected = strings.Join([]string{1236 "two",1237 ":0",1238 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")12391240 if output != expected {1241 t.Errorf("expected: %q, got: %q", expected, output)1242 }1243}12441245func TestValidArgsFuncSingleCmdInvalidArg(t *testing.T) {1246 rootCmd := &Command{1247 Use: "root",1248 // If we don't specify a value for Args, this test fails.1249 // This is only true for a root command without any subcommands, and is caused1250 // by the fact that the __complete command becomes a subcommand when there should not be one.1251 // The problem is in the implementation of legacyArgs().1252 Args: MinimumNArgs(1),1253 ValidArgsFunction: validArgsFunc,1254 Run: emptyRun,1255 }12561257 // Check completing with wrong number of args1258 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "unexpectedArg", "t")1259 if err != nil {1260 t.Errorf("Unexpected error: %v", err)1261 }12621263 expected := strings.Join([]string{1264 ":4",1265 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")12661267 if output != expected {1268 t.Errorf("expected: %q, got: %q", expected, output)1269 }1270}12711272func TestValidArgsFuncChildCmds(t *testing.T) {1273 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1274 child1Cmd := &Command{1275 Use: "child1",1276 ValidArgsFunction: validArgsFunc,1277 Run: emptyRun,1278 }1279 child2Cmd := &Command{1280 Use: "child2",1281 ValidArgsFunction: validArgsFunc2,1282 Run: emptyRun,1283 }1284 rootCmd.AddCommand(child1Cmd, child2Cmd)12851286 // Test completion of first sub-command with empty argument1287 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child1", "")1288 if err != nil {1289 t.Errorf("Unexpected error: %v", err)1290 }12911292 expected := strings.Join([]string{1293 "one",1294 "two",1295 ":0",1296 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")12971298 if output != expected {1299 t.Errorf("expected: %q, got: %q", expected, output)1300 }13011302 // Test completion of first sub-command with a prefix to complete1303 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child1", "t")1304 if err != nil {1305 t.Errorf("Unexpected error: %v", err)1306 }13071308 expected = strings.Join([]string{1309 "two",1310 ":0",1311 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")13121313 if output != expected {1314 t.Errorf("expected: %q, got: %q", expected, output)1315 }13161317 // Check completing with wrong number of args1318 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child1", "unexpectedArg", "t")1319 if err != nil {1320 t.Errorf("Unexpected error: %v", err)1321 }13221323 expected = strings.Join([]string{1324 ":4",1325 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")13261327 if output != expected {1328 t.Errorf("expected: %q, got: %q", expected, output)1329 }13301331 // Test completion of second sub-command with empty argument1332 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child2", "")1333 if err != nil {1334 t.Errorf("Unexpected error: %v", err)1335 }13361337 expected = strings.Join([]string{1338 "three",1339 "four",1340 ":0",1341 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")13421343 if output != expected {1344 t.Errorf("expected: %q, got: %q", expected, output)1345 }13461347 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child2", "t")1348 if err != nil {1349 t.Errorf("Unexpected error: %v", err)1350 }13511352 expected = strings.Join([]string{1353 "three",1354 ":0",1355 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")13561357 if output != expected {1358 t.Errorf("expected: %q, got: %q", expected, output)1359 }13601361 // Check completing with wrong number of args1362 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child2", "unexpectedArg", "t")1363 if err != nil {1364 t.Errorf("Unexpected error: %v", err)1365 }13661367 expected = strings.Join([]string{1368 ":4",1369 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")13701371 if output != expected {1372 t.Errorf("expected: %q, got: %q", expected, output)1373 }1374}13751376func TestValidArgsFuncAliases(t *testing.T) {1377 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1378 child := &Command{1379 Use: "child",1380 Aliases: []string{"son", "daughter"},1381 ValidArgsFunction: validArgsFunc,1382 Run: emptyRun,1383 }1384 rootCmd.AddCommand(child)13851386 // Test completion of first sub-command with empty argument1387 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "son", "")1388 if err != nil {1389 t.Errorf("Unexpected error: %v", err)1390 }13911392 expected := strings.Join([]string{1393 "one",1394 "two",1395 ":0",1396 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")13971398 if output != expected {1399 t.Errorf("expected: %q, got: %q", expected, output)1400 }14011402 // Test completion of first sub-command with a prefix to complete1403 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "daughter", "t")1404 if err != nil {1405 t.Errorf("Unexpected error: %v", err)1406 }14071408 expected = strings.Join([]string{1409 "two",1410 ":0",1411 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")14121413 if output != expected {1414 t.Errorf("expected: %q, got: %q", expected, output)1415 }14161417 // Check completing with wrong number of args1418 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "son", "unexpectedArg", "t")1419 if err != nil {1420 t.Errorf("Unexpected error: %v", err)1421 }14221423 expected = strings.Join([]string{1424 ":4",1425 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")14261427 if output != expected {1428 t.Errorf("expected: %q, got: %q", expected, output)1429 }1430}14311432func TestValidArgsFuncInBashScript(t *testing.T) {1433 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1434 child := &Command{1435 Use: "child",1436 ValidArgsFunction: validArgsFunc,1437 Run: emptyRun,1438 }1439 rootCmd.AddCommand(child)14401441 buf := new(bytes.Buffer)1442 assertNoErr(t, rootCmd.GenBashCompletion(buf))1443 output := buf.String()14441445 check(t, output, "has_completion_function=1")1446}14471448func TestNoValidArgsFuncInBashScript(t *testing.T) {1449 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1450 child := &Command{1451 Use: "child",1452 Run: emptyRun,1453 }1454 rootCmd.AddCommand(child)14551456 buf := new(bytes.Buffer)1457 assertNoErr(t, rootCmd.GenBashCompletion(buf))1458 output := buf.String()14591460 checkOmit(t, output, "has_completion_function=1")1461}14621463func TestCompleteCmdInBashScript(t *testing.T) {1464 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1465 child := &Command{1466 Use: "child",1467 ValidArgsFunction: validArgsFunc,1468 Run: emptyRun,1469 }1470 rootCmd.AddCommand(child)14711472 buf := new(bytes.Buffer)1473 assertNoErr(t, rootCmd.GenBashCompletion(buf))1474 output := buf.String()14751476 check(t, output, ShellCompNoDescRequestCmd)1477}14781479func TestCompleteNoDesCmdInZshScript(t *testing.T) {1480 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1481 child := &Command{1482 Use: "child",1483 ValidArgsFunction: validArgsFunc,1484 Run: emptyRun,1485 }1486 rootCmd.AddCommand(child)14871488 buf := new(bytes.Buffer)1489 assertNoErr(t, rootCmd.GenZshCompletionNoDesc(buf))1490 output := buf.String()14911492 check(t, output, ShellCompNoDescRequestCmd)1493}14941495func TestCompleteCmdInZshScript(t *testing.T) {1496 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1497 child := &Command{1498 Use: "child",1499 ValidArgsFunction: validArgsFunc,1500 Run: emptyRun,1501 }1502 rootCmd.AddCommand(child)15031504 buf := new(bytes.Buffer)1505 assertNoErr(t, rootCmd.GenZshCompletion(buf))1506 output := buf.String()15071508 check(t, output, ShellCompRequestCmd)1509 checkOmit(t, output, ShellCompNoDescRequestCmd)1510}15111512func TestFlagCompletionInGo(t *testing.T) {1513 rootCmd := &Command{1514 Use: "root",1515 Run: emptyRun,1516 }1517 rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")1518 assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1519 completions := []string{}1520 for _, comp := range []string{"1\tThe first", "2\tThe second", "10\tThe tenth"} {1521 if strings.HasPrefix(comp, toComplete) {1522 completions = append(completions, comp)1523 }1524 }1525 return completions, ShellCompDirectiveDefault1526 }))1527 rootCmd.Flags().String("filename", "", "Enter a filename")1528 assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1529 completions := []string{}1530 for _, comp := range []string{"file.yaml\tYAML format", "myfile.json\tJSON format", "file.xml\tXML format"} {1531 if strings.HasPrefix(comp, toComplete) {1532 completions = append(completions, comp)1533 }1534 }1535 return completions, ShellCompDirectiveNoSpace | ShellCompDirectiveNoFileComp1536 }))15371538 // Test completing an empty string1539 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--introot", "")1540 if err != nil {1541 t.Errorf("Unexpected error: %v", err)1542 }15431544 expected := strings.Join([]string{1545 "1",1546 "2",1547 "10",1548 ":0",1549 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")15501551 if output != expected {1552 t.Errorf("expected: %q, got: %q", expected, output)1553 }15541555 // Check completing with a prefix1556 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--introot", "1")1557 if err != nil {1558 t.Errorf("Unexpected error: %v", err)1559 }15601561 expected = strings.Join([]string{1562 "1",1563 "10",1564 ":0",1565 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")15661567 if output != expected {1568 t.Errorf("expected: %q, got: %q", expected, output)1569 }15701571 // Test completing an empty string1572 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--filename", "")1573 if err != nil {1574 t.Errorf("Unexpected error: %v", err)1575 }15761577 expected = strings.Join([]string{1578 "file.yaml",1579 "myfile.json",1580 "file.xml",1581 ":6",1582 "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")15831584 if output != expected {1585 t.Errorf("expected: %q, got: %q", expected, output)1586 }15871588 // Check completing with a prefix1589 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--filename", "f")1590 if err != nil {1591 t.Errorf("Unexpected error: %v", err)1592 }15931594 expected = strings.Join([]string{1595 "file.yaml",1596 "file.xml",1597 ":6",1598 "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")15991600 if output != expected {1601 t.Errorf("expected: %q, got: %q", expected, output)1602 }1603}16041605func TestValidArgsFuncChildCmdsWithDesc(t *testing.T) {1606 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1607 child1Cmd := &Command{1608 Use: "child1",1609 ValidArgsFunction: validArgsFunc,1610 Run: emptyRun,1611 }1612 child2Cmd := &Command{1613 Use: "child2",1614 ValidArgsFunction: validArgsFunc2,1615 Run: emptyRun,1616 }1617 rootCmd.AddCommand(child1Cmd, child2Cmd)16181619 // Test completion of first sub-command with empty argument1620 output, err := executeCommand(rootCmd, ShellCompRequestCmd, "child1", "")1621 if err != nil {1622 t.Errorf("Unexpected error: %v", err)1623 }16241625 expected := strings.Join([]string{1626 "one\tThe first",1627 "two\tThe second",1628 ":0",1629 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")16301631 if output != expected {1632 t.Errorf("expected: %q, got: %q", expected, output)1633 }16341635 // Test completion of first sub-command with a prefix to complete1636 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child1", "t")1637 if err != nil {1638 t.Errorf("Unexpected error: %v", err)1639 }16401641 expected = strings.Join([]string{1642 "two\tThe second",1643 ":0",1644 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")16451646 if output != expected {1647 t.Errorf("expected: %q, got: %q", expected, output)1648 }16491650 // Check completing with wrong number of args1651 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child1", "unexpectedArg", "t")1652 if err != nil {1653 t.Errorf("Unexpected error: %v", err)1654 }16551656 expected = strings.Join([]string{1657 ":4",1658 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")16591660 if output != expected {1661 t.Errorf("expected: %q, got: %q", expected, output)1662 }16631664 // Test completion of second sub-command with empty argument1665 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "")1666 if err != nil {1667 t.Errorf("Unexpected error: %v", err)1668 }16691670 expected = strings.Join([]string{1671 "three\tThe third",1672 "four\tThe fourth",1673 ":0",1674 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")16751676 if output != expected {1677 t.Errorf("expected: %q, got: %q", expected, output)1678 }16791680 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "t")1681 if err != nil {1682 t.Errorf("Unexpected error: %v", err)1683 }16841685 expected = strings.Join([]string{1686 "three\tThe third",1687 ":0",1688 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")16891690 if output != expected {1691 t.Errorf("expected: %q, got: %q", expected, output)1692 }16931694 // Check completing with wrong number of args1695 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "unexpectedArg", "t")1696 if err != nil {1697 t.Errorf("Unexpected error: %v", err)1698 }16991700 expected = strings.Join([]string{1701 ":4",1702 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")17031704 if output != expected {1705 t.Errorf("expected: %q, got: %q", expected, output)1706 }1707}17081709func TestFlagCompletionInGoWithDesc(t *testing.T) {1710 rootCmd := &Command{1711 Use: "root",1712 Run: emptyRun,1713 }1714 rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")1715 assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1716 completions := []string{}1717 for _, comp := range []string{"1\tThe first", "2\tThe second", "10\tThe tenth"} {1718 if strings.HasPrefix(comp, toComplete) {1719 completions = append(completions, comp)1720 }1721 }1722 return completions, ShellCompDirectiveDefault1723 }))1724 rootCmd.Flags().String("filename", "", "Enter a filename")1725 assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1726 completions := []string{}1727 for _, comp := range []string{"file.yaml\tYAML format", "myfile.json\tJSON format", "file.xml\tXML format"} {1728 if strings.HasPrefix(comp, toComplete) {1729 completions = append(completions, comp)1730 }1731 }1732 return completions, ShellCompDirectiveNoSpace | ShellCompDirectiveNoFileComp1733 }))17341735 // Test completing an empty string1736 output, err := executeCommand(rootCmd, ShellCompRequestCmd, "--introot", "")1737 if err != nil {1738 t.Errorf("Unexpected error: %v", err)1739 }17401741 expected := strings.Join([]string{1742 "1\tThe first",1743 "2\tThe second",1744 "10\tThe tenth",1745 ":0",1746 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")17471748 if output != expected {1749 t.Errorf("expected: %q, got: %q", expected, output)1750 }17511752 // Check completing with a prefix1753 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--introot", "1")1754 if err != nil {1755 t.Errorf("Unexpected error: %v", err)1756 }17571758 expected = strings.Join([]string{1759 "1\tThe first",1760 "10\tThe tenth",1761 ":0",1762 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")17631764 if output != expected {1765 t.Errorf("expected: %q, got: %q", expected, output)1766 }17671768 // Test completing an empty string1769 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--filename", "")1770 if err != nil {1771 t.Errorf("Unexpected error: %v", err)1772 }17731774 expected = strings.Join([]string{1775 "file.yaml\tYAML format",1776 "myfile.json\tJSON format",1777 "file.xml\tXML format",1778 ":6",1779 "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")17801781 if output != expected {1782 t.Errorf("expected: %q, got: %q", expected, output)1783 }17841785 // Check completing with a prefix1786 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--filename", "f")1787 if err != nil {1788 t.Errorf("Unexpected error: %v", err)1789 }17901791 expected = strings.Join([]string{1792 "file.yaml\tYAML format",1793 "file.xml\tXML format",1794 ":6",1795 "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")17961797 if output != expected {1798 t.Errorf("expected: %q, got: %q", expected, output)1799 }1800}18011802func TestValidArgsNotValidArgsFunc(t *testing.T) {1803 rootCmd := &Command{1804 Use: "root",1805 ValidArgs: []string{"one", "two"},1806 ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1807 return []string{"three", "four"}, ShellCompDirectiveNoFileComp1808 },1809 Run: emptyRun,1810 }18111812 // Test that if both ValidArgs and ValidArgsFunction are present1813 // only ValidArgs is considered1814 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")1815 if err != nil {1816 t.Errorf("Unexpected error: %v", err)1817 }18181819 expected := strings.Join([]string{1820 "one",1821 "two",1822 ":4",1823 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")18241825 if output != expected {1826 t.Errorf("expected: %q, got: %q", expected, output)1827 }18281829 // Check completing with a prefix1830 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")1831 if err != nil {1832 t.Errorf("Unexpected error: %v", err)1833 }18341835 expected = strings.Join([]string{1836 "two",1837 ":4",1838 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")18391840 if output != expected {1841 t.Errorf("expected: %q, got: %q", expected, output)1842 }1843}18441845func TestArgAliasesCompletionInGo(t *testing.T) {1846 rootCmd := &Command{1847 Use: "root",1848 Args: OnlyValidArgs,1849 ValidArgs: []string{"one", "two", "three"},1850 ArgAliases: []string{"un", "deux", "trois"},1851 Run: emptyRun,1852 }18531854 // Test that argaliases are not completed when there are validargs that match1855 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")1856 if err != nil {1857 t.Errorf("Unexpected error: %v", err)1858 }18591860 expected := strings.Join([]string{1861 "one",1862 "two",1863 "three",1864 ":4",1865 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")18661867 if output != expected {1868 t.Errorf("expected: %q, got: %q", expected, output)1869 }18701871 // Test that argaliases are not completed when there are validargs that match using a prefix1872 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")1873 if err != nil {1874 t.Errorf("Unexpected error: %v", err)1875 }18761877 expected = strings.Join([]string{1878 "two",1879 "three",1880 ":4",1881 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")18821883 if output != expected {1884 t.Errorf("expected: %q, got: %q", expected, output)1885 }18861887 // Test that argaliases are completed when there are no validargs that match1888 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "tr")1889 if err != nil {1890 t.Errorf("Unexpected error: %v", err)1891 }18921893 expected = strings.Join([]string{1894 "trois",1895 ":4",1896 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")18971898 if output != expected {1899 t.Errorf("expected: %q, got: %q", expected, output)1900 }1901}19021903func TestCompleteHelp(t *testing.T) {1904 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1905 child1Cmd := &Command{1906 Use: "child1",1907 Run: emptyRun,1908 }1909 child2Cmd := &Command{1910 Use: "child2",1911 Run: emptyRun,1912 }1913 rootCmd.AddCommand(child1Cmd, child2Cmd)19141915 child3Cmd := &Command{1916 Use: "child3",1917 Run: emptyRun,1918 }1919 child1Cmd.AddCommand(child3Cmd)19201921 // Test that completion includes the help command1922 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")1923 if err != nil {1924 t.Errorf("Unexpected error: %v", err)1925 }19261927 expected := strings.Join([]string{1928 "child1",1929 "child2",1930 "completion",1931 "help",1932 ":4",1933 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")19341935 if output != expected {1936 t.Errorf("expected: %q, got: %q", expected, output)1937 }19381939 // Test sub-commands are completed on first level of help command1940 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "help", "")1941 if err != nil {1942 t.Errorf("Unexpected error: %v", err)1943 }19441945 expected = strings.Join([]string{1946 "child1",1947 "child2",1948 "completion",1949 "help", // "<program> help help" is a valid command, so should be completed1950 ":4",1951 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")19521953 if output != expected {1954 t.Errorf("expected: %q, got: %q", expected, output)1955 }19561957 // Test sub-commands are completed on first level of help command1958 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "help", "child1", "")1959 if err != nil {1960 t.Errorf("Unexpected error: %v", err)1961 }19621963 expected = strings.Join([]string{1964 "child3",1965 ":4",1966 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")19671968 if output != expected {1969 t.Errorf("expected: %q, got: %q", expected, output)1970 }1971}19721973func removeCompCmd(rootCmd *Command) {1974 // Remove completion command for the next test1975 for _, cmd := range rootCmd.commands {1976 if cmd.Name() == compCmdName {1977 rootCmd.RemoveCommand(cmd)1978 return1979 }1980 }1981}19821983func TestDefaultCompletionCmd(t *testing.T) {1984 rootCmd := &Command{1985 Use: "root",1986 Args: NoArgs,1987 Run: emptyRun,1988 }19891990 // Test that no completion command is created if there are not other sub-commands1991 assertNoErr(t, rootCmd.Execute())1992 for _, cmd := range rootCmd.commands {1993 if cmd.Name() == compCmdName {1994 t.Errorf("Should not have a 'completion' command when there are no other sub-commands of root")1995 break1996 }1997 }19981999 subCmd := &Command{2000 Use: "sub",2001 Run: emptyRun,2002 }2003 rootCmd.AddCommand(subCmd)20042005 // Test that a completion command is created if there are other sub-commands2006 found := false2007 assertNoErr(t, rootCmd.Execute())2008 for _, cmd := range rootCmd.commands {2009 if cmd.Name() == compCmdName {2010 found = true2011 break2012 }2013 }2014 if !found {2015 t.Errorf("Should have a 'completion' command when there are other sub-commands of root")2016 }2017 // Remove completion command for the next test2018 removeCompCmd(rootCmd)20192020 // Test that the default completion command can be disabled2021 rootCmd.CompletionOptions.DisableDefaultCmd = true2022 assertNoErr(t, rootCmd.Execute())2023 for _, cmd := range rootCmd.commands {2024 if cmd.Name() == compCmdName {2025 t.Errorf("Should not have a 'completion' command when the feature is disabled")2026 break2027 }2028 }2029 // Re-enable for next test2030 rootCmd.CompletionOptions.DisableDefaultCmd = false20312032 // Test that completion descriptions are enabled by default2033 output, err := executeCommand(rootCmd, compCmdName, "zsh")2034 if err != nil {2035 t.Errorf("Unexpected error: %v", err)2036 }20372038 check(t, output, ShellCompRequestCmd)2039 checkOmit(t, output, ShellCompNoDescRequestCmd)2040 // Remove completion command for the next test2041 removeCompCmd(rootCmd)20422043 // Test that completion descriptions can be disabled completely2044 rootCmd.CompletionOptions.DisableDescriptions = true2045 output, err = executeCommand(rootCmd, compCmdName, "zsh")2046 if err != nil {2047 t.Errorf("Unexpected error: %v", err)2048 }20492050 check(t, output, ShellCompNoDescRequestCmd)2051 // Re-enable for next test2052 rootCmd.CompletionOptions.DisableDescriptions = false2053 // Remove completion command for the next test2054 removeCompCmd(rootCmd)20552056 var compCmd *Command2057 // Test that the --no-descriptions flag is present for the relevant shells only2058 assertNoErr(t, rootCmd.Execute())2059 for _, shell := range []string{"fish", "powershell", "zsh"} {2060 if compCmd, _, err = rootCmd.Find([]string{compCmdName, shell}); err != nil {2061 t.Errorf("Unexpected error: %v", err)2062 }2063 if flag := compCmd.Flags().Lookup(compCmdNoDescFlagName); flag == nil {2064 t.Errorf("Missing --%s flag for %s shell", compCmdNoDescFlagName, shell)2065 }2066 }2067 for _, shell := range []string{"bash"} {2068 if compCmd, _, err = rootCmd.Find([]string{compCmdName, shell}); err != nil {2069 t.Errorf("Unexpected error: %v", err)2070 }2071 if flag := compCmd.Flags().Lookup(compCmdNoDescFlagName); flag != nil {2072 t.Errorf("Unexpected --%s flag for %s shell", compCmdNoDescFlagName, shell)2073 }2074 }2075 // Remove completion command for the next test2076 removeCompCmd(rootCmd)20772078 // Test that the '--no-descriptions' flag can be disabled2079 rootCmd.CompletionOptions.DisableNoDescFlag = true2080 assertNoErr(t, rootCmd.Execute())2081 for _, shell := range []string{"fish", "zsh", "bash", "powershell"} {2082 if compCmd, _, err = rootCmd.Find([]string{compCmdName, shell}); err != nil {2083 t.Errorf("Unexpected error: %v", err)2084 }2085 if flag := compCmd.Flags().Lookup(compCmdNoDescFlagName); flag != nil {2086 t.Errorf("Unexpected --%s flag for %s shell", compCmdNoDescFlagName, shell)2087 }2088 }2089 // Re-enable for next test2090 rootCmd.CompletionOptions.DisableNoDescFlag = false2091 // Remove completion command for the next test2092 removeCompCmd(rootCmd)20932094 // Test that the '--no-descriptions' flag is disabled when descriptions are disabled2095 rootCmd.CompletionOptions.DisableDescriptions = true2096 assertNoErr(t, rootCmd.Execute())2097 for _, shell := range []string{"fish", "zsh", "bash", "powershell"} {2098 if compCmd, _, err = rootCmd.Find([]string{compCmdName, shell}); err != nil {2099 t.Errorf("Unexpected error: %v", err)2100 }2101 if flag := compCmd.Flags().Lookup(compCmdNoDescFlagName); flag != nil {2102 t.Errorf("Unexpected --%s flag for %s shell", compCmdNoDescFlagName, shell)2103 }2104 }2105 // Re-enable for next test2106 rootCmd.CompletionOptions.DisableDescriptions = false2107 // Remove completion command for the next test2108 removeCompCmd(rootCmd)2109}21102111func TestCompleteCompletion(t *testing.T) {2112 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}2113 subCmd := &Command{2114 Use: "sub",2115 Run: emptyRun,2116 }2117 rootCmd.AddCommand(subCmd)21182119 // Test sub-commands of the completion command2120 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "completion", "")2121 if err != nil {2122 t.Errorf("Unexpected error: %v", err)2123 }21242125 expected := strings.Join([]string{2126 "bash",2127 "fish",2128 "powershell",2129 "zsh",2130 ":4",2131 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")21322133 if output != expected {2134 t.Errorf("expected: %q, got: %q", expected, output)2135 }21362137 // Test there are no completions for the sub-commands of the completion command2138 var compCmd *Command2139 for _, cmd := range rootCmd.Commands() {2140 if cmd.Name() == compCmdName {2141 compCmd = cmd2142 break2143 }2144 }21452146 for _, shell := range compCmd.Commands() {2147 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, compCmdName, shell.Name(), "")2148 if err != nil {2149 t.Errorf("Unexpected error: %v", err)2150 }21512152 expected = strings.Join([]string{2153 ":4",2154 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")21552156 if output != expected {2157 t.Errorf("expected: %q, got: %q", expected, output)2158 }2159 }2160}
added:completions.go+727 added
1package cobra23import (4 "fmt"5 "os"6 "strings"78 "github.com/spf13/pflag"9)1011const (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 scripts.14 ShellCompRequestCmd = "__complete"15 // ShellCompNoDescRequestCmd is the name of the hidden command that is used to request16 // completion results without their description. It is used by the shell completion scripts.17 ShellCompNoDescRequestCmd = "__completeNoDesc"18)1920// Global map of flag completion functions.21var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){}2223// ShellCompDirective is a bit map representing the different behaviors the shell24// can be instructed to have once completions have been provided.25type ShellCompDirective int2627const (28 // ShellCompDirectiveError indicates an error occurred and completions should be ignored.29 ShellCompDirectiveError ShellCompDirective = 1 << iota3031 // ShellCompDirectiveNoSpace indicates that the shell should not add a space32 // after the completion even if there is a single completion provided.33 ShellCompDirectiveNoSpace3435 // ShellCompDirectiveNoFileComp indicates that the shell should not provide36 // file completion even when no completion is provided.37 // This currently does not work for zsh or bash < 438 ShellCompDirectiveNoFileComp3940 // ShellCompDirectiveFilterFileExt indicates that the provided completions41 // should be used as file extension filters.42 // For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename()43 // is a shortcut to using this directive explicitly. The BashCompFilenameExt44 // annotation can also be used to obtain the same behavior for flags.45 ShellCompDirectiveFilterFileExt4647 // ShellCompDirectiveFilterDirs indicates that only directory names should48 // be provided in file completion. To request directory names within another49 // directory, the returned completions should specify the directory within50 // which to search. The BashCompSubdirsInDir annotation can be used to51 // obtain the same behavior but only for flags.52 ShellCompDirectiveFilterDirs5354 // ===========================================================================5556 // All directives using iota should be above this one.57 // For internal use.58 shellCompDirectiveMaxValue5960 // ShellCompDirectiveDefault indicates to let the shell perform its default61 // behavior after completions have been provided.62 // This one must be last to avoid messing up the iota count.63 ShellCompDirectiveDefault ShellCompDirective = 064)6566const (67 // Constants for the completion command68 compCmdName = "completion"69 compCmdNoDescFlagName = "no-descriptions"70 compCmdNoDescFlagDesc = "disable completion descriptions"71 compCmdNoDescFlagDefault = false72)7374// CompletionOptions are the options to control shell completion75type CompletionOptions struct {76 // DisableDefaultCmd prevents Cobra from creating a default 'completion' command77 DisableDefaultCmd bool78 // DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag79 // for shells that support completion descriptions80 DisableNoDescFlag bool81 // DisableDescriptions turns off all completion descriptions for shells82 // that support them83 DisableDescriptions bool84}8586// NoFileCompletions can be used to disable file completion for commands that should87// not trigger file completions.88func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {89 return nil, ShellCompDirectiveNoFileComp90}9192// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.93func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error {94 flag := c.Flag(flagName)95 if flag == nil {96 return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName)97 }98 if _, exists := flagCompletionFunctions[flag]; exists {99 return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName)100 }101 flagCompletionFunctions[flag] = f102 return nil103}104105// Returns a string listing the different directive enabled in the specified parameter106func (d ShellCompDirective) string() string {107 var directives []string108 if d&ShellCompDirectiveError != 0 {109 directives = append(directives, "ShellCompDirectiveError")110 }111 if d&ShellCompDirectiveNoSpace != 0 {112 directives = append(directives, "ShellCompDirectiveNoSpace")113 }114 if d&ShellCompDirectiveNoFileComp != 0 {115 directives = append(directives, "ShellCompDirectiveNoFileComp")116 }117 if d&ShellCompDirectiveFilterFileExt != 0 {118 directives = append(directives, "ShellCompDirectiveFilterFileExt")119 }120 if d&ShellCompDirectiveFilterDirs != 0 {121 directives = append(directives, "ShellCompDirectiveFilterDirs")122 }123 if len(directives) == 0 {124 directives = append(directives, "ShellCompDirectiveDefault")125 }126127 if d >= shellCompDirectiveMaxValue {128 return fmt.Sprintf("ERROR: unexpected ShellCompDirective value: %d", d)129 }130 return strings.Join(directives, ", ")131}132133// Adds a special hidden command that can be used to request custom completions.134func (c *Command) initCompleteCmd(args []string) {135 completeCmd := &Command{136 Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd),137 Aliases: []string{ShellCompNoDescRequestCmd},138 DisableFlagsInUseLine: true,139 Hidden: true,140 DisableFlagParsing: true,141 Args: MinimumNArgs(1),142 Short: "Request shell completion choices for the specified command-line",143 Long: fmt.Sprintf("%[2]s is a special command that is used by the shell completion logic\n%[1]s",144 "to request completion choices for the specified command-line.", ShellCompRequestCmd),145 Run: func(cmd *Command, args []string) {146 finalCmd, completions, directive, err := cmd.getCompletions(args)147 if err != nil {148 CompErrorln(err.Error())149 // Keep going for multiple reasons:150 // 1- There could be some valid completions even though there was an error151 // 2- Even without completions, we need to print the directive152 }153154 noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd)155 for _, comp := range completions {156 if noDescriptions {157 // Remove any description that may be included following a tab character.158 comp = strings.Split(comp, "\t")[0]159 }160161 // Make sure we only write the first line to the output.162 // This is needed if a description contains a linebreak.163 // Otherwise the shell scripts will interpret the other lines as new flags164 // and could therefore provide a wrong completion.165 comp = strings.Split(comp, "\n")[0]166167 // Finally trim the completion. This is especially important to get rid168 // of a trailing tab when there are no description following it.169 // For example, a sub-command without a description should not be completed170 // with a tab at the end (or else zsh will show a -- following it171 // although there is no description).172 comp = strings.TrimSpace(comp)173174 // Print each possible completion to stdout for the completion script to consume.175 fmt.Fprintln(finalCmd.OutOrStdout(), comp)176 }177178 if directive >= shellCompDirectiveMaxValue {179 directive = ShellCompDirectiveDefault180 }181182 // As the last printout, print the completion directive for the completion script to parse.183 // The directive integer must be that last character following a single colon (:).184 // The completion script expects :<directive>185 fmt.Fprintf(finalCmd.OutOrStdout(), ":%d\n", directive)186187 // Print some helpful info to stderr for the user to understand.188 // Output from stderr must be ignored by the completion script.189 fmt.Fprintf(finalCmd.ErrOrStderr(), "Completion ended with directive: %s\n", directive.string())190 },191 }192 c.AddCommand(completeCmd)193 subCmd, _, err := c.Find(args)194 if err != nil || subCmd.Name() != ShellCompRequestCmd {195 // Only create this special command if it is actually being called.196 // This reduces possible side-effects of creating such a command;197 // for example, having this command would cause problems to a198 // cobra program that only consists of the root command, since this199 // command would cause the root command to suddenly have a subcommand.200 c.RemoveCommand(completeCmd)201 }202}203204func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) {205 // The last argument, which is not completely typed by the user,206 // should not be part of the list of arguments207 toComplete := args[len(args)-1]208 trimmedArgs := args[:len(args)-1]209210 var finalCmd *Command211 var finalArgs []string212 var err error213 // Find the real command for which completion must be performed214 // check if we need to traverse here to parse local flags on parent commands215 if c.Root().TraverseChildren {216 finalCmd, finalArgs, err = c.Root().Traverse(trimmedArgs)217 } else {218 finalCmd, finalArgs, err = c.Root().Find(trimmedArgs)219 }220 if err != nil {221 // Unable to find the real command. E.g., <program> someInvalidCmd <TAB>222 return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)223 }224225 // Check if we are doing flag value completion before parsing the flags.226 // This is important because if we are completing a flag value, we need to also227 // remove the flag name argument from the list of finalArgs or else the parsing228 // could fail due to an invalid value (incomplete) for the flag.229 flag, finalArgs, toComplete, err := checkIfFlagCompletion(finalCmd, finalArgs, toComplete)230 if err != nil {231 // Error while attempting to parse flags232 return finalCmd, []string{}, ShellCompDirectiveDefault, err233 }234235 // Parse the flags early so we can check if required flags are set236 if err = finalCmd.ParseFlags(finalArgs); err != nil {237 return finalCmd, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())238 }239240 if flag != nil {241 // Check if we are completing a flag value subject to annotations242 if validExts, present := flag.Annotations[BashCompFilenameExt]; present {243 if len(validExts) != 0 {244 // File completion filtered by extensions245 return finalCmd, validExts, ShellCompDirectiveFilterFileExt, nil246 }247248 // The annotation requests simple file completion. There is no reason to do249 // that since it is the default behavior anyway. Let's ignore this annotation250 // in case the program also registered a completion function for this flag.251 // Even though it is a mistake on the program's side, let's be nice when we can.252 }253254 if subDir, present := flag.Annotations[BashCompSubdirsInDir]; present {255 if len(subDir) == 1 {256 // Directory completion from within a directory257 return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil258 }259 // Directory completion260 return finalCmd, []string{}, ShellCompDirectiveFilterDirs, nil261 }262 }263264 // When doing completion of a flag name, as soon as an argument starts with265 // a '-' we know it is a flag. We cannot use isFlagArg() here as it requires266 // the flag name to be complete267 if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") {268 var completions []string269270 // First check for required flags271 completions = completeRequireFlags(finalCmd, toComplete)272273 // If we have not found any required flags, only then can we show regular flags274 if len(completions) == 0 {275 doCompleteFlags := func(flag *pflag.Flag) {276 if !flag.Changed ||277 strings.Contains(flag.Value.Type(), "Slice") ||278 strings.Contains(flag.Value.Type(), "Array") {279 // If the flag is not already present, or if it can be specified multiple times (Array or Slice)280 // we suggest it as a completion281 completions = append(completions, getFlagNameCompletions(flag, toComplete)...)282 }283 }284285 // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands286 // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and287 // non-inherited flags.288 finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {289 doCompleteFlags(flag)290 })291 finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {292 doCompleteFlags(flag)293 })294 }295296 directive := ShellCompDirectiveNoFileComp297 if len(completions) == 1 && strings.HasSuffix(completions[0], "=") {298 // If there is a single completion, the shell usually adds a space299 // after the completion. We don't want that if the flag ends with an =300 directive = ShellCompDirectiveNoSpace301 }302 return finalCmd, completions, directive, nil303 }304305 // We only remove the flags from the arguments if DisableFlagParsing is not set.306 // This is important for commands which have requested to do their own flag completion.307 if !finalCmd.DisableFlagParsing {308 finalArgs = finalCmd.Flags().Args()309 }310311 var completions []string312 directive := ShellCompDirectiveDefault313 if flag == nil {314 foundLocalNonPersistentFlag := false315 // If TraverseChildren is true on the root command we don't check for316 // local flags because we can use a local flag on a parent command317 if !finalCmd.Root().TraverseChildren {318 // Check if there are any local, non-persistent flags on the command-line319 localNonPersistentFlags := finalCmd.LocalNonPersistentFlags()320 finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {321 if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed {322 foundLocalNonPersistentFlag = true323 }324 })325 }326327 // Complete subcommand names, including the help command328 if len(finalArgs) == 0 && !foundLocalNonPersistentFlag {329 // We only complete sub-commands if:330 // - there are no arguments on the command-line and331 // - there are no local, non-peristent flag on the command-line or TraverseChildren is true332 for _, subCmd := range finalCmd.Commands() {333 if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand {334 if strings.HasPrefix(subCmd.Name(), toComplete) {335 completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))336 }337 directive = ShellCompDirectiveNoFileComp338 }339 }340 }341342 // Complete required flags even without the '-' prefix343 completions = append(completions, completeRequireFlags(finalCmd, toComplete)...)344345 // Always complete ValidArgs, even if we are completing a subcommand name.346 // This is for commands that have both subcommands and ValidArgs.347 if len(finalCmd.ValidArgs) > 0 {348 if len(finalArgs) == 0 {349 // ValidArgs are only for the first argument350 for _, validArg := range finalCmd.ValidArgs {351 if strings.HasPrefix(validArg, toComplete) {352 completions = append(completions, validArg)353 }354 }355 directive = ShellCompDirectiveNoFileComp356357 // If no completions were found within commands or ValidArgs,358 // see if there are any ArgAliases that should be completed.359 if len(completions) == 0 {360 for _, argAlias := range finalCmd.ArgAliases {361 if strings.HasPrefix(argAlias, toComplete) {362 completions = append(completions, argAlias)363 }364 }365 }366 }367368 // If there are ValidArgs specified (even if they don't match), we stop completion.369 // Only one of ValidArgs or ValidArgsFunction can be used for a single command.370 return finalCmd, completions, directive, nil371 }372373 // Let the logic continue so as to add any ValidArgsFunction completions,374 // even if we already found sub-commands.375 // This is for commands that have subcommands but also specify a ValidArgsFunction.376 }377378 // Find the completion function for the flag or command379 var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)380 if flag != nil {381 completionFn = flagCompletionFunctions[flag]382 } else {383 completionFn = finalCmd.ValidArgsFunction384 }385 if completionFn != nil {386 // Go custom completion defined for this flag or command.387 // Call the registered completion function to get the completions.388 var comps []string389 comps, directive = completionFn(finalCmd, finalArgs, toComplete)390 completions = append(completions, comps...)391 }392393 return finalCmd, completions, directive, nil394}395396func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string {397 if nonCompletableFlag(flag) {398 return []string{}399 }400401 var completions []string402 flagName := "--" + flag.Name403 if strings.HasPrefix(flagName, toComplete) {404 // Flag without the =405 completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))406407 // Why suggest both long forms: --flag and --flag= ?408 // This forces the user to *always* have to type either an = or a space after the flag name.409 // Let's be nice and avoid making users have to do that.410 // Since boolean flags and shortname flags don't show the = form, let's go that route and never show it.411 // The = form will still work, we just won't suggest it.412 // This also makes the list of suggested flags shorter as we avoid all the = forms.413 //414 // if len(flag.NoOptDefVal) == 0 {415 // // Flag requires a value, so it can be suffixed with =416 // flagName += "="417 // completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))418 // }419 }420421 flagName = "-" + flag.Shorthand422 if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) {423 completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))424 }425426 return completions427}428429func completeRequireFlags(finalCmd *Command, toComplete string) []string {430 var completions []string431432 doCompleteRequiredFlags := func(flag *pflag.Flag) {433 if _, present := flag.Annotations[BashCompOneRequiredFlag]; present {434 if !flag.Changed {435 // If the flag is not already present, we suggest it as a completion436 completions = append(completions, getFlagNameCompletions(flag, toComplete)...)437 }438 }439 }440441 // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands442 // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and443 // non-inherited flags.444 finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {445 doCompleteRequiredFlags(flag)446 })447 finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {448 doCompleteRequiredFlags(flag)449 })450451 return completions452}453454func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) {455 if finalCmd.DisableFlagParsing {456 // We only do flag completion if we are allowed to parse flags457 // This is important for commands which have requested to do their own flag completion.458 return nil, args, lastArg, nil459 }460461 var flagName string462 trimmedArgs := args463 flagWithEqual := false464465 // When doing completion of a flag name, as soon as an argument starts with466 // a '-' we know it is a flag. We cannot use isFlagArg() here as that function467 // requires the flag name to be complete468 if len(lastArg) > 0 && lastArg[0] == '-' {469 if index := strings.Index(lastArg, "="); index >= 0 {470 // Flag with an =471 flagName = strings.TrimLeft(lastArg[:index], "-")472 lastArg = lastArg[index+1:]473 flagWithEqual = true474 } else {475 // Normal flag completion476 return nil, args, lastArg, nil477 }478 }479480 if len(flagName) == 0 {481 if len(args) > 0 {482 prevArg := args[len(args)-1]483 if isFlagArg(prevArg) {484 // Only consider the case where the flag does not contain an =.485 // If the flag contains an = it means it has already been fully processed,486 // so we don't need to deal with it here.487 if index := strings.Index(prevArg, "="); index < 0 {488 flagName = strings.TrimLeft(prevArg, "-")489490 // Remove the uncompleted flag or else there could be an error created491 // for an invalid value for that flag492 trimmedArgs = args[:len(args)-1]493 }494 }495 }496 }497498 if len(flagName) == 0 {499 // Not doing flag completion500 return nil, trimmedArgs, lastArg, nil501 }502503 flag := findFlag(finalCmd, flagName)504 if flag == nil {505 // Flag not supported by this command, nothing to complete506 err := fmt.Errorf("Subcommand '%s' does not support flag '%s'", finalCmd.Name(), flagName)507 return nil, nil, "", err508 }509510 if !flagWithEqual {511 if len(flag.NoOptDefVal) != 0 {512 // We had assumed dealing with a two-word flag but the flag is a boolean flag.513 // In that case, there is no value following it, so we are not really doing flag completion.514 // Reset everything to do noun completion.515 trimmedArgs = args516 flag = nil517 }518 }519520 return flag, trimmedArgs, lastArg, nil521}522523// initDefaultCompletionCmd adds a default 'completion' command to c.524// This function will do nothing if any of the following is true:525// 1- the feature has been explicitly disabled by the program,526// 2- c has no subcommands (to avoid creating one),527// 3- c already has a 'completion' command provided by the program.528func (c *Command) initDefaultCompletionCmd() {529 if c.CompletionOptions.DisableDefaultCmd || !c.HasSubCommands() {530 return531 }532533 for _, cmd := range c.commands {534 if cmd.Name() == compCmdName || cmd.HasAlias(compCmdName) {535 // A completion command is already available536 return537 }538 }539540 haveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions541542 completionCmd := &Command{543 Use: compCmdName,544 Short: "generate the autocompletion script for the specified shell",545 Long: fmt.Sprintf(`546Generate the autocompletion script for %[1]s for the specified shell.547See each sub-command's help for details on how to use the generated script.548`, c.Root().Name()),549 Args: NoArgs,550 ValidArgsFunction: NoFileCompletions,551 }552 c.AddCommand(completionCmd)553554 out := c.OutOrStdout()555 noDesc := c.CompletionOptions.DisableDescriptions556 shortDesc := "generate the autocompletion script for %s"557 bash := &Command{558 Use: "bash",559 Short: fmt.Sprintf(shortDesc, "bash"),560 Long: fmt.Sprintf(`561Generate the autocompletion script for the bash shell.562563This script depends on the 'bash-completion' package.564If it is not installed already, you can install it via your OS's package manager.565566To load completions in your current shell session:567$ source <(%[1]s completion bash)568569To load completions for every new session, execute once:570Linux:571 $ %[1]s completion bash > /etc/bash_completion.d/%[1]s572MacOS:573 $ %[1]s completion bash > /usr/local/etc/bash_completion.d/%[1]s574575You will need to start a new shell for this setup to take effect.576 `, c.Root().Name()),577 Args: NoArgs,578 DisableFlagsInUseLine: true,579 ValidArgsFunction: NoFileCompletions,580 RunE: func(cmd *Command, args []string) error {581 return cmd.Root().GenBashCompletion(out)582 },583 }584585 zsh := &Command{586 Use: "zsh",587 Short: fmt.Sprintf(shortDesc, "zsh"),588 Long: fmt.Sprintf(`589Generate the autocompletion script for the zsh shell.590591If shell completion is not already enabled in your environment you will need592to enable it. You can execute the following once:593594$ echo "autoload -U compinit; compinit" >> ~/.zshrc595596To load completions for every new session, execute once:597$ %[1]s completion zsh > "${fpath[1]}/_%[1]s"598599You will need to start a new shell for this setup to take effect.600`, c.Root().Name()),601 Args: NoArgs,602 ValidArgsFunction: NoFileCompletions,603 RunE: func(cmd *Command, args []string) error {604 if noDesc {605 return cmd.Root().GenZshCompletionNoDesc(out)606 }607 return cmd.Root().GenZshCompletion(out)608 },609 }610 if haveNoDescFlag {611 zsh.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)612 }613614 fish := &Command{615 Use: "fish",616 Short: fmt.Sprintf(shortDesc, "fish"),617 Long: fmt.Sprintf(`618Generate the autocompletion script for the fish shell.619620To load completions in your current shell session:621$ %[1]s completion fish | source622623To load completions for every new session, execute once:624$ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish625626You will need to start a new shell for this setup to take effect.627`, c.Root().Name()),628 Args: NoArgs,629 ValidArgsFunction: NoFileCompletions,630 RunE: func(cmd *Command, args []string) error {631 return cmd.Root().GenFishCompletion(out, !noDesc)632 },633 }634 if haveNoDescFlag {635 fish.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)636 }637638 powershell := &Command{639 Use: "powershell",640 Short: fmt.Sprintf(shortDesc, "powershell"),641 Long: fmt.Sprintf(`642Generate the autocompletion script for powershell.643644To load completions in your current shell session:645PS C:\> %[1]s completion powershell | Out-String | Invoke-Expression646647To load completions for every new session, add the output of the above command648to your powershell profile.649`, c.Root().Name()),650 Args: NoArgs,651 ValidArgsFunction: NoFileCompletions,652 RunE: func(cmd *Command, args []string) error {653 if noDesc {654 return cmd.Root().GenPowerShellCompletion(out)655 }656 return cmd.Root().GenPowerShellCompletionWithDesc(out)657658 },659 }660 if haveNoDescFlag {661 powershell.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)662 }663664 completionCmd.AddCommand(bash, zsh, fish, powershell)665}666667func findFlag(cmd *Command, name string) *pflag.Flag {668 flagSet := cmd.Flags()669 if len(name) == 1 {670 // First convert the short flag into a long flag671 // as the cmd.Flag() search only accepts long flags672 if short := flagSet.ShorthandLookup(name); short != nil {673 name = short.Name674 } else {675 set := cmd.InheritedFlags()676 if short = set.ShorthandLookup(name); short != nil {677 name = short.Name678 } else {679 return nil680 }681 }682 }683 return cmd.Flag(name)684}685686// CompDebug prints the specified string to the same file as where the687// completion script prints its logs.688// Note that completion printouts should never be on stdout as they would689// be wrongly interpreted as actual completion choices by the completion script.690func CompDebug(msg string, printToStdErr bool) {691 msg = fmt.Sprintf("[Debug] %s", msg)692693 // Such logs are only printed when the user has set the environment694 // variable BASH_COMP_DEBUG_FILE to the path of some file to be used.695 if path := os.Getenv("BASH_COMP_DEBUG_FILE"); path != "" {696 f, err := os.OpenFile(path,697 os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)698 if err == nil {699 defer f.Close()700 WriteStringAndCheck(f, msg)701 }702 }703704 if printToStdErr {705 // Must print to stderr for this not to be read by the completion script.706 fmt.Fprint(os.Stderr, msg)707 }708}709710// CompDebugln prints the specified string with a newline at the end711// to the same file as where the completion script prints its logs.712// Such logs are only printed when the user has set the environment713// variable BASH_COMP_DEBUG_FILE to the path of some file to be used.714func CompDebugln(msg string, printToStdErr bool) {715 CompDebug(fmt.Sprintf("%s\n", msg), printToStdErr)716}717718// CompError prints the specified completion message to stderr.719func CompError(msg string) {720 msg = fmt.Sprintf("[Error] %s", msg)721 CompDebug(msg, true)722}723724// CompErrorln prints the specified completion message to stderr with a newline at the end.725func CompErrorln(msg string) {726 CompError(fmt.Sprintf("%s\n", msg))727}
deleted:custom_completions_test.go-1960 removed
1package cobra23import (4 "bytes"5 "strings"6 "testing"7)89func validArgsFunc(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {10 if len(args) != 0 {11 return nil, ShellCompDirectiveNoFileComp12 }1314 var completions []string15 for _, comp := range []string{"one\tThe first", "two\tThe second"} {16 if strings.HasPrefix(comp, toComplete) {17 completions = append(completions, comp)18 }19 }20 return completions, ShellCompDirectiveDefault21}2223func validArgsFunc2(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {24 if len(args) != 0 {25 return nil, ShellCompDirectiveNoFileComp26 }2728 var completions []string29 for _, comp := range []string{"three\tThe third", "four\tThe fourth"} {30 if strings.HasPrefix(comp, toComplete) {31 completions = append(completions, comp)32 }33 }34 return completions, ShellCompDirectiveDefault35}3637func TestCmdNameCompletionInGo(t *testing.T) {38 rootCmd := &Command{39 Use: "root",40 Run: emptyRun,41 }42 childCmd1 := &Command{43 Use: "firstChild",44 Short: "First command",45 Run: emptyRun,46 }47 childCmd2 := &Command{48 Use: "secondChild",49 Run: emptyRun,50 }51 hiddenCmd := &Command{52 Use: "testHidden",53 Hidden: true, // Not completed54 Run: emptyRun,55 }56 deprecatedCmd := &Command{57 Use: "testDeprecated",58 Deprecated: "deprecated", // Not completed59 Run: emptyRun,60 }61 aliasedCmd := &Command{62 Use: "aliased",63 Short: "A command with aliases",64 Aliases: []string{"testAlias", "testSynonym"}, // Not completed65 Run: emptyRun,66 }6768 rootCmd.AddCommand(childCmd1, childCmd2, hiddenCmd, deprecatedCmd, aliasedCmd)6970 // Test that sub-command names are completed71 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")72 if err != nil {73 t.Errorf("Unexpected error: %v", err)74 }7576 expected := strings.Join([]string{77 "aliased",78 "firstChild",79 "help",80 "secondChild",81 ":4",82 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")8384 if output != expected {85 t.Errorf("expected: %q, got: %q", expected, output)86 }8788 // Test that sub-command names are completed with prefix89 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "s")90 if err != nil {91 t.Errorf("Unexpected error: %v", err)92 }9394 expected = strings.Join([]string{95 "secondChild",96 ":4",97 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")9899 if output != expected {100 t.Errorf("expected: %q, got: %q", expected, output)101 }102103 // Test that even with no valid sub-command matches, hidden, deprecated and104 // aliases are not completed105 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "test")106 if err != nil {107 t.Errorf("Unexpected error: %v", err)108 }109110 expected = strings.Join([]string{111 ":4",112 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")113114 if output != expected {115 t.Errorf("expected: %q, got: %q", expected, output)116 }117118 // Test that sub-command names are completed with description119 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "")120 if err != nil {121 t.Errorf("Unexpected error: %v", err)122 }123124 expected = strings.Join([]string{125 "aliased\tA command with aliases",126 "firstChild\tFirst command",127 "help\tHelp about any command",128 "secondChild",129 ":4",130 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")131132 if output != expected {133 t.Errorf("expected: %q, got: %q", expected, output)134 }135}136137func TestNoCmdNameCompletionInGo(t *testing.T) {138 rootCmd := &Command{139 Use: "root",140 Run: emptyRun,141 }142 rootCmd.Flags().String("localroot", "", "local root flag")143144 childCmd1 := &Command{145 Use: "childCmd1",146 Short: "First command",147 Args: MinimumNArgs(0),148 Run: emptyRun,149 }150 rootCmd.AddCommand(childCmd1)151 childCmd1.PersistentFlags().StringP("persistent", "p", "", "persistent flag")152 persistentFlag := childCmd1.PersistentFlags().Lookup("persistent")153 childCmd1.Flags().StringP("nonPersistent", "n", "", "non-persistent flag")154 nonPersistentFlag := childCmd1.Flags().Lookup("nonPersistent")155156 childCmd2 := &Command{157 Use: "childCmd2",158 Run: emptyRun,159 }160 childCmd1.AddCommand(childCmd2)161162 // Test that sub-command names are not completed if there is an argument already163 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "arg1", "")164 if err != nil {165 t.Errorf("Unexpected error: %v", err)166 }167168 expected := strings.Join([]string{169 ":0",170 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")171172 if output != expected {173 t.Errorf("expected: %q, got: %q", expected, output)174 }175176 // Test that sub-command names are not completed if a local non-persistent flag is present177 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "--nonPersistent", "value", "")178 if err != nil {179 t.Errorf("Unexpected error: %v", err)180 }181 // Reset the flag for the next command182 nonPersistentFlag.Changed = false183184 expected = strings.Join([]string{185 ":0",186 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")187188 if output != expected {189 t.Errorf("expected: %q, got: %q", expected, output)190 }191192 // Test that sub-command names are completed if a local non-persistent flag is present and TraverseChildren is set to true193 // set TraverseChildren to true on the root cmd194 rootCmd.TraverseChildren = true195196 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--localroot", "value", "")197 if err != nil {198 t.Errorf("Unexpected error: %v", err)199 }200 // Reset TraverseChildren for next command201 rootCmd.TraverseChildren = false202203 expected = strings.Join([]string{204 "childCmd1",205 "help",206 ":4",207 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")208209 if output != expected {210 t.Errorf("expected: %q, got: %q", expected, output)211 }212213 // Test that sub-command names from a child cmd are completed if a local non-persistent flag is present214 // and TraverseChildren is set to true on the root cmd215 rootCmd.TraverseChildren = true216217 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--localroot", "value", "childCmd1", "--nonPersistent", "value", "")218 if err != nil {219 t.Errorf("Unexpected error: %v", err)220 }221 // Reset TraverseChildren for next command222 rootCmd.TraverseChildren = false223 // Reset the flag for the next command224 nonPersistentFlag.Changed = false225226 expected = strings.Join([]string{227 "childCmd2",228 ":4",229 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")230231 if output != expected {232 t.Errorf("expected: %q, got: %q", expected, output)233 }234235 // Test that we don't use Traverse when we shouldn't.236 // This command should not return a completion since the command line is invalid without TraverseChildren.237 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--localroot", "value", "childCmd1", "")238 if err != nil {239 t.Errorf("Unexpected error: %v", err)240 }241242 expected = strings.Join([]string{243 ":0",244 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")245246 if output != expected {247 t.Errorf("expected: %q, got: %q", expected, output)248 }249250 // Test that sub-command names are not completed if a local non-persistent short flag is present251 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "-n", "value", "")252 if err != nil {253 t.Errorf("Unexpected error: %v", err)254 }255 // Reset the flag for the next command256 nonPersistentFlag.Changed = false257258 expected = strings.Join([]string{259 ":0",260 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")261262 if output != expected {263 t.Errorf("expected: %q, got: %q", expected, output)264 }265266 // Test that sub-command names are completed with a persistent flag267 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "--persistent", "value", "")268 if err != nil {269 t.Errorf("Unexpected error: %v", err)270 }271 // Reset the flag for the next command272 persistentFlag.Changed = false273274 expected = strings.Join([]string{275 "childCmd2",276 ":4",277 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")278279 if output != expected {280 t.Errorf("expected: %q, got: %q", expected, output)281 }282283 // Test that sub-command names are completed with a persistent short flag284 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "-p", "value", "")285 if err != nil {286 t.Errorf("Unexpected error: %v", err)287 }288 // Reset the flag for the next command289 persistentFlag.Changed = false290291 expected = strings.Join([]string{292 "childCmd2",293 ":4",294 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")295296 if output != expected {297 t.Errorf("expected: %q, got: %q", expected, output)298 }299}300301func TestValidArgsCompletionInGo(t *testing.T) {302 rootCmd := &Command{303 Use: "root",304 ValidArgs: []string{"one", "two", "three"},305 Args: MinimumNArgs(1),306 }307308 // Test that validArgs are completed309 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")310 if err != nil {311 t.Errorf("Unexpected error: %v", err)312 }313314 expected := strings.Join([]string{315 "one",316 "two",317 "three",318 ":4",319 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")320321 if output != expected {322 t.Errorf("expected: %q, got: %q", expected, output)323 }324325 // Test that validArgs are completed with prefix326 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "o")327 if err != nil {328 t.Errorf("Unexpected error: %v", err)329 }330331 expected = strings.Join([]string{332 "one",333 ":4",334 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")335336 if output != expected {337 t.Errorf("expected: %q, got: %q", expected, output)338 }339340 // Test that validArgs don't repeat341 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "one", "")342 if err != nil {343 t.Errorf("Unexpected error: %v", err)344 }345346 expected = strings.Join([]string{347 ":0",348 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")349350 if output != expected {351 t.Errorf("expected: %q, got: %q", expected, output)352 }353}354355func TestValidArgsAndCmdCompletionInGo(t *testing.T) {356 rootCmd := &Command{357 Use: "root",358 ValidArgs: []string{"one", "two"},359 Run: emptyRun,360 }361362 childCmd := &Command{363 Use: "thechild",364 Run: emptyRun,365 }366367 rootCmd.AddCommand(childCmd)368369 // Test that both sub-commands and validArgs are completed370 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")371 if err != nil {372 t.Errorf("Unexpected error: %v", err)373 }374375 expected := strings.Join([]string{376 "help",377 "thechild",378 "one",379 "two",380 ":4",381 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")382383 if output != expected {384 t.Errorf("expected: %q, got: %q", expected, output)385 }386387 // Test that both sub-commands and validArgs are completed with prefix388 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")389 if err != nil {390 t.Errorf("Unexpected error: %v", err)391 }392393 expected = strings.Join([]string{394 "thechild",395 "two",396 ":4",397 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")398399 if output != expected {400 t.Errorf("expected: %q, got: %q", expected, output)401 }402}403404func TestValidArgsFuncAndCmdCompletionInGo(t *testing.T) {405 rootCmd := &Command{406 Use: "root",407 ValidArgsFunction: validArgsFunc,408 Run: emptyRun,409 }410411 childCmd := &Command{412 Use: "thechild",413 Short: "The child command",414 Run: emptyRun,415 }416417 rootCmd.AddCommand(childCmd)418419 // Test that both sub-commands and validArgsFunction are completed420 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")421 if err != nil {422 t.Errorf("Unexpected error: %v", err)423 }424425 expected := strings.Join([]string{426 "help",427 "thechild",428 "one",429 "two",430 ":0",431 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")432433 if output != expected {434 t.Errorf("expected: %q, got: %q", expected, output)435 }436437 // Test that both sub-commands and validArgs are completed with prefix438 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")439 if err != nil {440 t.Errorf("Unexpected error: %v", err)441 }442443 expected = strings.Join([]string{444 "thechild",445 "two",446 ":0",447 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")448449 if output != expected {450 t.Errorf("expected: %q, got: %q", expected, output)451 }452453 // Test that both sub-commands and validArgs are completed with description454 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "t")455 if err != nil {456 t.Errorf("Unexpected error: %v", err)457 }458459 expected = strings.Join([]string{460 "thechild\tThe child command",461 "two\tThe second",462 ":0",463 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")464465 if output != expected {466 t.Errorf("expected: %q, got: %q", expected, output)467 }468}469470func TestFlagNameCompletionInGo(t *testing.T) {471 rootCmd := &Command{472 Use: "root",473 Run: emptyRun,474 }475 childCmd := &Command{476 Use: "childCmd",477 Run: emptyRun,478 }479 rootCmd.AddCommand(childCmd)480481 rootCmd.Flags().IntP("first", "f", -1, "first flag")482 rootCmd.PersistentFlags().BoolP("second", "s", false, "second flag")483 childCmd.Flags().String("subFlag", "", "sub flag")484485 // Test that flag names are not shown if the user has not given the '-' prefix486 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")487 if err != nil {488 t.Errorf("Unexpected error: %v", err)489 }490491 expected := strings.Join([]string{492 "childCmd",493 "help",494 ":4",495 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")496497 if output != expected {498 t.Errorf("expected: %q, got: %q", expected, output)499 }500501 // Test that flag names are completed502 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-")503 if err != nil {504 t.Errorf("Unexpected error: %v", err)505 }506507 expected = strings.Join([]string{508 "--first",509 "-f",510 "--second",511 "-s",512 ":4",513 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")514515 if output != expected {516 t.Errorf("expected: %q, got: %q", expected, output)517 }518519 // Test that flag names are completed when a prefix is given520 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--f")521 if err != nil {522 t.Errorf("Unexpected error: %v", err)523 }524525 expected = strings.Join([]string{526 "--first",527 ":4",528 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")529530 if output != expected {531 t.Errorf("expected: %q, got: %q", expected, output)532 }533534 // Test that flag names are completed in a sub-cmd535 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd", "-")536 if err != nil {537 t.Errorf("Unexpected error: %v", err)538 }539540 expected = strings.Join([]string{541 "--second",542 "-s",543 "--subFlag",544 ":4",545 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")546547 if output != expected {548 t.Errorf("expected: %q, got: %q", expected, output)549 }550}551552func TestFlagNameCompletionInGoWithDesc(t *testing.T) {553 rootCmd := &Command{554 Use: "root",555 Run: emptyRun,556 }557 childCmd := &Command{558 Use: "childCmd",559 Short: "first command",560 Run: emptyRun,561 }562 rootCmd.AddCommand(childCmd)563564 rootCmd.Flags().IntP("first", "f", -1, "first flag\nlonger description for flag")565 rootCmd.PersistentFlags().BoolP("second", "s", false, "second flag")566 childCmd.Flags().String("subFlag", "", "sub flag")567568 // Test that flag names are not shown if the user has not given the '-' prefix569 output, err := executeCommand(rootCmd, ShellCompRequestCmd, "")570 if err != nil {571 t.Errorf("Unexpected error: %v", err)572 }573574 expected := strings.Join([]string{575 "childCmd\tfirst command",576 "help\tHelp about any command",577 ":4",578 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")579580 if output != expected {581 t.Errorf("expected: %q, got: %q", expected, output)582 }583584 // Test that flag names are completed585 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "-")586 if err != nil {587 t.Errorf("Unexpected error: %v", err)588 }589590 expected = strings.Join([]string{591 "--first\tfirst flag",592 "-f\tfirst flag",593 "--second\tsecond flag",594 "-s\tsecond flag",595 ":4",596 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")597598 if output != expected {599 t.Errorf("expected: %q, got: %q", expected, output)600 }601602 // Test that flag names are completed when a prefix is given603 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--f")604 if err != nil {605 t.Errorf("Unexpected error: %v", err)606 }607608 expected = strings.Join([]string{609 "--first\tfirst flag",610 ":4",611 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")612613 if output != expected {614 t.Errorf("expected: %q, got: %q", expected, output)615 }616617 // Test that flag names are completed in a sub-cmd618 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "childCmd", "-")619 if err != nil {620 t.Errorf("Unexpected error: %v", err)621 }622623 expected = strings.Join([]string{624 "--second\tsecond flag",625 "-s\tsecond flag",626 "--subFlag\tsub flag",627 ":4",628 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")629630 if output != expected {631 t.Errorf("expected: %q, got: %q", expected, output)632 }633}634635func TestFlagNameCompletionRepeat(t *testing.T) {636 rootCmd := &Command{637 Use: "root",638 Run: emptyRun,639 }640 childCmd := &Command{641 Use: "childCmd",642 Short: "first command",643 Run: emptyRun,644 }645 rootCmd.AddCommand(childCmd)646647 rootCmd.Flags().IntP("first", "f", -1, "first flag")648 firstFlag := rootCmd.Flags().Lookup("first")649 rootCmd.Flags().BoolP("second", "s", false, "second flag")650 secondFlag := rootCmd.Flags().Lookup("second")651 rootCmd.Flags().StringArrayP("array", "a", nil, "array flag")652 arrayFlag := rootCmd.Flags().Lookup("array")653 rootCmd.Flags().IntSliceP("slice", "l", nil, "slice flag")654 sliceFlag := rootCmd.Flags().Lookup("slice")655 rootCmd.Flags().BoolSliceP("bslice", "b", nil, "bool slice flag")656 bsliceFlag := rootCmd.Flags().Lookup("bslice")657658 // Test that flag names are not repeated unless they are an array or slice659 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--first", "1", "--")660 if err != nil {661 t.Errorf("Unexpected error: %v", err)662 }663 // Reset the flag for the next command664 firstFlag.Changed = false665666 expected := strings.Join([]string{667 "--array",668 "--bslice",669 "--second",670 "--slice",671 ":4",672 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")673674 if output != expected {675 t.Errorf("expected: %q, got: %q", expected, output)676 }677678 // Test that flag names are not repeated unless they are an array or slice679 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--first", "1", "--second=false", "--")680 if err != nil {681 t.Errorf("Unexpected error: %v", err)682 }683 // Reset the flag for the next command684 firstFlag.Changed = false685 secondFlag.Changed = false686687 expected = strings.Join([]string{688 "--array",689 "--bslice",690 "--slice",691 ":4",692 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")693694 if output != expected {695 t.Errorf("expected: %q, got: %q", expected, output)696 }697698 // Test that flag names are not repeated unless they are an array or slice699 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--slice", "1", "--slice=2", "--array", "val", "--bslice", "true", "--")700 if err != nil {701 t.Errorf("Unexpected error: %v", err)702 }703 // Reset the flag for the next command704 sliceFlag.Changed = false705 arrayFlag.Changed = false706 bsliceFlag.Changed = false707708 expected = strings.Join([]string{709 "--array",710 "--bslice",711 "--first",712 "--second",713 "--slice",714 ":4",715 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")716717 if output != expected {718 t.Errorf("expected: %q, got: %q", expected, output)719 }720721 // Test that flag names are not repeated unless they are an array or slice, using shortname722 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-l", "1", "-l=2", "-a", "val", "-")723 if err != nil {724 t.Errorf("Unexpected error: %v", err)725 }726 // Reset the flag for the next command727 sliceFlag.Changed = false728 arrayFlag.Changed = false729730 expected = strings.Join([]string{731 "--array",732 "-a",733 "--bslice",734 "-b",735 "--first",736 "-f",737 "--second",738 "-s",739 "--slice",740 "-l",741 ":4",742 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")743744 if output != expected {745 t.Errorf("expected: %q, got: %q", expected, output)746 }747748 // Test that flag names are not repeated unless they are an array or slice, using shortname with prefix749 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-l", "1", "-l=2", "-a", "val", "-a")750 if err != nil {751 t.Errorf("Unexpected error: %v", err)752 }753 // Reset the flag for the next command754 sliceFlag.Changed = false755 arrayFlag.Changed = false756757 expected = strings.Join([]string{758 "-a",759 ":4",760 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")761762 if output != expected {763 t.Errorf("expected: %q, got: %q", expected, output)764 }765}766767func TestRequiredFlagNameCompletionInGo(t *testing.T) {768 rootCmd := &Command{769 Use: "root",770 ValidArgs: []string{"realArg"},771 Run: emptyRun,772 }773 childCmd := &Command{774 Use: "childCmd",775 ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {776 return []string{"subArg"}, ShellCompDirectiveNoFileComp777 },778 Run: emptyRun,779 }780 rootCmd.AddCommand(childCmd)781782 rootCmd.Flags().IntP("requiredFlag", "r", -1, "required flag")783 assertNoErr(t, rootCmd.MarkFlagRequired("requiredFlag"))784 requiredFlag := rootCmd.Flags().Lookup("requiredFlag")785786 rootCmd.PersistentFlags().IntP("requiredPersistent", "p", -1, "required persistent")787 assertNoErr(t, rootCmd.MarkPersistentFlagRequired("requiredPersistent"))788 requiredPersistent := rootCmd.PersistentFlags().Lookup("requiredPersistent")789790 rootCmd.Flags().StringP("release", "R", "", "Release name")791792 childCmd.Flags().BoolP("subRequired", "s", false, "sub required flag")793 assertNoErr(t, childCmd.MarkFlagRequired("subRequired"))794 childCmd.Flags().BoolP("subNotRequired", "n", false, "sub not required flag")795796 // Test that a required flag is suggested even without the - prefix797 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")798 if err != nil {799 t.Errorf("Unexpected error: %v", err)800 }801802 expected := strings.Join([]string{803 "childCmd",804 "help",805 "--requiredFlag",806 "-r",807 "--requiredPersistent",808 "-p",809 "realArg",810 ":4",811 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")812813 if output != expected {814 t.Errorf("expected: %q, got: %q", expected, output)815 }816817 // Test that a required flag is suggested without other flags when using the '-' prefix818 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-")819 if err != nil {820 t.Errorf("Unexpected error: %v", err)821 }822823 expected = strings.Join([]string{824 "--requiredFlag",825 "-r",826 "--requiredPersistent",827 "-p",828 ":4",829 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")830831 if output != expected {832 t.Errorf("expected: %q, got: %q", expected, output)833 }834835 // Test that if no required flag matches, the normal flags are suggested836 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--relea")837 if err != nil {838 t.Errorf("Unexpected error: %v", err)839 }840841 expected = strings.Join([]string{842 "--release",843 ":4",844 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")845846 if output != expected {847 t.Errorf("expected: %q, got: %q", expected, output)848 }849850 // Test required flags for sub-commands851 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd", "")852 if err != nil {853 t.Errorf("Unexpected error: %v", err)854 }855856 expected = strings.Join([]string{857 "--requiredPersistent",858 "-p",859 "--subRequired",860 "-s",861 "subArg",862 ":4",863 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")864865 if output != expected {866 t.Errorf("expected: %q, got: %q", expected, output)867 }868869 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd", "-")870 if err != nil {871 t.Errorf("Unexpected error: %v", err)872 }873874 expected = strings.Join([]string{875 "--requiredPersistent",876 "-p",877 "--subRequired",878 "-s",879 ":4",880 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")881882 if output != expected {883 t.Errorf("expected: %q, got: %q", expected, output)884 }885886 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd", "--subNot")887 if err != nil {888 t.Errorf("Unexpected error: %v", err)889 }890891 expected = strings.Join([]string{892 "--subNotRequired",893 ":4",894 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")895896 if output != expected {897 t.Errorf("expected: %q, got: %q", expected, output)898 }899900 // Test that when a required flag is present, it is not suggested anymore901 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--requiredFlag", "1", "")902 if err != nil {903 t.Errorf("Unexpected error: %v", err)904 }905 // Reset the flag for the next command906 requiredFlag.Changed = false907908 expected = strings.Join([]string{909 "--requiredPersistent",910 "-p",911 "realArg",912 ":4",913 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")914915 if output != expected {916 t.Errorf("expected: %q, got: %q", expected, output)917 }918919 // Test that when a persistent required flag is present, it is not suggested anymore920 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--requiredPersistent", "1", "")921 if err != nil {922 t.Errorf("Unexpected error: %v", err)923 }924 // Reset the flag for the next command925 requiredPersistent.Changed = false926927 expected = strings.Join([]string{928 "childCmd",929 "help",930 "--requiredFlag",931 "-r",932 "realArg",933 ":4",934 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")935936 if output != expected {937 t.Errorf("expected: %q, got: %q", expected, output)938 }939940 // Test that when all required flags are present, normal completion is done941 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--requiredFlag", "1", "--requiredPersistent", "1", "")942 if err != nil {943 t.Errorf("Unexpected error: %v", err)944 }945 // Reset the flags for the next command946 requiredFlag.Changed = false947 requiredPersistent.Changed = false948949 expected = strings.Join([]string{950 "realArg",951 ":4",952 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")953954 if output != expected {955 t.Errorf("expected: %q, got: %q", expected, output)956 }957}958959func TestFlagFileExtFilterCompletionInGo(t *testing.T) {960 rootCmd := &Command{961 Use: "root",962 Run: emptyRun,963 }964965 // No extensions. Should be ignored.966 rootCmd.Flags().StringP("file", "f", "", "file flag")967 assertNoErr(t, rootCmd.MarkFlagFilename("file"))968969 // Single extension970 rootCmd.Flags().StringP("log", "l", "", "log flag")971 assertNoErr(t, rootCmd.MarkFlagFilename("log", "log"))972973 // Multiple extensions974 rootCmd.Flags().StringP("yaml", "y", "", "yaml flag")975 assertNoErr(t, rootCmd.MarkFlagFilename("yaml", "yaml", "yml"))976977 // Directly using annotation978 rootCmd.Flags().StringP("text", "t", "", "text flag")979 assertNoErr(t, rootCmd.Flags().SetAnnotation("text", BashCompFilenameExt, []string{"txt"}))980981 // Test that the completion logic returns the proper info for the completion982 // script to handle the file filtering983 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--file", "")984 if err != nil {985 t.Errorf("Unexpected error: %v", err)986 }987988 expected := strings.Join([]string{989 ":0",990 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")991992 if output != expected {993 t.Errorf("expected: %q, got: %q", expected, output)994 }995996 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--log", "")997 if err != nil {998 t.Errorf("Unexpected error: %v", err)999 }10001001 expected = strings.Join([]string{1002 "log",1003 ":8",1004 "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")10051006 if output != expected {1007 t.Errorf("expected: %q, got: %q", expected, output)1008 }10091010 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--yaml", "")1011 if err != nil {1012 t.Errorf("Unexpected error: %v", err)1013 }10141015 expected = strings.Join([]string{1016 "yaml", "yml",1017 ":8",1018 "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")10191020 if output != expected {1021 t.Errorf("expected: %q, got: %q", expected, output)1022 }10231024 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--yaml=")1025 if err != nil {1026 t.Errorf("Unexpected error: %v", err)1027 }10281029 expected = strings.Join([]string{1030 "yaml", "yml",1031 ":8",1032 "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")10331034 if output != expected {1035 t.Errorf("expected: %q, got: %q", expected, output)1036 }10371038 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-y", "")1039 if err != nil {1040 t.Errorf("Unexpected error: %v", err)1041 }10421043 expected = strings.Join([]string{1044 "yaml", "yml",1045 ":8",1046 "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")10471048 if output != expected {1049 t.Errorf("expected: %q, got: %q", expected, output)1050 }10511052 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-y=")1053 if err != nil {1054 t.Errorf("Unexpected error: %v", err)1055 }10561057 expected = strings.Join([]string{1058 "yaml", "yml",1059 ":8",1060 "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")10611062 if output != expected {1063 t.Errorf("expected: %q, got: %q", expected, output)1064 }10651066 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--text", "")1067 if err != nil {1068 t.Errorf("Unexpected error: %v", err)1069 }10701071 expected = strings.Join([]string{1072 "txt",1073 ":8",1074 "Completion ended with directive: ShellCompDirectiveFilterFileExt", ""}, "\n")10751076 if output != expected {1077 t.Errorf("expected: %q, got: %q", expected, output)1078 }1079}10801081func TestFlagDirFilterCompletionInGo(t *testing.T) {1082 rootCmd := &Command{1083 Use: "root",1084 Run: emptyRun,1085 }10861087 // Filter directories1088 rootCmd.Flags().StringP("dir", "d", "", "dir flag")1089 assertNoErr(t, rootCmd.MarkFlagDirname("dir"))10901091 // Filter directories within a directory1092 rootCmd.Flags().StringP("subdir", "s", "", "subdir")1093 assertNoErr(t, rootCmd.Flags().SetAnnotation("subdir", BashCompSubdirsInDir, []string{"themes"}))10941095 // Multiple directory specification get ignored1096 rootCmd.Flags().StringP("manydir", "m", "", "manydir")1097 assertNoErr(t, rootCmd.Flags().SetAnnotation("manydir", BashCompSubdirsInDir, []string{"themes", "colors"}))10981099 // Test that the completion logic returns the proper info for the completion1100 // script to handle the directory filtering1101 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--dir", "")1102 if err != nil {1103 t.Errorf("Unexpected error: %v", err)1104 }11051106 expected := strings.Join([]string{1107 ":16",1108 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")11091110 if output != expected {1111 t.Errorf("expected: %q, got: %q", expected, output)1112 }11131114 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-d", "")1115 if err != nil {1116 t.Errorf("Unexpected error: %v", err)1117 }11181119 expected = strings.Join([]string{1120 ":16",1121 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")11221123 if output != expected {1124 t.Errorf("expected: %q, got: %q", expected, output)1125 }11261127 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--subdir", "")1128 if err != nil {1129 t.Errorf("Unexpected error: %v", err)1130 }11311132 expected = strings.Join([]string{1133 "themes",1134 ":16",1135 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")11361137 if output != expected {1138 t.Errorf("expected: %q, got: %q", expected, output)1139 }11401141 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--subdir=")1142 if err != nil {1143 t.Errorf("Unexpected error: %v", err)1144 }11451146 expected = strings.Join([]string{1147 "themes",1148 ":16",1149 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")11501151 if output != expected {1152 t.Errorf("expected: %q, got: %q", expected, output)1153 }11541155 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-s", "")1156 if err != nil {1157 t.Errorf("Unexpected error: %v", err)1158 }11591160 expected = strings.Join([]string{1161 "themes",1162 ":16",1163 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")11641165 if output != expected {1166 t.Errorf("expected: %q, got: %q", expected, output)1167 }11681169 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "-s=")1170 if err != nil {1171 t.Errorf("Unexpected error: %v", err)1172 }11731174 expected = strings.Join([]string{1175 "themes",1176 ":16",1177 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")11781179 if output != expected {1180 t.Errorf("expected: %q, got: %q", expected, output)1181 }11821183 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--manydir", "")1184 if err != nil {1185 t.Errorf("Unexpected error: %v", err)1186 }11871188 expected = strings.Join([]string{1189 ":16",1190 "Completion ended with directive: ShellCompDirectiveFilterDirs", ""}, "\n")11911192 if output != expected {1193 t.Errorf("expected: %q, got: %q", expected, output)1194 }1195}11961197func TestValidArgsFuncSingleCmd(t *testing.T) {1198 rootCmd := &Command{1199 Use: "root",1200 ValidArgsFunction: validArgsFunc,1201 Run: emptyRun,1202 }12031204 // Test completing an empty string1205 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")1206 if err != nil {1207 t.Errorf("Unexpected error: %v", err)1208 }12091210 expected := strings.Join([]string{1211 "one",1212 "two",1213 ":0",1214 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")12151216 if output != expected {1217 t.Errorf("expected: %q, got: %q", expected, output)1218 }12191220 // Check completing with a prefix1221 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")1222 if err != nil {1223 t.Errorf("Unexpected error: %v", err)1224 }12251226 expected = strings.Join([]string{1227 "two",1228 ":0",1229 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")12301231 if output != expected {1232 t.Errorf("expected: %q, got: %q", expected, output)1233 }1234}12351236func TestValidArgsFuncSingleCmdInvalidArg(t *testing.T) {1237 rootCmd := &Command{1238 Use: "root",1239 // If we don't specify a value for Args, this test fails.1240 // This is only true for a root command without any subcommands, and is caused1241 // by the fact that the __complete command becomes a subcommand when there should not be one.1242 // The problem is in the implementation of legacyArgs().1243 Args: MinimumNArgs(1),1244 ValidArgsFunction: validArgsFunc,1245 Run: emptyRun,1246 }12471248 // Check completing with wrong number of args1249 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "unexpectedArg", "t")1250 if err != nil {1251 t.Errorf("Unexpected error: %v", err)1252 }12531254 expected := strings.Join([]string{1255 ":4",1256 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")12571258 if output != expected {1259 t.Errorf("expected: %q, got: %q", expected, output)1260 }1261}12621263func TestValidArgsFuncChildCmds(t *testing.T) {1264 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1265 child1Cmd := &Command{1266 Use: "child1",1267 ValidArgsFunction: validArgsFunc,1268 Run: emptyRun,1269 }1270 child2Cmd := &Command{1271 Use: "child2",1272 ValidArgsFunction: validArgsFunc2,1273 Run: emptyRun,1274 }1275 rootCmd.AddCommand(child1Cmd, child2Cmd)12761277 // Test completion of first sub-command with empty argument1278 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child1", "")1279 if err != nil {1280 t.Errorf("Unexpected error: %v", err)1281 }12821283 expected := strings.Join([]string{1284 "one",1285 "two",1286 ":0",1287 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")12881289 if output != expected {1290 t.Errorf("expected: %q, got: %q", expected, output)1291 }12921293 // Test completion of first sub-command with a prefix to complete1294 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child1", "t")1295 if err != nil {1296 t.Errorf("Unexpected error: %v", err)1297 }12981299 expected = strings.Join([]string{1300 "two",1301 ":0",1302 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")13031304 if output != expected {1305 t.Errorf("expected: %q, got: %q", expected, output)1306 }13071308 // Check completing with wrong number of args1309 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child1", "unexpectedArg", "t")1310 if err != nil {1311 t.Errorf("Unexpected error: %v", err)1312 }13131314 expected = strings.Join([]string{1315 ":4",1316 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")13171318 if output != expected {1319 t.Errorf("expected: %q, got: %q", expected, output)1320 }13211322 // Test completion of second sub-command with empty argument1323 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child2", "")1324 if err != nil {1325 t.Errorf("Unexpected error: %v", err)1326 }13271328 expected = strings.Join([]string{1329 "three",1330 "four",1331 ":0",1332 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")13331334 if output != expected {1335 t.Errorf("expected: %q, got: %q", expected, output)1336 }13371338 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child2", "t")1339 if err != nil {1340 t.Errorf("Unexpected error: %v", err)1341 }13421343 expected = strings.Join([]string{1344 "three",1345 ":0",1346 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")13471348 if output != expected {1349 t.Errorf("expected: %q, got: %q", expected, output)1350 }13511352 // Check completing with wrong number of args1353 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child2", "unexpectedArg", "t")1354 if err != nil {1355 t.Errorf("Unexpected error: %v", err)1356 }13571358 expected = strings.Join([]string{1359 ":4",1360 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")13611362 if output != expected {1363 t.Errorf("expected: %q, got: %q", expected, output)1364 }1365}13661367func TestValidArgsFuncAliases(t *testing.T) {1368 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1369 child := &Command{1370 Use: "child",1371 Aliases: []string{"son", "daughter"},1372 ValidArgsFunction: validArgsFunc,1373 Run: emptyRun,1374 }1375 rootCmd.AddCommand(child)13761377 // Test completion of first sub-command with empty argument1378 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "son", "")1379 if err != nil {1380 t.Errorf("Unexpected error: %v", err)1381 }13821383 expected := strings.Join([]string{1384 "one",1385 "two",1386 ":0",1387 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")13881389 if output != expected {1390 t.Errorf("expected: %q, got: %q", expected, output)1391 }13921393 // Test completion of first sub-command with a prefix to complete1394 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "daughter", "t")1395 if err != nil {1396 t.Errorf("Unexpected error: %v", err)1397 }13981399 expected = strings.Join([]string{1400 "two",1401 ":0",1402 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")14031404 if output != expected {1405 t.Errorf("expected: %q, got: %q", expected, output)1406 }14071408 // Check completing with wrong number of args1409 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "son", "unexpectedArg", "t")1410 if err != nil {1411 t.Errorf("Unexpected error: %v", err)1412 }14131414 expected = strings.Join([]string{1415 ":4",1416 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")14171418 if output != expected {1419 t.Errorf("expected: %q, got: %q", expected, output)1420 }1421}14221423func TestValidArgsFuncInBashScript(t *testing.T) {1424 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1425 child := &Command{1426 Use: "child",1427 ValidArgsFunction: validArgsFunc,1428 Run: emptyRun,1429 }1430 rootCmd.AddCommand(child)14311432 buf := new(bytes.Buffer)1433 assertNoErr(t, rootCmd.GenBashCompletion(buf))1434 output := buf.String()14351436 check(t, output, "has_completion_function=1")1437}14381439func TestNoValidArgsFuncInBashScript(t *testing.T) {1440 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1441 child := &Command{1442 Use: "child",1443 Run: emptyRun,1444 }1445 rootCmd.AddCommand(child)14461447 buf := new(bytes.Buffer)1448 assertNoErr(t, rootCmd.GenBashCompletion(buf))1449 output := buf.String()14501451 checkOmit(t, output, "has_completion_function=1")1452}14531454func TestCompleteCmdInBashScript(t *testing.T) {1455 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1456 child := &Command{1457 Use: "child",1458 ValidArgsFunction: validArgsFunc,1459 Run: emptyRun,1460 }1461 rootCmd.AddCommand(child)14621463 buf := new(bytes.Buffer)1464 assertNoErr(t, rootCmd.GenBashCompletion(buf))1465 output := buf.String()14661467 check(t, output, ShellCompNoDescRequestCmd)1468}14691470func TestCompleteNoDesCmdInZshScript(t *testing.T) {1471 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1472 child := &Command{1473 Use: "child",1474 ValidArgsFunction: validArgsFunc,1475 Run: emptyRun,1476 }1477 rootCmd.AddCommand(child)14781479 buf := new(bytes.Buffer)1480 assertNoErr(t, rootCmd.GenZshCompletionNoDesc(buf))1481 output := buf.String()14821483 check(t, output, ShellCompNoDescRequestCmd)1484}14851486func TestCompleteCmdInZshScript(t *testing.T) {1487 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1488 child := &Command{1489 Use: "child",1490 ValidArgsFunction: validArgsFunc,1491 Run: emptyRun,1492 }1493 rootCmd.AddCommand(child)14941495 buf := new(bytes.Buffer)1496 assertNoErr(t, rootCmd.GenZshCompletion(buf))1497 output := buf.String()14981499 check(t, output, ShellCompRequestCmd)1500 checkOmit(t, output, ShellCompNoDescRequestCmd)1501}15021503func TestFlagCompletionInGo(t *testing.T) {1504 rootCmd := &Command{1505 Use: "root",1506 Run: emptyRun,1507 }1508 rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")1509 assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1510 completions := []string{}1511 for _, comp := range []string{"1\tThe first", "2\tThe second", "10\tThe tenth"} {1512 if strings.HasPrefix(comp, toComplete) {1513 completions = append(completions, comp)1514 }1515 }1516 return completions, ShellCompDirectiveDefault1517 }))1518 rootCmd.Flags().String("filename", "", "Enter a filename")1519 assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1520 completions := []string{}1521 for _, comp := range []string{"file.yaml\tYAML format", "myfile.json\tJSON format", "file.xml\tXML format"} {1522 if strings.HasPrefix(comp, toComplete) {1523 completions = append(completions, comp)1524 }1525 }1526 return completions, ShellCompDirectiveNoSpace | ShellCompDirectiveNoFileComp1527 }))15281529 // Test completing an empty string1530 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--introot", "")1531 if err != nil {1532 t.Errorf("Unexpected error: %v", err)1533 }15341535 expected := strings.Join([]string{1536 "1",1537 "2",1538 "10",1539 ":0",1540 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")15411542 if output != expected {1543 t.Errorf("expected: %q, got: %q", expected, output)1544 }15451546 // Check completing with a prefix1547 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--introot", "1")1548 if err != nil {1549 t.Errorf("Unexpected error: %v", err)1550 }15511552 expected = strings.Join([]string{1553 "1",1554 "10",1555 ":0",1556 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")15571558 if output != expected {1559 t.Errorf("expected: %q, got: %q", expected, output)1560 }15611562 // Test completing an empty string1563 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--filename", "")1564 if err != nil {1565 t.Errorf("Unexpected error: %v", err)1566 }15671568 expected = strings.Join([]string{1569 "file.yaml",1570 "myfile.json",1571 "file.xml",1572 ":6",1573 "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")15741575 if output != expected {1576 t.Errorf("expected: %q, got: %q", expected, output)1577 }15781579 // Check completing with a prefix1580 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--filename", "f")1581 if err != nil {1582 t.Errorf("Unexpected error: %v", err)1583 }15841585 expected = strings.Join([]string{1586 "file.yaml",1587 "file.xml",1588 ":6",1589 "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")15901591 if output != expected {1592 t.Errorf("expected: %q, got: %q", expected, output)1593 }1594}15951596func TestValidArgsFuncChildCmdsWithDesc(t *testing.T) {1597 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1598 child1Cmd := &Command{1599 Use: "child1",1600 ValidArgsFunction: validArgsFunc,1601 Run: emptyRun,1602 }1603 child2Cmd := &Command{1604 Use: "child2",1605 ValidArgsFunction: validArgsFunc2,1606 Run: emptyRun,1607 }1608 rootCmd.AddCommand(child1Cmd, child2Cmd)16091610 // Test completion of first sub-command with empty argument1611 output, err := executeCommand(rootCmd, ShellCompRequestCmd, "child1", "")1612 if err != nil {1613 t.Errorf("Unexpected error: %v", err)1614 }16151616 expected := strings.Join([]string{1617 "one\tThe first",1618 "two\tThe second",1619 ":0",1620 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")16211622 if output != expected {1623 t.Errorf("expected: %q, got: %q", expected, output)1624 }16251626 // Test completion of first sub-command with a prefix to complete1627 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child1", "t")1628 if err != nil {1629 t.Errorf("Unexpected error: %v", err)1630 }16311632 expected = strings.Join([]string{1633 "two\tThe second",1634 ":0",1635 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")16361637 if output != expected {1638 t.Errorf("expected: %q, got: %q", expected, output)1639 }16401641 // Check completing with wrong number of args1642 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child1", "unexpectedArg", "t")1643 if err != nil {1644 t.Errorf("Unexpected error: %v", err)1645 }16461647 expected = strings.Join([]string{1648 ":4",1649 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")16501651 if output != expected {1652 t.Errorf("expected: %q, got: %q", expected, output)1653 }16541655 // Test completion of second sub-command with empty argument1656 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "")1657 if err != nil {1658 t.Errorf("Unexpected error: %v", err)1659 }16601661 expected = strings.Join([]string{1662 "three\tThe third",1663 "four\tThe fourth",1664 ":0",1665 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")16661667 if output != expected {1668 t.Errorf("expected: %q, got: %q", expected, output)1669 }16701671 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "t")1672 if err != nil {1673 t.Errorf("Unexpected error: %v", err)1674 }16751676 expected = strings.Join([]string{1677 "three\tThe third",1678 ":0",1679 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")16801681 if output != expected {1682 t.Errorf("expected: %q, got: %q", expected, output)1683 }16841685 // Check completing with wrong number of args1686 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "child2", "unexpectedArg", "t")1687 if err != nil {1688 t.Errorf("Unexpected error: %v", err)1689 }16901691 expected = strings.Join([]string{1692 ":4",1693 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")16941695 if output != expected {1696 t.Errorf("expected: %q, got: %q", expected, output)1697 }1698}16991700func TestFlagCompletionInGoWithDesc(t *testing.T) {1701 rootCmd := &Command{1702 Use: "root",1703 Run: emptyRun,1704 }1705 rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")1706 assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("introot", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1707 completions := []string{}1708 for _, comp := range []string{"1\tThe first", "2\tThe second", "10\tThe tenth"} {1709 if strings.HasPrefix(comp, toComplete) {1710 completions = append(completions, comp)1711 }1712 }1713 return completions, ShellCompDirectiveDefault1714 }))1715 rootCmd.Flags().String("filename", "", "Enter a filename")1716 assertNoErr(t, rootCmd.RegisterFlagCompletionFunc("filename", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1717 completions := []string{}1718 for _, comp := range []string{"file.yaml\tYAML format", "myfile.json\tJSON format", "file.xml\tXML format"} {1719 if strings.HasPrefix(comp, toComplete) {1720 completions = append(completions, comp)1721 }1722 }1723 return completions, ShellCompDirectiveNoSpace | ShellCompDirectiveNoFileComp1724 }))17251726 // Test completing an empty string1727 output, err := executeCommand(rootCmd, ShellCompRequestCmd, "--introot", "")1728 if err != nil {1729 t.Errorf("Unexpected error: %v", err)1730 }17311732 expected := strings.Join([]string{1733 "1\tThe first",1734 "2\tThe second",1735 "10\tThe tenth",1736 ":0",1737 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")17381739 if output != expected {1740 t.Errorf("expected: %q, got: %q", expected, output)1741 }17421743 // Check completing with a prefix1744 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--introot", "1")1745 if err != nil {1746 t.Errorf("Unexpected error: %v", err)1747 }17481749 expected = strings.Join([]string{1750 "1\tThe first",1751 "10\tThe tenth",1752 ":0",1753 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")17541755 if output != expected {1756 t.Errorf("expected: %q, got: %q", expected, output)1757 }17581759 // Test completing an empty string1760 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--filename", "")1761 if err != nil {1762 t.Errorf("Unexpected error: %v", err)1763 }17641765 expected = strings.Join([]string{1766 "file.yaml\tYAML format",1767 "myfile.json\tJSON format",1768 "file.xml\tXML format",1769 ":6",1770 "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")17711772 if output != expected {1773 t.Errorf("expected: %q, got: %q", expected, output)1774 }17751776 // Check completing with a prefix1777 output, err = executeCommand(rootCmd, ShellCompRequestCmd, "--filename", "f")1778 if err != nil {1779 t.Errorf("Unexpected error: %v", err)1780 }17811782 expected = strings.Join([]string{1783 "file.yaml\tYAML format",1784 "file.xml\tXML format",1785 ":6",1786 "Completion ended with directive: ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp", ""}, "\n")17871788 if output != expected {1789 t.Errorf("expected: %q, got: %q", expected, output)1790 }1791}17921793func TestValidArgsNotValidArgsFunc(t *testing.T) {1794 rootCmd := &Command{1795 Use: "root",1796 ValidArgs: []string{"one", "two"},1797 ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1798 return []string{"three", "four"}, ShellCompDirectiveNoFileComp1799 },1800 Run: emptyRun,1801 }18021803 // Test that if both ValidArgs and ValidArgsFunction are present1804 // only ValidArgs is considered1805 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")1806 if err != nil {1807 t.Errorf("Unexpected error: %v", err)1808 }18091810 expected := strings.Join([]string{1811 "one",1812 "two",1813 ":4",1814 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")18151816 if output != expected {1817 t.Errorf("expected: %q, got: %q", expected, output)1818 }18191820 // Check completing with a prefix1821 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")1822 if err != nil {1823 t.Errorf("Unexpected error: %v", err)1824 }18251826 expected = strings.Join([]string{1827 "two",1828 ":4",1829 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")18301831 if output != expected {1832 t.Errorf("expected: %q, got: %q", expected, output)1833 }1834}18351836func TestArgAliasesCompletionInGo(t *testing.T) {1837 rootCmd := &Command{1838 Use: "root",1839 Args: OnlyValidArgs,1840 ValidArgs: []string{"one", "two", "three"},1841 ArgAliases: []string{"un", "deux", "trois"},1842 Run: emptyRun,1843 }18441845 // Test that argaliases are not completed when there are validargs that match1846 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")1847 if err != nil {1848 t.Errorf("Unexpected error: %v", err)1849 }18501851 expected := strings.Join([]string{1852 "one",1853 "two",1854 "three",1855 ":4",1856 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")18571858 if output != expected {1859 t.Errorf("expected: %q, got: %q", expected, output)1860 }18611862 // Test that argaliases are not completed when there are validargs that match using a prefix1863 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "t")1864 if err != nil {1865 t.Errorf("Unexpected error: %v", err)1866 }18671868 expected = strings.Join([]string{1869 "two",1870 "three",1871 ":4",1872 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")18731874 if output != expected {1875 t.Errorf("expected: %q, got: %q", expected, output)1876 }18771878 // Test that argaliases are completed when there are no validargs that match1879 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "tr")1880 if err != nil {1881 t.Errorf("Unexpected error: %v", err)1882 }18831884 expected = strings.Join([]string{1885 "trois",1886 ":4",1887 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")18881889 if output != expected {1890 t.Errorf("expected: %q, got: %q", expected, output)1891 }1892}18931894func TestCompleteHelp(t *testing.T) {1895 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1896 child1Cmd := &Command{1897 Use: "child1",1898 Run: emptyRun,1899 }1900 child2Cmd := &Command{1901 Use: "child2",1902 Run: emptyRun,1903 }1904 rootCmd.AddCommand(child1Cmd, child2Cmd)19051906 child3Cmd := &Command{1907 Use: "child3",1908 Run: emptyRun,1909 }1910 child1Cmd.AddCommand(child3Cmd)19111912 // Test that completion includes the help command1913 output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "")1914 if err != nil {1915 t.Errorf("Unexpected error: %v", err)1916 }19171918 expected := strings.Join([]string{1919 "child1",1920 "child2",1921 "help",1922 ":4",1923 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")19241925 if output != expected {1926 t.Errorf("expected: %q, got: %q", expected, output)1927 }19281929 // Test sub-commands are completed on first level of help command1930 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "help", "")1931 if err != nil {1932 t.Errorf("Unexpected error: %v", err)1933 }19341935 expected = strings.Join([]string{1936 "child1",1937 "child2",1938 "help", // "<program> help help" is a valid command, so should be completed1939 ":4",1940 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")19411942 if output != expected {1943 t.Errorf("expected: %q, got: %q", expected, output)1944 }19451946 // Test sub-commands are completed on first level of help command1947 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "help", "child1", "")1948 if err != nil {1949 t.Errorf("Unexpected error: %v", err)1950 }19511952 expected = strings.Join([]string{1953 "child3",1954 ":4",1955 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")19561957 if output != expected {1958 t.Errorf("expected: %q, got: %q", expected, output)1959 }1960}
deleted:custom_completions.go-557 removed
1package cobra23import (4 "fmt"5 "os"6 "strings"78 "github.com/spf13/pflag"9)1011const (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 scripts.14 ShellCompRequestCmd = "__complete"15 // ShellCompNoDescRequestCmd is the name of the hidden command that is used to request16 // completion results without their description. It is used by the shell completion scripts.17 ShellCompNoDescRequestCmd = "__completeNoDesc"18)1920// Global map of flag completion functions.21var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){}2223// ShellCompDirective is a bit map representing the different behaviors the shell24// can be instructed to have once completions have been provided.25type ShellCompDirective int2627const (28 // ShellCompDirectiveError indicates an error occurred and completions should be ignored.29 ShellCompDirectiveError ShellCompDirective = 1 << iota3031 // ShellCompDirectiveNoSpace indicates that the shell should not add a space32 // after the completion even if there is a single completion provided.33 ShellCompDirectiveNoSpace3435 // ShellCompDirectiveNoFileComp indicates that the shell should not provide36 // file completion even when no completion is provided.37 // This currently does not work for zsh or bash < 438 ShellCompDirectiveNoFileComp3940 // ShellCompDirectiveFilterFileExt indicates that the provided completions41 // should be used as file extension filters.42 // For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename()43 // is a shortcut to using this directive explicitly. The BashCompFilenameExt44 // annotation can also be used to obtain the same behavior for flags.45 ShellCompDirectiveFilterFileExt4647 // ShellCompDirectiveFilterDirs indicates that only directory names should48 // be provided in file completion. To request directory names within another49 // directory, the returned completions should specify the directory within50 // which to search. The BashCompSubdirsInDir annotation can be used to51 // obtain the same behavior but only for flags.52 ShellCompDirectiveFilterDirs5354 // ===========================================================================5556 // All directives using iota should be above this one.57 // For internal use.58 shellCompDirectiveMaxValue5960 // ShellCompDirectiveDefault indicates to let the shell perform its default61 // behavior after completions have been provided.62 // This one must be last to avoid messing up the iota count.63 ShellCompDirectiveDefault ShellCompDirective = 064)6566// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.67func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error {68 flag := c.Flag(flagName)69 if flag == nil {70 return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName)71 }72 if _, exists := flagCompletionFunctions[flag]; exists {73 return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName)74 }75 flagCompletionFunctions[flag] = f76 return nil77}7879// Returns a string listing the different directive enabled in the specified parameter80func (d ShellCompDirective) string() string {81 var directives []string82 if d&ShellCompDirectiveError != 0 {83 directives = append(directives, "ShellCompDirectiveError")84 }85 if d&ShellCompDirectiveNoSpace != 0 {86 directives = append(directives, "ShellCompDirectiveNoSpace")87 }88 if d&ShellCompDirectiveNoFileComp != 0 {89 directives = append(directives, "ShellCompDirectiveNoFileComp")90 }91 if d&ShellCompDirectiveFilterFileExt != 0 {92 directives = append(directives, "ShellCompDirectiveFilterFileExt")93 }94 if d&ShellCompDirectiveFilterDirs != 0 {95 directives = append(directives, "ShellCompDirectiveFilterDirs")96 }97 if len(directives) == 0 {98 directives = append(directives, "ShellCompDirectiveDefault")99 }100101 if d >= shellCompDirectiveMaxValue {102 return fmt.Sprintf("ERROR: unexpected ShellCompDirective value: %d", d)103 }104 return strings.Join(directives, ", ")105}106107// Adds a special hidden command that can be used to request custom completions.108func (c *Command) initCompleteCmd(args []string) {109 completeCmd := &Command{110 Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd),111 Aliases: []string{ShellCompNoDescRequestCmd},112 DisableFlagsInUseLine: true,113 Hidden: true,114 DisableFlagParsing: true,115 Args: MinimumNArgs(1),116 Short: "Request shell completion choices for the specified command-line",117 Long: fmt.Sprintf("%[2]s is a special command that is used by the shell completion logic\n%[1]s",118 "to request completion choices for the specified command-line.", ShellCompRequestCmd),119 Run: func(cmd *Command, args []string) {120 finalCmd, completions, directive, err := cmd.getCompletions(args)121 if err != nil {122 CompErrorln(err.Error())123 // Keep going for multiple reasons:124 // 1- There could be some valid completions even though there was an error125 // 2- Even without completions, we need to print the directive126 }127128 noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd)129 for _, comp := range completions {130 if noDescriptions {131 // Remove any description that may be included following a tab character.132 comp = strings.Split(comp, "\t")[0]133 }134135 // Make sure we only write the first line to the output.136 // This is needed if a description contains a linebreak.137 // Otherwise the shell scripts will interpret the other lines as new flags138 // and could therefore provide a wrong completion.139 comp = strings.Split(comp, "\n")[0]140141 // Finally trim the completion. This is especially important to get rid142 // of a trailing tab when there are no description following it.143 // For example, a sub-command without a description should not be completed144 // with a tab at the end (or else zsh will show a -- following it145 // although there is no description).146 comp = strings.TrimSpace(comp)147148 // Print each possible completion to stdout for the completion script to consume.149 fmt.Fprintln(finalCmd.OutOrStdout(), comp)150 }151152 if directive >= shellCompDirectiveMaxValue {153 directive = ShellCompDirectiveDefault154 }155156 // As the last printout, print the completion directive for the completion script to parse.157 // The directive integer must be that last character following a single colon (:).158 // The completion script expects :<directive>159 fmt.Fprintf(finalCmd.OutOrStdout(), ":%d\n", directive)160161 // Print some helpful info to stderr for the user to understand.162 // Output from stderr must be ignored by the completion script.163 fmt.Fprintf(finalCmd.ErrOrStderr(), "Completion ended with directive: %s\n", directive.string())164 },165 }166 c.AddCommand(completeCmd)167 subCmd, _, err := c.Find(args)168 if err != nil || subCmd.Name() != ShellCompRequestCmd {169 // Only create this special command if it is actually being called.170 // This reduces possible side-effects of creating such a command;171 // for example, having this command would cause problems to a172 // cobra program that only consists of the root command, since this173 // command would cause the root command to suddenly have a subcommand.174 c.RemoveCommand(completeCmd)175 }176}177178func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) {179 // The last argument, which is not completely typed by the user,180 // should not be part of the list of arguments181 toComplete := args[len(args)-1]182 trimmedArgs := args[:len(args)-1]183184 var finalCmd *Command185 var finalArgs []string186 var err error187 // Find the real command for which completion must be performed188 // check if we need to traverse here to parse local flags on parent commands189 if c.Root().TraverseChildren {190 finalCmd, finalArgs, err = c.Root().Traverse(trimmedArgs)191 } else {192 finalCmd, finalArgs, err = c.Root().Find(trimmedArgs)193 }194 if err != nil {195 // Unable to find the real command. E.g., <program> someInvalidCmd <TAB>196 return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)197 }198199 // Check if we are doing flag value completion before parsing the flags.200 // This is important because if we are completing a flag value, we need to also201 // remove the flag name argument from the list of finalArgs or else the parsing202 // could fail due to an invalid value (incomplete) for the flag.203 flag, finalArgs, toComplete, err := checkIfFlagCompletion(finalCmd, finalArgs, toComplete)204 if err != nil {205 // Error while attempting to parse flags206 return finalCmd, []string{}, ShellCompDirectiveDefault, err207 }208209 // Parse the flags early so we can check if required flags are set210 if err = finalCmd.ParseFlags(finalArgs); err != nil {211 return finalCmd, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())212 }213214 if flag != nil {215 // Check if we are completing a flag value subject to annotations216 if validExts, present := flag.Annotations[BashCompFilenameExt]; present {217 if len(validExts) != 0 {218 // File completion filtered by extensions219 return finalCmd, validExts, ShellCompDirectiveFilterFileExt, nil220 }221222 // The annotation requests simple file completion. There is no reason to do223 // that since it is the default behavior anyway. Let's ignore this annotation224 // in case the program also registered a completion function for this flag.225 // Even though it is a mistake on the program's side, let's be nice when we can.226 }227228 if subDir, present := flag.Annotations[BashCompSubdirsInDir]; present {229 if len(subDir) == 1 {230 // Directory completion from within a directory231 return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil232 }233 // Directory completion234 return finalCmd, []string{}, ShellCompDirectiveFilterDirs, nil235 }236 }237238 // When doing completion of a flag name, as soon as an argument starts with239 // a '-' we know it is a flag. We cannot use isFlagArg() here as it requires240 // the flag name to be complete241 if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") {242 var completions []string243244 // First check for required flags245 completions = completeRequireFlags(finalCmd, toComplete)246247 // If we have not found any required flags, only then can we show regular flags248 if len(completions) == 0 {249 doCompleteFlags := func(flag *pflag.Flag) {250 if !flag.Changed ||251 strings.Contains(flag.Value.Type(), "Slice") ||252 strings.Contains(flag.Value.Type(), "Array") {253 // If the flag is not already present, or if it can be specified multiple times (Array or Slice)254 // we suggest it as a completion255 completions = append(completions, getFlagNameCompletions(flag, toComplete)...)256 }257 }258259 // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands260 // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and261 // non-inherited flags.262 finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {263 doCompleteFlags(flag)264 })265 finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {266 doCompleteFlags(flag)267 })268 }269270 directive := ShellCompDirectiveNoFileComp271 if len(completions) == 1 && strings.HasSuffix(completions[0], "=") {272 // If there is a single completion, the shell usually adds a space273 // after the completion. We don't want that if the flag ends with an =274 directive = ShellCompDirectiveNoSpace275 }276 return finalCmd, completions, directive, nil277 }278279 // We only remove the flags from the arguments if DisableFlagParsing is not set.280 // This is important for commands which have requested to do their own flag completion.281 if !finalCmd.DisableFlagParsing {282 finalArgs = finalCmd.Flags().Args()283 }284285 var completions []string286 directive := ShellCompDirectiveDefault287 if flag == nil {288 foundLocalNonPersistentFlag := false289 // If TraverseChildren is true on the root command we don't check for290 // local flags because we can use a local flag on a parent command291 if !finalCmd.Root().TraverseChildren {292 // Check if there are any local, non-persistent flags on the command-line293 localNonPersistentFlags := finalCmd.LocalNonPersistentFlags()294 finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {295 if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed {296 foundLocalNonPersistentFlag = true297 }298 })299 }300301 // Complete subcommand names, including the help command302 if len(finalArgs) == 0 && !foundLocalNonPersistentFlag {303 // We only complete sub-commands if:304 // - there are no arguments on the command-line and305 // - there are no local, non-peristent flag on the command-line or TraverseChildren is true306 for _, subCmd := range finalCmd.Commands() {307 if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand {308 if strings.HasPrefix(subCmd.Name(), toComplete) {309 completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))310 }311 directive = ShellCompDirectiveNoFileComp312 }313 }314 }315316 // Complete required flags even without the '-' prefix317 completions = append(completions, completeRequireFlags(finalCmd, toComplete)...)318319 // Always complete ValidArgs, even if we are completing a subcommand name.320 // This is for commands that have both subcommands and ValidArgs.321 if len(finalCmd.ValidArgs) > 0 {322 if len(finalArgs) == 0 {323 // ValidArgs are only for the first argument324 for _, validArg := range finalCmd.ValidArgs {325 if strings.HasPrefix(validArg, toComplete) {326 completions = append(completions, validArg)327 }328 }329 directive = ShellCompDirectiveNoFileComp330331 // If no completions were found within commands or ValidArgs,332 // see if there are any ArgAliases that should be completed.333 if len(completions) == 0 {334 for _, argAlias := range finalCmd.ArgAliases {335 if strings.HasPrefix(argAlias, toComplete) {336 completions = append(completions, argAlias)337 }338 }339 }340 }341342 // If there are ValidArgs specified (even if they don't match), we stop completion.343 // Only one of ValidArgs or ValidArgsFunction can be used for a single command.344 return finalCmd, completions, directive, nil345 }346347 // Let the logic continue so as to add any ValidArgsFunction completions,348 // even if we already found sub-commands.349 // This is for commands that have subcommands but also specify a ValidArgsFunction.350 }351352 // Find the completion function for the flag or command353 var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)354 if flag != nil {355 completionFn = flagCompletionFunctions[flag]356 } else {357 completionFn = finalCmd.ValidArgsFunction358 }359 if completionFn != nil {360 // Go custom completion defined for this flag or command.361 // Call the registered completion function to get the completions.362 var comps []string363 comps, directive = completionFn(finalCmd, finalArgs, toComplete)364 completions = append(completions, comps...)365 }366367 return finalCmd, completions, directive, nil368}369370func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string {371 if nonCompletableFlag(flag) {372 return []string{}373 }374375 var completions []string376 flagName := "--" + flag.Name377 if strings.HasPrefix(flagName, toComplete) {378 // Flag without the =379 completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))380381 // Why suggest both long forms: --flag and --flag= ?382 // This forces the user to *always* have to type either an = or a space after the flag name.383 // Let's be nice and avoid making users have to do that.384 // Since boolean flags and shortname flags don't show the = form, let's go that route and never show it.385 // The = form will still work, we just won't suggest it.386 // This also makes the list of suggested flags shorter as we avoid all the = forms.387 //388 // if len(flag.NoOptDefVal) == 0 {389 // // Flag requires a value, so it can be suffixed with =390 // flagName += "="391 // completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))392 // }393 }394395 flagName = "-" + flag.Shorthand396 if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) {397 completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))398 }399400 return completions401}402403func completeRequireFlags(finalCmd *Command, toComplete string) []string {404 var completions []string405406 doCompleteRequiredFlags := func(flag *pflag.Flag) {407 if _, present := flag.Annotations[BashCompOneRequiredFlag]; present {408 if !flag.Changed {409 // If the flag is not already present, we suggest it as a completion410 completions = append(completions, getFlagNameCompletions(flag, toComplete)...)411 }412 }413 }414415 // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands416 // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and417 // non-inherited flags.418 finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {419 doCompleteRequiredFlags(flag)420 })421 finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {422 doCompleteRequiredFlags(flag)423 })424425 return completions426}427428func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) {429 if finalCmd.DisableFlagParsing {430 // We only do flag completion if we are allowed to parse flags431 // This is important for commands which have requested to do their own flag completion.432 return nil, args, lastArg, nil433 }434435 var flagName string436 trimmedArgs := args437 flagWithEqual := false438439 // When doing completion of a flag name, as soon as an argument starts with440 // a '-' we know it is a flag. We cannot use isFlagArg() here as that function441 // requires the flag name to be complete442 if len(lastArg) > 0 && lastArg[0] == '-' {443 if index := strings.Index(lastArg, "="); index >= 0 {444 // Flag with an =445 flagName = strings.TrimLeft(lastArg[:index], "-")446 lastArg = lastArg[index+1:]447 flagWithEqual = true448 } else {449 // Normal flag completion450 return nil, args, lastArg, nil451 }452 }453454 if len(flagName) == 0 {455 if len(args) > 0 {456 prevArg := args[len(args)-1]457 if isFlagArg(prevArg) {458 // Only consider the case where the flag does not contain an =.459 // If the flag contains an = it means it has already been fully processed,460 // so we don't need to deal with it here.461 if index := strings.Index(prevArg, "="); index < 0 {462 flagName = strings.TrimLeft(prevArg, "-")463464 // Remove the uncompleted flag or else there could be an error created465 // for an invalid value for that flag466 trimmedArgs = args[:len(args)-1]467 }468 }469 }470 }471472 if len(flagName) == 0 {473 // Not doing flag completion474 return nil, trimmedArgs, lastArg, nil475 }476477 flag := findFlag(finalCmd, flagName)478 if flag == nil {479 // Flag not supported by this command, nothing to complete480 err := fmt.Errorf("Subcommand '%s' does not support flag '%s'", finalCmd.Name(), flagName)481 return nil, nil, "", err482 }483484 if !flagWithEqual {485 if len(flag.NoOptDefVal) != 0 {486 // We had assumed dealing with a two-word flag but the flag is a boolean flag.487 // In that case, there is no value following it, so we are not really doing flag completion.488 // Reset everything to do noun completion.489 trimmedArgs = args490 flag = nil491 }492 }493494 return flag, trimmedArgs, lastArg, nil495}496497func findFlag(cmd *Command, name string) *pflag.Flag {498 flagSet := cmd.Flags()499 if len(name) == 1 {500 // First convert the short flag into a long flag501 // as the cmd.Flag() search only accepts long flags502 if short := flagSet.ShorthandLookup(name); short != nil {503 name = short.Name504 } else {505 set := cmd.InheritedFlags()506 if short = set.ShorthandLookup(name); short != nil {507 name = short.Name508 } else {509 return nil510 }511 }512 }513 return cmd.Flag(name)514}515516// CompDebug prints the specified string to the same file as where the517// completion script prints its logs.518// Note that completion printouts should never be on stdout as they would519// be wrongly interpreted as actual completion choices by the completion script.520func CompDebug(msg string, printToStdErr bool) {521 msg = fmt.Sprintf("[Debug] %s", msg)522523 // Such logs are only printed when the user has set the environment524 // variable BASH_COMP_DEBUG_FILE to the path of some file to be used.525 if path := os.Getenv("BASH_COMP_DEBUG_FILE"); path != "" {526 f, err := os.OpenFile(path,527 os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)528 if err == nil {529 defer f.Close()530 WriteStringAndCheck(f, msg)531 }532 }533534 if printToStdErr {535 // Must print to stderr for this not to be read by the completion script.536 fmt.Fprint(os.Stderr, msg)537 }538}539540// CompDebugln prints the specified string with a newline at the end541// to the same file as where the completion script prints its logs.542// Such logs are only printed when the user has set the environment543// variable BASH_COMP_DEBUG_FILE to the path of some file to be used.544func CompDebugln(msg string, printToStdErr bool) {545 CompDebug(fmt.Sprintf("%s\n", msg), printToStdErr)546}547548// CompError prints the specified completion message to stderr.549func CompError(msg string) {550 msg = fmt.Sprintf("[Error] %s", msg)551 CompDebug(msg, true)552}553554// CompErrorln prints the specified completion message to stderr with a newline at the end.555func CompErrorln(msg string) {556 CompError(fmt.Sprintf("%s\n", msg))557}
modified:shell_completions.md+30 added-1 removed
5 unmodified lines
6- Zsh7- fish8- PowerShell910Cobra will automatically provide your program with a fully functional `completion` command,11similarly to how it provides the `help` command.1213## Creating your own completion command1415If you do not wish to use the default `completion` command, you can choose to16provide your own, which will take precedence over the default one. (This also provides17backwards-compatibility with programs that already have their own `completion` command.)1819If you are using the generator, you can create a completion command by running2021```bash22cobra add completion
55 unmodified lines
78 cmd.Root().GenZshCompletion(os.Stdout)79 case "fish":80 cmd.Root().GenFishCompletion(os.Stdout, true)81 case "powershell":73 cmd.Root().GenPowerShellCompletion(os.Stdout)82 cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout)83 }84 },85}86```8788**Note:** The cobra generator may include messages printed to stdout, for example, if the config file is loaded; this will break the auto-completion script so must be removed.8990## Adapting the default completion command9192Cobra provides a few options for the default `completion` command. To configure such options you must set93the `CompletionOptions` field on the *root* command.9495To tell Cobra *not* to provide the default `completion` command:96```97rootCmd.CompletionOptions.DisableDefaultCmd = true98```99100To tell Cobra *not* to provide the user with the `--no-descriptions` flag to the completion sub-commands:101```102rootCmd.CompletionOptions.DisableNoDescFlag = true103```104105To tell Cobra to completely disable descriptions for completions:106```107rootCmd.CompletionOptions.DisableDescriptions = true108```109110# Customizing completions111112The generated completion scripts will automatically handle completing commands and flags. However, you can make your completions much more powerful by providing information to complete your program's nouns and flag values.113
399 unmodified lines