Skip to content
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
6 changes: 3 additions & 3 deletions command_parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,9 @@ func (cmd *Command) parseFlags(args Args) (Args, error) {
// positional argument probably
tracef("rearrange-3 (cmd=%[1]q) check %[2]q", cmd.Name, firstArg)

// if there is a command by that name let the command handle the
// rest of the parsing
if cmd.Command(firstArg) != nil {
// Dispatch matches the first positional argument without trimming it.
// Only hand off parsing when that argument selects a child command.
if len(posArgs) == 0 && cmd.Command(rargs[0]) != nil {
posArgs = append(posArgs, rargs...)
return &stringSliceArgs{posArgs}, nil
}
Expand Down
36 changes: 36 additions & 0 deletions command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8333,3 +8333,39 @@ func TestCommand_RunAgainChecksRequiredFlagsAndSources(t *testing.T) {
r.NoError(cmd.Run(buildTestContext(t), []string{"app"}))
r.Equal("from-env", cmd.String("name"))
}

func TestCommand_ChildNameAfterPositionalArgument(t *testing.T) {
for _, test := range []struct {
name string
args []string
wantArgs []string
wantChild bool
}{
{name: "command name", args: []string{"file", "deploy", "--verbose"}, wantArgs: []string{"file", "deploy"}},
{name: "command alias", args: []string{"file", "d", "-v"}, wantArgs: []string{"file", "d"}},
{name: "empty first argument", args: []string{"", "deploy", "--verbose"}, wantArgs: []string{"", "deploy"}},
{name: "ordinary argument", args: []string{"file", "other", "--verbose"}, wantArgs: []string{"file", "other"}},
{name: "padded first argument", args: []string{" deploy ", "--verbose"}, wantArgs: []string{" deploy "}},
{name: "first command name", args: []string{"deploy", "--verbose"}, wantArgs: []string{}, wantChild: true},
{name: "first command alias", args: []string{"d", "--verbose"}, wantArgs: []string{}, wantChild: true},
} {
t.Run(test.name, func(t *testing.T) {
var ran bool
action := func(_ context.Context, cmd *Command) error {
ran = true
require.Equal(t, test.wantChild, cmd.Name == "deploy")
require.True(t, cmd.Bool("verbose"))
require.Equal(t, test.wantArgs, cmd.Args().Slice())
return nil
}
cmd := &Command{
Name: "app",
Flags: []Flag{&BoolFlag{Name: "verbose", Aliases: []string{"v"}}},
Action: action,
Commands: []*Command{{Name: "deploy", Aliases: []string{"d"}, Action: action}},
}
require.NoError(t, cmd.Run(t.Context(), append([]string{"app"}, test.args...)))
require.True(t, ran)
})
}
}
Loading