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

Have optional subcommands take priority over positional arguments #299

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions arg_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,27 @@ func TestPositionalRequiredRestRangeEmptyFail(t *testing.T) {

assertError(t, err, ErrRequired, "the required argument `Rest (zero arguments)` was not provided")
}

func TestPositionalWithSubcommand(t *testing.T) {
var opts = struct {
Command struct {
Positional struct {
Rest []string
} `positional-args:"yes"`
Subcommand struct {
Positional struct {
Rest []string
} `positional-args:"yes"`
} `command:"subcmd"`
} `command:"cmd" subcommands-optional:"true"`
}{}

p := NewParser(&opts, None)
_, err := p.ParseArgs([]string{"cmd", "subcmd", "thing"})

if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
assertStringArray(t, opts.Command.Subcommand.Positional.Rest, []string{"thing"})
assertStringArray(t, opts.Command.Positional.Rest, []string{})
}
7 changes: 2 additions & 5 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -650,22 +650,19 @@ func (p *parseState) addArgs(args ...string) error {
}

func (p *Parser) parseNonOption(s *parseState) error {
if len(s.positional) > 0 {
return s.addArgs(s.arg)
}

if len(s.command.commands) > 0 && len(s.retargs) == 0 {
if cmd := s.lookup.commands[s.arg]; cmd != nil {
s.command.Active = cmd
cmd.fillParseState(s)

return nil
} else if len(s.positional) > 0 {
return s.addArgs(s.arg)
} else if !s.command.SubcommandsOptional {
s.addArgs(s.arg)
return newErrorf(ErrUnknownCommand, "Unknown command `%s'", s.arg)
}
}

return s.addArgs(s.arg)
}

Expand Down