Skip to content
Myr

Add 'one required flag' group (#1952)

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

authored by Martijn Evers · committed by GitHub · parent dcb405a · Browse files · 4 files+228 added−12 removed
This commit

State

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

Diff stats

4 files+228 added−12 removed

  • other:+228 added−12 removed

4 files+228 added−12 removed

modified:site/content/user_guide.md+10 added-1 removed
347 unmodified lines
348rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")349rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")350```351352If you want to require at least one flag from a group to be present, you can use `MarkFlagsOneRequired`.353This can be combined with `MarkFlagsMutuallyExclusive` to enforce exactly one flag from a given group:354```go355rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON")356rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML")357rootCmd.MarkFlagsOneRequired("json", "yaml")358rootCmd.MarkFlagsMutuallyExclusive("json", "yaml")359```360352In both of these cases:361In these cases:362 - both local and persistent flags can be used363 - **NOTE:** the group is only enforced on commands where every flag is defined364 - a flag may appear in multiple groups365 - a group may contain any number of flags
375 unmodified lines
modified:completions_test.go+98 added
2828 unmodified lines
2829 })2830 }2831}28322833func TestCompletionForOneRequiredGroupFlags(t *testing.T) {2834 getCmd := func() *Command {2835 rootCmd := &Command{2836 Use: "root",2837 Run: emptyRun,2838 }2839 childCmd := &Command{2840 Use: "child",2841 ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {2842 return []string{"subArg"}, ShellCompDirectiveNoFileComp2843 },2844 Run: emptyRun,2845 }2846 rootCmd.AddCommand(childCmd)28472848 rootCmd.PersistentFlags().Int("ingroup1", -1, "ingroup1")2849 rootCmd.PersistentFlags().String("ingroup2", "", "ingroup2")28502851 childCmd.Flags().Bool("ingroup3", false, "ingroup3")2852 childCmd.Flags().Bool("nogroup", false, "nogroup")28532854 // Add flags to a group2855 childCmd.MarkFlagsOneRequired("ingroup1", "ingroup2", "ingroup3")28562857 return rootCmd2858 }28592860 // Each test case uses a unique command from the function above.2861 testcases := []struct {2862 desc string2863 args []string2864 expectedOutput string2865 }{2866 {2867 desc: "flags in group suggested without - prefix",2868 args: []string{"child", ""},2869 expectedOutput: strings.Join([]string{2870 "--ingroup1",2871 "--ingroup2",2872 "--ingroup3",2873 "subArg",2874 ":4",2875 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),2876 },2877 {2878 desc: "flags in group suggested with - prefix",2879 args: []string{"child", "-"},2880 expectedOutput: strings.Join([]string{2881 "--ingroup1",2882 "--ingroup2",2883 "--ingroup3",2884 ":4",2885 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),2886 },2887 {2888 desc: "when any flag in group present, other flags in group not suggested without - prefix",2889 args: []string{"child", "--ingroup2", "value", ""},2890 expectedOutput: strings.Join([]string{2891 "subArg",2892 ":4",2893 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),2894 },2895 {2896 desc: "when all flags in group present, flags not suggested without - prefix",2897 args: []string{"child", "--ingroup1", "8", "--ingroup2", "value2", "--ingroup3", ""},2898 expectedOutput: strings.Join([]string{2899 "subArg",2900 ":4",2901 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),2902 },2903 {2904 desc: "group ignored if some flags not applicable",2905 args: []string{"--ingroup2", "value", ""},2906 expectedOutput: strings.Join([]string{2907 "child",2908 "completion",2909 "help",2910 ":4",2911 "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n"),2912 },2913 }29142915 for _, tc := range testcases {2916 t.Run(tc.desc, func(t *testing.T) {2917 c := getCmd()2918 args := []string{ShellCompNoDescRequestCmd}2919 args = append(args, tc.args...)2920 output, err := executeCommand(c, args...)2921 switch {2922 case err == nil && output != tc.expectedOutput:2923 t.Errorf("expected: %q, got: %q", tc.expectedOutput, output)2924 case err != nil:2925 t.Errorf("Unexpected error %q", err)2926 }2927 })2928 }2929}29302931func TestCompletionForMutuallyExclusiveFlags(t *testing.T) {2932 getCmd := func() *Command {2933 rootCmd := &Command{2934 Use: "root",
345 unmodified lines
modified:flag_groups_test.go+53 added-10 removed
41 unmodified lines
42 }4344 // Each test case uses a unique command from the function above.45 testcases := []struct {46 desc string47 flagGroupsRequired []string48 flagGroupsExclusive []string49 subCmdFlagGroupsRequired []string50 subCmdFlagGroupsExclusive []string51 args []string52 expectErr string46 desc string47 flagGroupsRequired []string48 flagGroupsOneRequired []string49 flagGroupsExclusive []string50 subCmdFlagGroupsRequired []string51 subCmdFlagGroupsOneRequired []string52 subCmdFlagGroupsExclusive []string53 args []string54 expectErr string55 }{56 {57 desc: "No flags no problem",58 }, {
5 unmodified lines
64 flagGroupsRequired: []string{"a b c"},65 args: []string{"--a=foo"},66 expectErr: "if any flags in the group [a b c] are set they must all be set; missing [b c]",67 }, {68 desc: "One-required flag group not satisfied",69 flagGroupsOneRequired: []string{"a b"},70 args: []string{"--c=foo"},71 expectErr: "at least one of the flags in the group [a b] is required",72 }, {73 desc: "Exclusive flag group not satisfied",74 flagGroupsExclusive: []string{"a b c"},75 args: []string{"--a=foo", "--b=foo"},76 expectErr: "if any flags in the group [a b c] are set none of the others can be; [a b] were all set",
2 unmodified lines
79 flagGroupsRequired: []string{"a b c", "a d"},80 args: []string{"--c=foo", "--d=foo"},81 expectErr: `if any flags in the group [a b c] are set they must all be set; missing [a b]`,82 }, {83 desc: "Multiple one-required flag group not satisfied returns first error",84 flagGroupsOneRequired: []string{"a b", "d e"},85 args: []string{"--c=foo", "--f=foo"},86 expectErr: `at least one of the flags in the group [a b] is required`,87 }, {88 desc: "Multiple exclusive flag group not satisfied returns first error",89 flagGroupsExclusive: []string{"a b c", "a d"},90 args: []string{"--a=foo", "--c=foo", "--d=foo"},91 expectErr: `if any flags in the group [a b c] are set none of the others can be; [a c] were all set`,
2 unmodified lines
94 flagGroupsRequired: []string{"a d", "a b", "a c"},95 args: []string{"--a=foo"},96 expectErr: `if any flags in the group [a b] are set they must all be set; missing [b]`,97 }, {98 desc: "Validation of one-required groups occurs on groups in sorted order",99 flagGroupsOneRequired: []string{"d e", "a b", "f g"},100 args: []string{"--c=foo"},101 expectErr: `at least one of the flags in the group [a b] is required`,102 }, {103 desc: "Validation of exclusive groups occurs on groups in sorted order",104 flagGroupsExclusive: []string{"a d", "a b", "a c"},105 args: []string{"--a=foo", "--b=foo", "--c=foo"},106 expectErr: `if any flags in the group [a b] are set none of the others can be; [a b] were all set`,107 }, {91 desc: "Persistent flags utilize both features and can fail required groups",108 desc: "Persistent flags utilize required and exclusive groups and can fail required groups",109 flagGroupsRequired: []string{"a e", "e f"},110 flagGroupsExclusive: []string{"f g"},111 args: []string{"--a=foo", "--f=foo", "--g=foo"},112 expectErr: `if any flags in the group [a e] are set they must all be set; missing [e]`,113 }, {97 desc: "Persistent flags utilize both features and can fail mutually exclusive groups",114 desc: "Persistent flags utilize one-required and exclusive groups and can fail one-required groups",115 flagGroupsOneRequired: []string{"a b", "e f"},116 flagGroupsExclusive: []string{"e f"},117 args: []string{"--e=foo"},118 expectErr: `at least one of the flags in the group [a b] is required`,119 }, {120 desc: "Persistent flags utilize required and exclusive groups and can fail mutually exclusive groups",121 flagGroupsRequired: []string{"a e", "e f"},122 flagGroupsExclusive: []string{"f g"},123 args: []string{"--a=foo", "--e=foo", "--f=foo", "--g=foo"},124 expectErr: `if any flags in the group [f g] are set none of the others can be; [f g] were all set`,125 }, {103 desc: "Persistent flags utilize both features and can pass",126 desc: "Persistent flags utilize required and exclusive groups and can pass",127 flagGroupsRequired: []string{"a e", "e f"},128 flagGroupsExclusive: []string{"f g"},129 args: []string{"--a=foo", "--e=foo", "--f=foo"},130 }, {131 desc: "Persistent flags utilize one-required and exclusive groups and can pass",132 flagGroupsOneRequired: []string{"a e", "e f"},133 flagGroupsExclusive: []string{"f g"},134 args: []string{"--a=foo", "--e=foo", "--f=foo"},135 }, {136 desc: "Subcmds can use required groups using inherited flags",137 subCmdFlagGroupsRequired: []string{"e subonly"},138 args: []string{"subcmd", "--e=foo", "--subonly=foo"},139 }, {140 desc: "Subcmds can use one-required groups using inherited flags",141 subCmdFlagGroupsOneRequired: []string{"e subonly"},142 args: []string{"subcmd", "--e=foo", "--subonly=foo"},143 }, {144 desc: "Subcmds can use one-required groups using inherited flags and fail one-required groups",145 subCmdFlagGroupsOneRequired: []string{"e subonly"},146 args: []string{"subcmd"},147 expectErr: "at least one of the flags in the group [e subonly] is required",148 }, {149 desc: "Subcmds can use exclusive groups using inherited flags",150 subCmdFlagGroupsExclusive: []string{"e subonly"},151 args: []string{"subcmd", "--e=foo", "--subonly=foo"},152 expectErr: "if any flags in the group [e subonly] are set none of the others can be; [e subonly] were all set",
13 unmodified lines
166 sub := c.Commands()[0]167 for _, flagGroup := range tc.flagGroupsRequired {168 c.MarkFlagsRequiredTogether(strings.Split(flagGroup, " ")...)169 }170 for _, flagGroup := range tc.flagGroupsOneRequired {171 c.MarkFlagsOneRequired(strings.Split(flagGroup, " ")...)172 }173 for _, flagGroup := range tc.flagGroupsExclusive {174 c.MarkFlagsMutuallyExclusive(strings.Split(flagGroup, " ")...)175 }176 for _, flagGroup := range tc.subCmdFlagGroupsRequired {177 sub.MarkFlagsRequiredTogether(strings.Split(flagGroup, " ")...)178 }179 for _, flagGroup := range tc.subCmdFlagGroupsOneRequired {180 sub.MarkFlagsOneRequired(strings.Split(flagGroup, " ")...)181 }182 for _, flagGroup := range tc.subCmdFlagGroupsExclusive {183 sub.MarkFlagsMutuallyExclusive(strings.Split(flagGroup, " ")...)184 }185 c.SetArgs(tc.args)
10 unmodified lines
modified:flag_groups.go+67 added-1 removed
22 unmodified lines
23)2425const (26 requiredAsGroup = "cobra_annotation_required_if_others_set"27 oneRequired = "cobra_annotation_one_required"28 mutuallyExclusive = "cobra_annotation_mutually_exclusive"29)3031// MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors
11 unmodified lines
43 }44 }45}4647// MarkFlagsOneRequired marks the given flags with annotations so that Cobra errors48// if the command is invoked without at least one flag from the given set of flags.49func (c *Command) MarkFlagsOneRequired(flagNames ...string) {50 c.mergePersistentFlags()51 for _, v := range flagNames {52 f := c.Flags().Lookup(v)53 if f == nil {54 panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a one-required flag group", v))55 }56 if err := c.Flags().SetAnnotation(v, oneRequired, append(f.Annotations[oneRequired], strings.Join(flagNames, " "))); err != nil {57 // Only errs if the flag isn't found.58 panic(err)59 }60 }61}6263// MarkFlagsMutuallyExclusive marks the given flags with annotations so that Cobra errors64// if the command is invoked with more than one flag from the given set of flags.65func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) {66 c.mergePersistentFlags()
8 unmodified lines
75 }76 }77}7862// ValidateFlagGroups validates the mutuallyExclusive/requiredAsGroup logic and returns the79// ValidateFlagGroups validates the mutuallyExclusive/oneRequired/requiredAsGroup logic and returns the80// first error encountered.81func (c *Command) ValidateFlagGroups() error {82 if c.DisableFlagParsing {83 return nil
3 unmodified lines
8788 // groupStatus format is the list of flags as a unique ID,89 // then a map of each flag name and whether it is set or not.90 groupStatus := map[string]map[string]bool{}91 oneRequiredGroupStatus := map[string]map[string]bool{}92 mutuallyExclusiveGroupStatus := map[string]map[string]bool{}93 flags.VisitAll(func(pflag *flag.Flag) {94 processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus)95 processFlagForGroupAnnotation(flags, pflag, oneRequired, oneRequiredGroupStatus)96 processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus)97 })9899 if err := validateRequiredFlagGroups(groupStatus); err != nil {100 return err101 }102 if err := validateOneRequiredFlagGroups(oneRequiredGroupStatus); err != nil {103 return err104 }105 if err := validateExclusiveFlagGroups(mutuallyExclusiveGroupStatus); err != nil {106 return err107 }108 return nil
54 unmodified lines
163164 return nil165}166167func validateOneRequiredFlagGroups(data map[string]map[string]bool) error {168 keys := sortedKeys(data)169 for _, flagList := range keys {170 flagnameAndStatus := data[flagList]171 var set []string172 for flagname, isSet := range flagnameAndStatus {173 if isSet {174 set = append(set, flagname)175 }176 }177 if len(set) >= 1 {178 continue179 }180181 // Sort values, so they can be tested/scripted against consistently.182 sort.Strings(set)183 return fmt.Errorf("at least one of the flags in the group [%v] is required", flagList)184 }185 return nil186}187188func validateExclusiveFlagGroups(data map[string]map[string]bool) error {189 keys := sortedKeys(data)190 for _, flagList := range keys {191 flagnameAndStatus := data[flagList]
26 unmodified lines
218}219220// enforceFlagGroupsForCompletion will do the following:221// - when a flag in a group is present, other flags in the group will be marked required222// - when none of the flags in a one-required group are present, all flags in the group will be marked required223// - when a flag in a mutually exclusive group is present, other flags in the group will be marked as hidden224// This allows the standard completion logic to behave appropriately for flag groups225func (c *Command) enforceFlagGroupsForCompletion() {226 if c.DisableFlagParsing {
1 unmodified line
228 }229230 flags := c.Flags()231 groupStatus := map[string]map[string]bool{}232 oneRequiredGroupStatus := map[string]map[string]bool{}233 mutuallyExclusiveGroupStatus := map[string]map[string]bool{}234 c.Flags().VisitAll(func(pflag *flag.Flag) {235 processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus)236 processFlagForGroupAnnotation(flags, pflag, oneRequired, oneRequiredGroupStatus)237 processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus)238 })239240 // If a flag that is part of a group is present, we make all the other flags
8 unmodified lines
249 }250 }251 }252253 // If none of the flags of a one-required group are present, we make all the flags254 // of that group required so that the shell completion suggests them automatically255 for flagList, flagnameAndStatus := range oneRequiredGroupStatus {256 set := 0257258 for _, isSet := range flagnameAndStatus {259 if isSet {260 set++261 }262 }263264 // None of the flags of the group are set, mark all flags in the group265 // as required266 if set == 0 {267 for _, fName := range strings.Split(flagList, " ") {268 _ = c.MarkFlagRequired(fName)269 }270 }271 }272273 // If a flag that is mutually exclusive to others is present, we hide the other274 // flags of that group so the shell completion does not suggest them275 for flagList, flagnameAndStatus := range mutuallyExclusiveGroupStatus {276 for flagName, isSet := range flagnameAndStatus {
14 unmodified lines