Skip to content
Myr

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).

authored by Marc Khouzam · committed by GitHub · parent 680936a · Browse files · 4 files+179 added−13 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@gmail.com>

Diff stats

4 files+179 added−13 removed

  • other:+179 added−13 removed

4 files+179 added−13 removed

modified:site/content/completions/_index.md+2 added-1 removed
6 unmodified lines
7- fish8- PowerShell910Cobra will automatically provide your program with a fully functional `completion` command,11similarly to how it provides the `help` command.11similarly to how it provides the `help` command. If there are no other subcommands, the12default `completion` command will be hidden, but still functional.1314## Creating your own completion command1516If you do not wish to use the default `completion` command, you can choose to
570 unmodified lines
modified:command.go+8 added-7 removed
1095 unmodified lines
1096 }10971098 // 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()11001103 // Now that all commands have been created, let's make sure all groups1104 // are properly created also1105 c.checkCommandGroups()11061101 args := c.args11021103 // 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 lines
1107 if c.args == nil && !isTesting() {1108 args = os.Args[1:]1109 }11101117 // initialize the hidden command to be used for shell completion1111 // initialize the __complete command to be used for shell completion1112 c.initCompleteCmd(args)11131114 // initialize the default completion command1115 c.InitDefaultCompletionCmd(args...)11161117 // Now that all commands have been created, let's make sure all groups1118 // are properly created also1119 c.checkCommandGroups()11201121 var flags []string1122 if c.TraverseChildren {1123 cmd, flags, err = c.Traverse(args)1124 } else {
945 unmodified lines
modified:completions_test.go+141 added-3 removed
2463 unmodified lines
2464 Args: NoArgs,2465 Run: emptyRun,2466 }24672468 // 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 }24762477 // 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)24862487 // Add a sub-command2488 subCmd := &Command{2489 Use: "sub",2490 Run: emptyRun,2491 }
113 unmodified lines
2605}26062607func TestCompleteCompletion(t *testing.T) {2608 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}26092610 // 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 }26162617 expected := strings.Join([]string{2618 ":0",2619 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")26202621 if output != expected {2622 t.Errorf("expected: %q, got: %q", expected, output)2623 }26242625 // 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 }26312632 expected = strings.Join([]string{2633 "bash",2634 "fish",2635 "powershell",2636 "zsh",2637 ":4",2638 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")26392640 if output != expected {2641 t.Errorf("expected: %q, got: %q", expected, output)2642 }26432644 // Add a sub-command2645 subCmd := &Command{2646 Use: "sub",2647 Run: emptyRun,2648 }2649 rootCmd.AddCommand(subCmd)26502651 // 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 }26562610 expected := strings.Join([]string{2657 expected = strings.Join([]string{2658 "bash",2659 "fish",2660 "powershell",2661 "zsh",
1176 unmodified lines
3838 }3839 })3840 }3841}38423843// A test to make sure the InitDefaultCompletionCmd function works as expected3844// in case a project calls it directly.3845func TestInitDefaultCompletionCmd(t *testing.T) {38463847 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 }38963897 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}39013902 expectedNumSubCommands := 03903 if tc.hasChildCmd {3904 rootCmd.AddCommand(childCmd)3905 expectedNumSubCommands++3906 }39073908 if tc.expectCompCmd {3909 expectedNumSubCommands++3910 }39113912 if len(tc.args) > 0 && tc.args[0] == "__complete" {3913 expectedNumSubCommands++3914 }39153916 // Setup the __complete command to mimic real world scenarios3917 rootCmd.initCompleteCmd(tc.args)39183919 // Call the InitDefaultCompletionCmd function directly3920 if tc.args == nil {3921 rootCmd.InitDefaultCompletionCmd()3922 } else {3923 rootCmd.InitDefaultCompletionCmd(tc.args...)3924 }39253926 // 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 lines
726// 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.730func (c *Command) InitDefaultCompletionCmd() {731 if c.CompletionOptions.DisableDefaultCmd || !c.HasSubCommands() {730func (c *Command) InitDefaultCompletionCmd(args ...string) {731 if c.CompletionOptions.DisableDefaultCmd {732 return733 }734735 for _, cmd := range c.commands {
4 unmodified lines
740 }741742 haveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions743744 // 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 }753754 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 lines
763 GroupID: c.completionCommandGroupID,764 }765 c.AddCommand(completionCmd)766767 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 }782783 out := c.OutOrStdout()784 noDesc := c.CompletionOptions.DisableDescriptions785 shortDesc := "Generate the autocompletion script for %s"786 bash := &Command{
219 unmodified lines