spf13 / cobra

A Commander for modern Go CLI interactions
https://cobra.dev
Apache License 2.0
38.41k stars 2.86k forks source link

add MarkIfFlagPresentThenOthersRequired #2200

Open faizan-siddiqui opened 1 month ago

faizan-siddiqui commented 1 month ago

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")

This change makes it easier to enforce dependencies between flags while allowing flexible defaults when the primary flag is not specified.

CLAassistant commented 1 month ago

CLA assistant check
All committers have signed the CLA.

faizan-siddiqui commented 1 month ago

@marckhouzam Would love to get this in thanks! Let me know if you have any questions :)

faizan-siddiqui commented 2 weeks ago

@dpetersen @markbates @EdwardBetts Would love to get this in thanks! Let me know if you have any questions :)