Skip to content

Consider add mutually exlusive flag marker #1385

Closed
@Dentrax

Description

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
	},

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions