-
Notifications
You must be signed in to change notification settings - Fork 2.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
add MarkIfFlagPresentThenOthersRequired #2200
Open
faizan-siddiqui
wants to merge
8
commits into
spf13:main
Choose a base branch
from
faizan-siddiqui:patch-1
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
ca3972e
add MarkIfFlagPresentThenOthersRequired
faizan-siddiqui 4944350
added test cases
faizan-siddiqui 23cadf7
update test
faizan-siddiqui ad5e8c3
update error message to be more readable
faizan-siddiqui cb45935
add more verbose test cases
faizan-siddiqui 1c44c42
fix comment to say other flags will be marked required instead of sec…
faizan-siddiqui dd7bc42
fix test error message
faizan-siddiqui a9bed3a
Merge branch 'spf13:main' into patch-1
faizan-siddiqui File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -23,9 +23,10 @@ import ( | |
) | ||
|
||
const ( | ||
requiredAsGroupAnnotation = "cobra_annotation_required_if_others_set" | ||
oneRequiredAnnotation = "cobra_annotation_one_required" | ||
mutuallyExclusiveAnnotation = "cobra_annotation_mutually_exclusive" | ||
requiredAsGroupAnnotation = "cobra_annotation_required_if_others_set" | ||
oneRequiredAnnotation = "cobra_annotation_one_required" | ||
mutuallyExclusiveAnnotation = "cobra_annotation_mutually_exclusive" | ||
ifPresentThenOthersRequiredAnnotation = "cobra_annotation_if_present_then_others_required" | ||
) | ||
|
||
// MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors | ||
|
@@ -76,6 +77,25 @@ func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) { | |
} | ||
} | ||
|
||
// MarkIfFlagPresentThenOthersRequired marks the given flags so that if the first flag is set, | ||
// all the other flags become required. | ||
func (c *Command) MarkIfFlagPresentThenOthersRequired(flagNames ...string) { | ||
if len(flagNames) < 2 { | ||
panic("MarkIfFlagPresentThenRequired requires at least two flags") | ||
} | ||
c.mergePersistentFlags() | ||
for _, v := range flagNames { | ||
f := c.Flags().Lookup(v) | ||
if f == nil { | ||
panic(fmt.Sprintf("Failed to find flag %q and mark it as being in an if present then others required flag group", v)) | ||
} | ||
// Each time this is called is a single new entry; this allows it to be a member of multiple groups if needed. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is this tested? I mean covered by a test that will ensure it will stay like this if there is a future refactoring |
||
if err := c.Flags().SetAnnotation(v, ifPresentThenOthersRequiredAnnotation, append(f.Annotations[ifPresentThenOthersRequiredAnnotation], strings.Join(flagNames, " "))); err != nil { | ||
panic(err) | ||
} | ||
} | ||
} | ||
|
||
// ValidateFlagGroups validates the mutuallyExclusive/oneRequired/requiredAsGroup logic and returns the | ||
// first error encountered. | ||
func (c *Command) ValidateFlagGroups() error { | ||
|
@@ -90,10 +110,12 @@ func (c *Command) ValidateFlagGroups() error { | |
groupStatus := map[string]map[string]bool{} | ||
oneRequiredGroupStatus := map[string]map[string]bool{} | ||
mutuallyExclusiveGroupStatus := map[string]map[string]bool{} | ||
ifPresentThenOthersRequiredGroupStatus := map[string]map[string]bool{} | ||
flags.VisitAll(func(pflag *flag.Flag) { | ||
processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus) | ||
processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus) | ||
processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus) | ||
processFlagForGroupAnnotation(flags, pflag, ifPresentThenOthersRequiredAnnotation, ifPresentThenOthersRequiredGroupStatus) | ||
}) | ||
|
||
if err := validateRequiredFlagGroups(groupStatus); err != nil { | ||
|
@@ -105,6 +127,9 @@ func (c *Command) ValidateFlagGroups() error { | |
if err := validateExclusiveFlagGroups(mutuallyExclusiveGroupStatus); err != nil { | ||
return err | ||
} | ||
if err := validateIfPresentThenRequiredFlagGroups(ifPresentThenOthersRequiredGroupStatus); err != nil { | ||
return err | ||
} | ||
return nil | ||
} | ||
|
||
|
@@ -206,6 +231,38 @@ func validateExclusiveFlagGroups(data map[string]map[string]bool) error { | |
return nil | ||
} | ||
|
||
func validateIfPresentThenRequiredFlagGroups(data map[string]map[string]bool) error { | ||
for flagList, flagnameAndStatus := range data { | ||
flags := strings.Split(flagList, " ") | ||
primaryFlag := flags[0] | ||
remainingFlags := flags[1:] | ||
|
||
// Handle missing primary flag entry | ||
if _, exists := flagnameAndStatus[primaryFlag]; !exists { | ||
flagnameAndStatus[primaryFlag] = false | ||
} | ||
|
||
// Check if the primary flag is set | ||
if flagnameAndStatus[primaryFlag] { | ||
var unset []string | ||
for _, flag := range remainingFlags { | ||
if !flagnameAndStatus[flag] { | ||
unset = append(unset, flag) | ||
} | ||
} | ||
|
||
// If any dependent flags are unset, trigger an error | ||
if len(unset) > 0 { | ||
return fmt.Errorf( | ||
"%v is set, the following flags must be provided: %v", | ||
primaryFlag, unset, | ||
) | ||
} | ||
} | ||
} | ||
return nil | ||
} | ||
|
||
func sortedKeys(m map[string]map[string]bool) []string { | ||
keys := make([]string, len(m)) | ||
i := 0 | ||
|
@@ -221,6 +278,7 @@ func sortedKeys(m map[string]map[string]bool) []string { | |
// - when a flag in a group is present, other flags in the group will be marked required | ||
// - when none of the flags in a one-required group are present, all flags in the group will be marked required | ||
// - when a flag in a mutually exclusive group is present, other flags in the group will be marked as hidden | ||
// - when the first flag in an if-present-then-required group is present, the other flags will be marked as required | ||
// This allows the standard completion logic to behave appropriately for flag groups | ||
func (c *Command) enforceFlagGroupsForCompletion() { | ||
if c.DisableFlagParsing { | ||
|
@@ -231,10 +289,12 @@ func (c *Command) enforceFlagGroupsForCompletion() { | |
groupStatus := map[string]map[string]bool{} | ||
oneRequiredGroupStatus := map[string]map[string]bool{} | ||
mutuallyExclusiveGroupStatus := map[string]map[string]bool{} | ||
ifPresentThenRequiredGroupStatus := map[string]map[string]bool{} | ||
c.Flags().VisitAll(func(pflag *flag.Flag) { | ||
processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus) | ||
processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus) | ||
processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus) | ||
processFlagForGroupAnnotation(flags, pflag, ifPresentThenOthersRequiredAnnotation, ifPresentThenRequiredGroupStatus) | ||
}) | ||
|
||
// If a flag that is part of a group is present, we make all the other flags | ||
|
@@ -287,4 +347,17 @@ func (c *Command) enforceFlagGroupsForCompletion() { | |
} | ||
} | ||
} | ||
|
||
// If a flag that is marked as if-present-then-required is present, make other flags in the group required | ||
for flagList, flagnameAndStatus := range ifPresentThenRequiredGroupStatus { | ||
flags := strings.Split(flagList, " ") | ||
primaryFlag := flags[0] | ||
remainingFlags := flags[1:] | ||
|
||
if flagnameAndStatus[primaryFlag] { | ||
for _, fName := range remainingFlags { | ||
_ = c.MarkFlagRequired(fName) | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could you rename them in a way they share a common prefix, not suffix
These constants are defined at the package level, so IDE will suggest them in any method when coding in that package
I would like to see something like this
The names of the constants are just suggestions to give you an idea