Skip to content

Commit

Permalink
Add support for persistent flags and test them
Browse files Browse the repository at this point in the history
  • Loading branch information
johnSchnake committed Apr 5, 2022
1 parent 5f38f45 commit a92caec
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
2 changes: 2 additions & 0 deletions flag_groups.go
Expand Up @@ -28,6 +28,7 @@ const (

func (c *Command) MarkFlagsRequiredTogether(flagNames ...string) {
for _, v := range flagNames {
c.mergePersistentFlags()
f := c.Flags().Lookup(v)
if f.Annotations == nil {
f.Annotations = map[string][]string{}
Expand All @@ -39,6 +40,7 @@ func (c *Command) MarkFlagsRequiredTogether(flagNames ...string) {

func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) {
for _, v := range flagNames {
c.mergePersistentFlags()
f := c.Flags().Lookup(v)
if f.Annotations == nil {
f.Annotations = map[string][]string{}
Expand Down
16 changes: 15 additions & 1 deletion flag_groups_test.go
Expand Up @@ -25,9 +25,12 @@ func TestValidateFlagGroups(t *testing.T) {
Run: func(cmd *Command, args []string) {
}}
// Define lots of flags to utilize for testing.
for _, v := range []string{"a", "b", "c", "d", "e", "f", "g"} {
for _, v := range []string{"a", "b", "c", "d"} {
c.Flags().String(v, "", "")
}
for _, v := range []string{ "e", "f", "g"} {
c.PersistentFlags().String(v, "", "")
}
return c
}

Expand Down Expand Up @@ -65,6 +68,17 @@ func TestValidateFlagGroups(t *testing.T) {
flagGroupsExclusive: []string{"a b c", "a d"},
args: []string{"testcmd", "--a=foo", "--c=foo", "--d=foo"},
expectErr: "if any flags in the group [a b c] are set none of the others can be; [a c] were all set, if any flags in the group [a d] are set none of the others can be; [a d] were all set",
},{
desc: "Persistent flags utilize both features and can fail",
flagGroupsRequired: []string{"a e", "e f"},
flagGroupsExclusive: []string{"f g"},
args: []string{"testcmd", "--a=foo", "--f=foo", "--g=foo"},
expectErr: "if any flags in the group [a e] are set they must all be set; missing [e], if any flags in the group [e f] are set they must all be set; missing [e], if any flags in the group [f g] are set none of the others can be; [f g] were all set",
},{
desc: "Persistent flags utilize both features and can pass",
flagGroupsRequired: []string{"a e", "e f"},
flagGroupsExclusive: []string{"f g"},
args: []string{"testcmd", "--a=foo", "--e=foo","--f=foo"},
},
}
for _, tc := range testcases {
Expand Down

0 comments on commit a92caec

Please sign in to comment.