Include --help and --version flag in completion (#1813)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Fixes #1786 The --help, -h, --version and -v flags are normally added when the `execute()` function is called on a command. When doing completion we don't call `execute()` so we need to add these flags explicitly to the command being completed. Also, we disable all further completions if the 'help' or 'version' flags are present on the command-line.
authored by Marc Khouzam · committed by GitHub · parent d4040ad · Browse files · 3 files·+257 added−5 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
3 files+257 added−5 removed
- other:+257 added−5 removed
Provenance
- Commit
212ea40- Tree
2503e0f- Author
Marc Khouzam <marc.khouzam@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
d4040ad
3 files changed+257 added−5 removed
modified:command.go+4 added
28 unmodified lines29 30 flag "github.com/spf13/pflag"31 )32 33+const FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra"34+35 // FParseErrWhitelist configures Flag parse errors to be ignored36 type FParseErrWhitelist flag.ParseErrorsWhitelist37 38 // Command is just that, a command for your application.1026 unmodified lines1065 } else {1066 usage += c.Name()1067 }1068 c.Flags().BoolP("help", "h", false, usage)1069+ _ = c.Flags().SetAnnotation("help", FlagSetByCobraAnnotation, []string{"true"})1070 }1071 }1072 1073 // InitDefaultVersionFlag adds default version flag to c.17 unmodified lines1091 c.Flags().BoolP("version", "v", false, usage)1092 } else {1093 c.Flags().Bool("version", false, usage)1094 }1095+ _ = c.Flags().SetAnnotation("version", FlagSetByCobraAnnotation, []string{"true"})1096 }1097 }1098 1099 // InitDefaultHelpCmd adds default help command to c.624 unmodified linesmodified:completions_test.go+229 added-5 removed
491 unmodified lines492 Use: "root",493 Run: emptyRun,494 }495 childCmd := &Command{496- Use: "childCmd",497- Run: emptyRun,496+ Use: "childCmd",497+ Version: "1.2.3",498+ Run: emptyRun,499 }500 rootCmd.AddCommand(childCmd)501 502 rootCmd.Flags().IntP("first", "f", -1, "first flag")25 unmodified lines528 529 expected = strings.Join([]string{530 "--first",531 "-f",532+ "--help",533+ "-h",534 "--second",535 "-s",536 ":4",537 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")25 unmodified lines563 564 expected = strings.Join([]string{565 "--second",566 "-s",567+ "--help",568+ "-h",569 "--subFlag",570+ "--version",571+ "-v",572 ":4",573 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")574 575 if output != expected {6 unmodified lines582 Use: "root",583 Run: emptyRun,584 }585 childCmd := &Command{579- Use: "childCmd",580- Short: "first command",581- Run: emptyRun,586+ Use: "childCmd",587+ Short: "first command",588+ Version: "1.2.3",589+ Run: emptyRun,590 }591 rootCmd.AddCommand(childCmd)592 593 rootCmd.Flags().IntP("first", "f", -1, "first flag\nlonger description for flag")25 unmodified lines619 620 expected = strings.Join([]string{621 "--first\tfirst flag",622 "-f\tfirst flag",623+ "--help\thelp for root",624+ "-h\thelp for root",625 "--second\tsecond flag",626 "-s\tsecond flag",627 ":4",628 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")25 unmodified lines654 655 expected = strings.Join([]string{656 "--second\tsecond flag",657 "-s\tsecond flag",658+ "--help\thelp for childCmd",659+ "-h\thelp for childCmd",660 "--subFlag\tsub flag",661+ "--version\tversion for childCmd",662+ "-v\tversion for childCmd",663 ":4",664 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")665 666 if output != expected {34 unmodified lines701 702 expected := strings.Join([]string{703 "--array",704 "--bslice",705+ "--help",706 "--second",707 "--slice",708 ":4",709 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")13 unmodified lines723 724 expected = strings.Join([]string{725 "--array",726 "--bslice",727+ "--help",728 "--slice",729 ":4",730 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")731 14 unmodified lines746 expected = strings.Join([]string{747 "--array",748 "--bslice",749 "--first",750+ "--help",751 "--second",752 "--slice",753 ":4",754 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")17 unmodified lines772 "--bslice",773 "-b",774 "--first",775 "-f",776+ "--help",777+ "-h",778 "--second",779 "-s",780 "--slice",781 "-l",1028 unmodified lines1810 }1811 1812 expected := strings.Join([]string{1813 "--bool\ttest bool flag",1814+ "--help\thelp for child",1815 "--string\ttest string flag",1816 ":4",1817 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")1818 802 unmodified lines2621 2622 expected := strings.Join([]string{2623 "--persistent",2624 "-p",2625+ "--help",2626+ "-h",2627 "--nonPersistent",2628 "-n",2629 "--flag",2630 "-f",14 unmodified lines2645 // Cobra was not told of any flags, so it returns nothing2646 expected = strings.Join([]string{2647 "--persistent",2648 "-p",2649+ "--help",2650+ "-h",2651 "--nonPersistent",2652 "-n",2653 ":4",2654 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")121 unmodified lines2776 args: []string{"child", "-"},2777 expectedOutput: strings.Join([]string{2778 "--ingroup1",2779 "--ingroup2",2780+ "--help",2781+ "-h",2782 "--ingroup3",2783 "--nogroup",2784 ":4",2785 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),90 unmodified lines2876 args: []string{"child", "-"},2877 expectedOutput: strings.Join([]string{2878 "--ingroup1",2879 "--ingroup2",2880+ "--help",2881+ "-h",2882 "--ingroup3",2883 "--nogroup",2884 ":4",2885 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),2 unmodified lines2888 desc: "when flag in mutually exclusive group present, other flags in group not suggested even with the - prefix",2889 args: []string{"child", "--ingroup1", "8", "-"},2890 expectedOutput: strings.Join([]string{2891 "--ingroup1", // Should be suggested again since it is a slice2892+ "--help",2893+ "-h",2894 "--nogroup",2895 ":4",2896 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),2897 },2898 {2899 desc: "group ignored if some flags not applicable",2900 args: []string{"--ingroup1", "8", "-"},2901 expectedOutput: strings.Join([]string{2902+ "--help",2903+ "-h",2904 "--ingroup1",2905 "--ingroup2",2906 ":4",2907 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),14 unmodified lines2922 }2923 })2924 }2925 }2926+2927+func TestCompletionCobraFlags(t *testing.T) {2928+ getCmd := func() *Command {2929+ rootCmd := &Command{2930+ Use: "root",2931+ Version: "1.1.1",2932+ Run: emptyRun,2933+ }2934+ childCmd := &Command{2935+ Use: "child",2936+ Version: "1.1.1",2937+ Run: emptyRun,2938+ ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {2939+ return []string{"extra"}, ShellCompDirectiveNoFileComp2940+ },2941+ }2942+ childCmd2 := &Command{2943+ Use: "child2",2944+ Version: "1.1.1",2945+ Run: emptyRun,2946+ ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {2947+ return []string{"extra2"}, ShellCompDirectiveNoFileComp2948+ },2949+ }2950+ childCmd3 := &Command{2951+ Use: "child3",2952+ Version: "1.1.1",2953+ Run: emptyRun,2954+ ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {2955+ return []string{"extra3"}, ShellCompDirectiveNoFileComp2956+ },2957+ }2958+2959+ rootCmd.AddCommand(childCmd, childCmd2, childCmd3)2960+2961+ _ = childCmd.Flags().Bool("bool", false, "A bool flag")2962+ _ = childCmd.MarkFlagRequired("bool")2963+2964+ // Have a command that adds its own help and version flag2965+ _ = childCmd2.Flags().BoolP("help", "h", false, "My own help")2966+ _ = childCmd2.Flags().BoolP("version", "v", false, "My own version")2967+2968+ // Have a command that only adds its own -v flag2969+ _ = childCmd3.Flags().BoolP("verbose", "v", false, "Not a version flag")2970+2971+ return rootCmd2972+ }2973+2974+ // Each test case uses a unique command from the function above.2975+ testcases := []struct {2976+ desc string2977+ args []string2978+ expectedOutput string2979+ }{2980+ {2981+ desc: "completion of help and version flags",2982+ args: []string{"-"},2983+ expectedOutput: strings.Join([]string{2984+ "--help",2985+ "-h",2986+ "--version",2987+ "-v",2988+ ":4",2989+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),2990+ },2991+ {2992+ desc: "no completion after --help flag",2993+ args: []string{"--help", ""},2994+ expectedOutput: strings.Join([]string{2995+ ":4",2996+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),2997+ },2998+ {2999+ desc: "no completion after -h flag",3000+ args: []string{"-h", ""},3001+ expectedOutput: strings.Join([]string{3002+ ":4",3003+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),3004+ },3005+ {3006+ desc: "no completion after --version flag",3007+ args: []string{"--version", ""},3008+ expectedOutput: strings.Join([]string{3009+ ":4",3010+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),3011+ },3012+ {3013+ desc: "no completion after -v flag",3014+ args: []string{"-v", ""},3015+ expectedOutput: strings.Join([]string{3016+ ":4",3017+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),3018+ },3019+ {3020+ desc: "no completion after --help flag even with other completions",3021+ args: []string{"child", "--help", ""},3022+ expectedOutput: strings.Join([]string{3023+ ":4",3024+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),3025+ },3026+ {3027+ desc: "no completion after -h flag even with other completions",3028+ args: []string{"child", "-h", ""},3029+ expectedOutput: strings.Join([]string{3030+ ":4",3031+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),3032+ },3033+ {3034+ desc: "no completion after --version flag even with other completions",3035+ args: []string{"child", "--version", ""},3036+ expectedOutput: strings.Join([]string{3037+ ":4",3038+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),3039+ },3040+ {3041+ desc: "no completion after -v flag even with other completions",3042+ args: []string{"child", "-v", ""},3043+ expectedOutput: strings.Join([]string{3044+ ":4",3045+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),3046+ },3047+ {3048+ desc: "no completion after -v flag even with other flag completions",3049+ args: []string{"child", "-v", "-"},3050+ expectedOutput: strings.Join([]string{3051+ ":4",3052+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),3053+ },3054+ {3055+ desc: "completion after --help flag when created by program",3056+ args: []string{"child2", "--help", ""},3057+ expectedOutput: strings.Join([]string{3058+ "extra2",3059+ ":4",3060+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),3061+ },3062+ {3063+ desc: "completion after -h flag when created by program",3064+ args: []string{"child2", "-h", ""},3065+ expectedOutput: strings.Join([]string{3066+ "extra2",3067+ ":4",3068+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),3069+ },3070+ {3071+ desc: "completion after --version flag when created by program",3072+ args: []string{"child2", "--version", ""},3073+ expectedOutput: strings.Join([]string{3074+ "extra2",3075+ ":4",3076+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),3077+ },3078+ {3079+ desc: "completion after -v flag when created by program",3080+ args: []string{"child2", "-v", ""},3081+ expectedOutput: strings.Join([]string{3082+ "extra2",3083+ ":4",3084+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),3085+ },3086+ {3087+ desc: "completion after --version when only -v flag was created by program",3088+ args: []string{"child3", "--version", ""},3089+ expectedOutput: strings.Join([]string{3090+ ":4",3091+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),3092+ },3093+ {3094+ desc: "completion after -v flag when only -v flag was created by program",3095+ args: []string{"child3", "-v", ""},3096+ expectedOutput: strings.Join([]string{3097+ "extra3",3098+ ":4",3099+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),3100+ },3101+ }3102+3103+ for _, tc := range testcases {3104+ t.Run(tc.desc, func(t *testing.T) {3105+ c := getCmd()3106+ args := []string{ShellCompNoDescRequestCmd}3107+ args = append(args, tc.args...)3108+ output, err := executeCommand(c, args...)3109+ switch {3110+ case err == nil && output != tc.expectedOutput:3111+ t.Errorf("expected: %q, got: %q", tc.expectedOutput, output)3112+ case err != nil:3113+ t.Errorf("Unexpected error %q", err)3114+ }3115+ })3116+ }3117+}modified:completions.go+24 added
272 unmodified lines273 return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)274 }275 finalCmd.ctx = c.ctx276 277+ // These flags are normally added when `execute()` is called on `finalCmd`,278+ // however, when doing completion, we don't call `finalCmd.execute()`.279+ // Let's add the --help and --version flag ourselves.280+ finalCmd.InitDefaultHelpFlag()281+ finalCmd.InitDefaultVersionFlag()282+283 // Check if we are doing flag value completion before parsing the flags.284 // This is important because if we are completing a flag value, we need to also285 // remove the flag name argument from the list of finalArgs or else the parsing286 // could fail due to an invalid value (incomplete) for the flag.24 unmodified lines311 return finalCmd, []string{}, ShellCompDirectiveDefault, flagErr312 }313 }314 315+ // Look for the --help or --version flags. If they are present,316+ // there should be no further completions.317+ if helpOrVersionFlagPresent(finalCmd) {318+ return finalCmd, []string{}, ShellCompDirectiveNoFileComp, nil319+ }320+321 // We only remove the flags from the arguments if DisableFlagParsing is not set.322 // This is important for commands which have requested to do their own flag completion.323 if !finalCmd.DisableFlagParsing {324 finalArgs = finalCmd.Flags().Args()163 unmodified lines488 489 return finalCmd, completions, directive, nil490 }491 492+func helpOrVersionFlagPresent(cmd *Command) bool {493+ if versionFlag := cmd.Flags().Lookup("version"); versionFlag != nil &&494+ len(versionFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && versionFlag.Changed {495+ return true496+ }497+ if helpFlag := cmd.Flags().Lookup("help"); helpFlag != nil &&498+ len(helpFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && helpFlag.Changed {499+ return true500+ }501+ return false502+}503+504 func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string {505 if nonCompletableFlag(flag) {506 return []string{}507 }363 unmodified lines