add MarkIfFlagPresentThenOthersRequired
This PR introduces a new flag group function, MarkIfFlagPresentThenOthersRequired, which enforces a "one-way required together" relationship among flags. This means that if a primary flag is set, then other dependent flags must also be set. This allows users to make certain flags conditionally required based on the presence of another flag, while maintaining flexibility when the primary flag is not provided.
Example
Consider a command called get-range that uses the flags --start and --end to specify a date range. By default, the command can run without either flag, using default start and end values (e.g., start=someDefaultStart and end=Now). However, you may want to enforce that if the user specifies an --end, they must also specify a --start.
cmd := &cobra.Command{
Use: "get-range",
}
cmd.Flags().String("start", "", "Start date")
cmd.Flags().String("end", "", "End date")
// If --end is set, --start is required
cmd.MarkIfFlagPresentThenRequired("end", "start")
- If the command is called with only
--end=value, it will trigger an error because--startis missing. - If called without any flags or only with
--start, it will run using the default values or the provided start date.
This change makes it easier to enforce dependencies between flags while allowing flexible defaults when the primary flag is not specified.
@marckhouzam Would love to get this in thanks! Let me know if you have any questions :)
@dpetersen @markbates @EdwardBetts Would love to get this in thanks! Let me know if you have any questions :)
@marckhouzam is there anything we can do to get this moving? Alternatively we're happy to have discussions about it being out of scope, it just felt fairly obviously useful to us.
I like the idea. I’ll put it on my queue to review. Thank you.
Hi @ccoVeille thank you for the review, I have committed your suggested changes
This PR exceeds the recommended size of 200 lines. Please make sure you are NOT addressing multiple issues with one PR. Note this PR might be rejected due to its size.
This PR exceeds the recommended size of 200 lines. Please make sure you are NOT addressing multiple issues with one PR. Note this PR might be rejected due to its size.
Thanks @ccoVeille I have addressed your comment and added an explicit test case for ensuring the annotation is appended as expected and is guarded against future refactorings, please review if you can :)
Thanks @ccoVeille for helping out with the review and suggested changes @marckhouzam would love to get this in, please let me know if any issues
Hi @marckhouzam , @ccoVeille , is there anything else you may need to have this merged in? Let me know if there are any questions.