From b8177f9994e2a580df6e3e7ee5832fdf11749604 Mon Sep 17 00:00:00 2001 From: John Schnake Date: Tue, 5 Apr 2022 11:13:33 -0500 Subject: [PATCH] Add support for persistent flags and test them --- flag_groups.go | 2 ++ flag_groups_test.go | 16 +++++++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/flag_groups.go b/flag_groups.go index 8faad500b..66d02f1b1 100644 --- a/flag_groups.go +++ b/flag_groups.go @@ -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{} @@ -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{} diff --git a/flag_groups_test.go b/flag_groups_test.go index 30508d948..c569fa7f6 100644 --- a/flag_groups_test.go +++ b/flag_groups_test.go @@ -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 } @@ -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 {