Skip to content

No simple way to block repeated flags #2355

@SecretGibbon

Description

@SecretGibbon

Hello, team Cobra,
I got a request to make a CLI reject repeated flags (eg. ./cli --name test --name test2 or ./cli -f -f).
I found two ways of doing this.

  1. PersistentPreRunE with raw arguments validation
  2. Defining custom flag types that will error out on multiple Set calls.

I went with #2:

func (sb *singleBool) Set(value string) error {
	err := sb.occurrenceCounter.Check()
	if err != nil {
		return err
	}
	sb.value, err = strconv.ParseBool(value)
	return err
}

but it requires me to define full type for every type of flag used (6 files each ~60 lines). It's not terrible but it could be simple setting for the cobra itself instead of 360 lines of code.
Would it be possible to add feature flag allowing flags to be set only once? Or is there any simpler way I have misseed?
Thank you.

Metadata

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