Skip to content
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

Consider add mutually exlusive flag marker #1385

Closed
Dentrax opened this issue Apr 28, 2021 · 3 comments
Closed

Consider add mutually exlusive flag marker #1385

Dentrax opened this issue Apr 28, 2021 · 3 comments

Comments

@Dentrax
Copy link

Dentrax commented Apr 28, 2021

Required case:

var cmdFoo = &cobra.Command{
	Use:   "foo {-a A | -b B}",
	...
}
cmdFoo.Flags().StringVarP(&a, "a", "a", "", "a")
cmdFoo.Flags().StringVarP(&b, "b", "a", "", "a")
_ = cmdFoo.MarkFlagRequired("a")
_ = cmdFoo.MarkFlagRequired("b")

We can not set them both at the same time, but one of the -a or -b is required. (See: #1358) We may need something like:

func (c *Command) MarkFlagMutuallyExlusive(flag string, otherFlags ...string) error

Optional case:

var cmdFoo = &cobra.Command{
	Use:   "foo [-a A | -b B]",
	...
}
cmdFoo.Flags().StringVarP(&a, "a", "a", "", "a")
cmdFoo.Flags().StringVarP(&b, "b", "a", "", "a")

i.e.:

_ = cmdFoo.MarkFlagMutuallyExlusive("a", "b")

Should error out, i.e.:

required flag(s) "a" or "b" not set
exit status 1

Current workaround:

	PreRunE: func(cmd *cobra.Command, args []string) error {
		if a != "" && b != "" {
			return fmt.Errorf("--a and --b are mutually exclusive, can not be set at the same time")
		}
		if a == "" || b == "" {
			return fmt.Errorf("one of the --a or --b are required")
		}
		return nil
	},
@jef
Copy link

jef commented May 14, 2021

Duplicate of #1216

@github-actions
Copy link

This issue is being marked as stale due to a long period of inactivity

@johnSchnake
Copy link
Collaborator

Closing as duplicate; thanks for linking the other issue @jef

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants