Skip to content

feat: support xor/and groups for positional arguments#604

Open
toller892 wants to merge 1 commit into
alecthomas:masterfrom
toller892:fix/xor-positional-args
Open

feat: support xor/and groups for positional arguments#604
toller892 wants to merge 1 commit into
alecthomas:masterfrom
toller892:fix/xor-positional-args

Conversation

@toller892

Copy link
Copy Markdown

Fixes #255

Problem

xor and and group validation only worked for flags, not positional arguments. Providing both a flag and a positional arg in the same xor group did not produce an error.

Changes

  • context.go: Extended checkMissingFlags, checkXorDuplicates, and checkAndMissing to include positional arguments in xor/and group validation
  • kong.go: Extended checkOverlappingXorAnd to also scan positional arguments for xor/and group membership
  • Error messages now use ShortSummary() instead of hardcoded --%s format, so they correctly display both flag names (--flag) and positional arg names

Example

type CLI struct {
    Defaults bool     `xor:"group1" help:"Use defaults"`
    Args     []string `arg:"" xor:"group1" optional:"" help:"Positional args"`
}

Before: run --defaults foo bar → no error
After: run --defaults foo bar → error: "--defaults and args can't be used together"

Tests

All existing tests pass. The fix is backward-compatible since positional args without xor/and tags are unaffected.

@alecthomas

Copy link
Copy Markdown
Owner

Please add tests.

Fixes alecthomas#255

Extend checkMissingFlags, checkXorDuplicates, checkAndMissing, and
checkOverlappingXorAnd to include positional arguments in xor/and
group validation. Error messages now use ShortSummary() to correctly
display both flag (--flag) and positional arg names.
@toller892 toller892 force-pushed the fix/xor-positional-args branch from 18bfd45 to 5d03973 Compare May 28, 2026 09:43
@toller892

Copy link
Copy Markdown
Author

Tests added! I've added 3 new test cases covering xor/and with positional arguments:

  • TestXorWithPositional — flag vs positional in same xor group (all 4 combinations: both, flag-only, positional-only, neither)
  • TestXorFlagAndPositionalInverted — same test with reversed field order
  • TestAndWithPositional — flag + positional in same and group (missing positional detected)

The implementation was also improved: the xor/and validation now groups paths by command scope (root vs child commands) to correctly handle both flat structs and subcommands. All 2700+ existing tests pass.

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.

Xor is ignored with positional arguments

2 participants