Skip to content

feat: add MarkFlagNonRepeatable to reject repeated flags#2403

Closed
aspr0d wants to merge 1 commit into
spf13:mainfrom
aspr0d:feat/non-repeatable-flag
Closed

feat: add MarkFlagNonRepeatable to reject repeated flags#2403
aspr0d wants to merge 1 commit into
spf13:mainfrom
aspr0d:feat/non-repeatable-flag

Conversation

@aspr0d

@aspr0d aspr0d commented May 13, 2026

Copy link
Copy Markdown

Summary

Adds MarkFlagNonRepeatable(name string) to Command, which prevents a flag from being specified more than once on the command line.

Currently, developers who need this behavior must define custom pflag.Value types for every flag type they use (~60 lines each), as described in #2355. This PR offers a single-call API that wraps the flag's existing Value to reject a second Set() invocation.

Implementation

  • nonRepeatableValue — a thin wrapper around pflag.Value that counts Set() calls and returns an error on the second one.
  • IsBoolFlag() is forwarded so --verbose (no value) still works for boolean flags.
  • The approach catches the repetition at parse time, giving the user immediate feedback.

Example

cmd.Flags().String("name", "", "user name")
cmd.MarkFlagNonRepeatable("name")
// mycli --name=alice --name=bob → error

Test plan

  • TestNonRepeatableFlag — 5 cases: single string, repeated string, single bool, repeated bool, no flags
  • All existing tests pass (go test ./...)
  • go build ./... and go vet ./... clean

Closes #2355

Wraps the flag's pflag.Value so that a second Set() call returns a
clear error instead of silently overwriting the first value.

Also forwards the BoolFlag interface so --verbose (no value) still
works for boolean flags marked non-repeatable.

Closes spf13#2355

Co-authored-by: Cursor <cursoragent@cursor.com>
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

Successfully merging this pull request may close these issues.

No simple way to block repeated flags

1 participant