Remove the default "completion" cmd if it is alone (#1559)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
When a program has no sub-commands, its root command can accept arguments. If we add the default "completion" command to such programs they will now have a sub-command and will no longer accept arguments. What we do instead for this special case, is only add the "completion" command if it is being called, or if it is being completed itself. We want to have the "completion" command for such programs because it will allow the completion of flags and of arguments (if provided by the program).
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@gmail.com>
Diff stats
4 files+179 added−13 removed
- other:+179 added−13 removed
Provenance
- Commit
24ada7f- Tree
17e8400- Author
Marc Khouzam <marc.khouzam@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
680936a
4 files changed+179 added−13 removed
modified:site/content/completions/_index.md+2 added-1 removed
6 unmodified lines7 - fish8 - PowerShell9 10 Cobra will automatically provide your program with a fully functional `completion` command,11-similarly to how it provides the `help` command.11+similarly to how it provides the `help` command. If there are no other subcommands, the12+default `completion` command will be hidden, but still functional.13 14 ## Creating your own completion command15 16 If you do not wish to use the default `completion` command, you can choose to570 unmodified linesmodified:command.go+8 added-7 removed
1095 unmodified lines1096 }1097 1098 // initialize help at the last point to allow for user overriding1099 c.InitDefaultHelpCmd()1100- // initialize completion at the last point to allow for user overriding1101- c.InitDefaultCompletionCmd()1100 1103- // Now that all commands have been created, let's make sure all groups1104- // are properly created also1105- c.checkCommandGroups()1106-1101 args := c.args1102 1103 // If running unit tests, we don't want to take the os.Args, see #155 and #2173.1104 // For example, the following would fail:2 unmodified lines1107 if c.args == nil && !isTesting() {1108 args = os.Args[1:]1109 }1110 1117- // initialize the hidden command to be used for shell completion1111+ // initialize the __complete command to be used for shell completion1112 c.initCompleteCmd(args)1113 1114+ // initialize the default completion command1115+ c.InitDefaultCompletionCmd(args...)1116+1117+ // Now that all commands have been created, let's make sure all groups1118+ // are properly created also1119+ c.checkCommandGroups()1120+1121 var flags []string1122 if c.TraverseChildren {1123 cmd, flags, err = c.Traverse(args)1124 } else {945 unmodified linesmodified:completions_test.go+141 added-3 removed
2463 unmodified lines2464 Args: NoArgs,2465 Run: emptyRun,2466 }2467 2468- // Test that no completion command is created if there are not other sub-commands2468+ // Test that when there are no sub-commands, the completion command is not created if it is not called directly.2469 assertNoErr(t, rootCmd.Execute())2470 for _, cmd := range rootCmd.commands {2471 if cmd.Name() == compCmdName {2472 t.Errorf("Should not have a 'completion' command when there are no other sub-commands of root")2473 break2474 }2475 }2476 2477+ // Test that when there are no sub-commands, the completion command is created when it is called directly.2478+ _, err := executeCommand(rootCmd, compCmdName)2479+ if err != nil {2480+ t.Errorf("Unexpected error: %v", err)2481+ }2482+ // Reset the arguments2483+ rootCmd.args = nil2484+ // Remove completion command for the next test2485+ removeCompCmd(rootCmd)2486+2487+ // Add a sub-command2488 subCmd := &Command{2489 Use: "sub",2490 Run: emptyRun,2491 }113 unmodified lines2605 }2606 2607 func TestCompleteCompletion(t *testing.T) {2608 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}2609+2610+ // Test that when there are no sub-commands, the 'completion' command is not completed2611+ // (because it is not created).2612+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "completion")2613+ if err != nil {2614+ t.Errorf("Unexpected error: %v", err)2615+ }2616+2617+ expected := strings.Join([]string{2618+ ":0",2619+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")2620+2621+ if output != expected {2622+ t.Errorf("expected: %q, got: %q", expected, output)2623+ }2624+2625+ // Test that when there are no sub-commands, completion can be triggered for the default2626+ // 'completion' command2627+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "completion", "")2628+ if err != nil {2629+ t.Errorf("Unexpected error: %v", err)2630+ }2631+2632+ expected = strings.Join([]string{2633+ "bash",2634+ "fish",2635+ "powershell",2636+ "zsh",2637+ ":4",2638+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")2639+2640+ if output != expected {2641+ t.Errorf("expected: %q, got: %q", expected, output)2642+ }2643+2644+ // Add a sub-command2645 subCmd := &Command{2646 Use: "sub",2647 Run: emptyRun,2648 }2649 rootCmd.AddCommand(subCmd)2650 2651 // Test sub-commands of the completion command2605- output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "completion", "")2652+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "completion", "")2653 if err != nil {2654 t.Errorf("Unexpected error: %v", err)2655 }2656 2610- expected := strings.Join([]string{2657+ expected = strings.Join([]string{2658 "bash",2659 "fish",2660 "powershell",2661 "zsh",1176 unmodified lines3838 }3839 })3840 }3841 }3842+3843+// A test to make sure the InitDefaultCompletionCmd function works as expected3844+// in case a project calls it directly.3845+func TestInitDefaultCompletionCmd(t *testing.T) {3846+3847+ testCases := []struct {3848+ desc string3849+ hasChildCmd bool3850+ args []string3851+ expectCompCmd bool3852+ }{3853+ {3854+ desc: "no child command and not calling the completion command",3855+ hasChildCmd: false,3856+ args: []string{"somearg"},3857+ expectCompCmd: false,3858+ },3859+ {3860+ desc: "no child command but calling the completion command",3861+ hasChildCmd: false,3862+ args: []string{"completion"},3863+ expectCompCmd: true,3864+ },3865+ {3866+ desc: "no child command but calling __complete on the root command",3867+ hasChildCmd: false,3868+ args: []string{"__complete", ""},3869+ expectCompCmd: false,3870+ },3871+ {3872+ desc: "no child command but calling __complete on the completion command",3873+ hasChildCmd: false,3874+ args: []string{"__complete", "completion", ""},3875+ expectCompCmd: true,3876+ },3877+ {3878+ desc: "with child command",3879+ hasChildCmd: true,3880+ args: []string{"child"},3881+ expectCompCmd: true,3882+ },3883+ {3884+ desc: "no child command not passing args",3885+ hasChildCmd: false,3886+ args: nil,3887+ expectCompCmd: false,3888+ },3889+ {3890+ desc: "with child command not passing args",3891+ hasChildCmd: true,3892+ args: nil,3893+ expectCompCmd: true,3894+ },3895+ }3896+3897+ for _, tc := range testCases {3898+ t.Run(tc.desc, func(t *testing.T) {3899+ rootCmd := &Command{Use: "root", Run: emptyRun}3900+ childCmd := &Command{Use: "child", Run: emptyRun}3901+3902+ expectedNumSubCommands := 03903+ if tc.hasChildCmd {3904+ rootCmd.AddCommand(childCmd)3905+ expectedNumSubCommands++3906+ }3907+3908+ if tc.expectCompCmd {3909+ expectedNumSubCommands++3910+ }3911+3912+ if len(tc.args) > 0 && tc.args[0] == "__complete" {3913+ expectedNumSubCommands++3914+ }3915+3916+ // Setup the __complete command to mimic real world scenarios3917+ rootCmd.initCompleteCmd(tc.args)3918+3919+ // Call the InitDefaultCompletionCmd function directly3920+ if tc.args == nil {3921+ rootCmd.InitDefaultCompletionCmd()3922+ } else {3923+ rootCmd.InitDefaultCompletionCmd(tc.args...)3924+ }3925+3926+ // Check if the completion command was added3927+ if len(rootCmd.Commands()) != expectedNumSubCommands {3928+ t.Errorf("Expected %d subcommands, got %d", expectedNumSubCommands, len(rootCmd.Commands()))3929+ }3930+ })3931+ }3932+}modified:completions.go+28 added-2 removed
725 unmodified lines726 // This function will do nothing if any of the following is true:727 // 1- the feature has been explicitly disabled by the program,728 // 2- c has no subcommands (to avoid creating one),729 // 3- c already has a 'completion' command provided by the program.730-func (c *Command) InitDefaultCompletionCmd() {731- if c.CompletionOptions.DisableDefaultCmd || !c.HasSubCommands() {730+func (c *Command) InitDefaultCompletionCmd(args ...string) {731+ if c.CompletionOptions.DisableDefaultCmd {732 return733 }734 735 for _, cmd := range c.commands {4 unmodified lines740 }741 742 haveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions743 744+ // Special case to know if there are sub-commands or not.745+ hasSubCommands := false746+ for _, cmd := range c.commands {747+ if cmd.Name() != ShellCompRequestCmd && cmd.Name() != helpCommandName {748+ // We found a real sub-command (not 'help' or '__complete')749+ hasSubCommands = true750+ break751+ }752+ }753+754 completionCmd := &Command{755 Use: compCmdName,756 Short: "Generate the autocompletion script for the specified shell",757 Long: fmt.Sprintf(`Generate the autocompletion script for %[1]s for the specified shell.5 unmodified lines763 GroupID: c.completionCommandGroupID,764 }765 c.AddCommand(completionCmd)766 767+ if !hasSubCommands {768+ // If the 'completion' command will be the only sub-command,769+ // we only create it if it is actually being called.770+ // This avoids breaking programs that would suddenly find themselves with771+ // a subcommand, which would prevent them from accepting arguments.772+ // We also create the 'completion' command if the user is triggering773+ // shell completion for it (prog __complete completion '')774+ subCmd, cmdArgs, err := c.Find(args)775+ if err != nil || subCmd.Name() != compCmdName &&776+ !(subCmd.Name() == ShellCompRequestCmd && len(cmdArgs) > 1 && cmdArgs[0] == compCmdName) {777+ // The completion command is not being called or being completed so we remove it.778+ c.RemoveCommand(completionCmd)779+ return780+ }781+ }782+783 out := c.OutOrStdout()784 noDesc := c.CompletionOptions.DisableDescriptions785 shortDesc := "Generate the autocompletion script for %s"786 bash := &Command{219 unmodified lines