diff --git a/command_parse.go b/command_parse.go index d1e09735a8..7de7298dbd 100644 --- a/command_parse.go +++ b/command_parse.go @@ -23,7 +23,7 @@ func flagFromError(err error) (string, error) { return trimmed, nil } -func (cmd *Command) parseFlags(args Args) (Args, error) { +func (cmd *Command) parseFlags(args Args, suggestName func(string) string) (Args, error) { tracef("parsing flags from arguments %[1]q (cmd=%[2]q)", args, cmd.Name) cmd.setFlags = map[Flag]struct{}{} @@ -112,7 +112,13 @@ func (cmd *Command) parseFlags(args Args) (Args, error) { // if there is a command by that name let the command handle the // rest of the parsing - if cmd.Command(firstArg) != nil { + commandName := firstArg + if len(posArgs) == 0 && cmd.SuggestCommandFunc != nil && !cmd.Root().shellCompletion { + // Resolve shorthand before parsing the child's flags. Reuse this + // result at dispatch so custom matchers are only called once. + commandName = suggestName(rargs[0]) + } + if cmd.Command(commandName) != nil { posArgs = append(posArgs, rargs...) return &stringSliceArgs{posArgs}, nil } diff --git a/command_run.go b/command_run.go index 94e7182491..f6ee3e40b2 100644 --- a/command_run.go +++ b/command_run.go @@ -165,12 +165,23 @@ func (cmd *Command) run(ctx context.Context, osArgs []string) (_ context.Context } var err error + // Parsing and dispatch share one match for the first positional argument. + // Keep it local to this run so reused commands resolve each invocation. + var suggestedName string + commandSuggested := false + suggestName := func(name string) string { + if !commandSuggested { + suggestedName = cmd.SuggestCommandFunc(cmd.Commands, name) + commandSuggested = true + } + return suggestedName + } if cmd.SkipFlagParsing { tracef("skipping flag parsing (cmd=%[1]q)", cmd.Name) cmd.parsedArgs = args } else { - cmd.parsedArgs, err = cmd.parseFlags(args) + cmd.parsedArgs, err = cmd.parseFlags(args, suggestName) } tracef("using post-parse arguments %[1]q (cmd=%[2]q)", args, cmd.Name) @@ -275,7 +286,7 @@ func (cmd *Command) run(ctx context.Context, osArgs []string) (_ context.Context tracef("using first positional argument as sub-command name=%[1]q (cmd=%[2]q)", name, cmd.Name) if cmd.SuggestCommandFunc != nil && name != "--" { - name = cmd.SuggestCommandFunc(cmd.Commands, name) + name = suggestName(name) tracef("suggested command name=%1[q] (cmd=%[2]q)", name, cmd.Name) } subCmd = cmd.Command(name) diff --git a/command_test.go b/command_test.go index 263ad82cde..b62460d8a9 100644 --- a/command_test.go +++ b/command_test.go @@ -5041,6 +5041,99 @@ func TestShorthandCommand(t *testing.T) { assert.True(t, cmd1 == 0 && cmd2 == 1, "Expected command1 to be triggered once") } +func TestShorthandCommandWithFlags(t *testing.T) { + for _, name := range []string{"deploy", "ship", "depl"} { + for _, flag := range []string{"--region", "-r"} { + t.Run(name+"/"+flag, func(t *testing.T) { + called := false + cmd := &Command{ + Name: "app", + PrefixMatchCommands: true, + Writer: io.Discard, + ErrWriter: io.Discard, + Commands: []*Command{{ + Name: "deploy", + Aliases: []string{"ship"}, + Flags: []Flag{&StringFlag{Name: "region", Aliases: []string{"r"}}}, + Action: func(_ context.Context, c *Command) error { + called = true + require.Equal(t, "west", c.String("region")) + return nil + }, + }}, + } + require.NoError(t, cmd.Run(t.Context(), []string{"app", name, flag, "west"})) + require.True(t, called) + }) + } + } +} + +func TestShorthandCommandCompletionDoesNotMatch(t *testing.T) { + completed := false + cmd := &Command{ + Name: "app", + EnableShellCompletion: true, + Writer: io.Discard, + ErrWriter: io.Discard, + SuggestCommandFunc: func(_ []*Command, _ string) string { + t.Fatal("completion must not invoke the command matcher") + return "deploy" + }, + Commands: []*Command{{Name: "deploy"}}, + ShellComplete: func(_ context.Context, c *Command) { + completed = true + require.Equal(t, []string{"depl"}, c.Args().Slice()) + }, + } + require.NoError(t, cmd.Run(t.Context(), []string{"app", "depl", completionFlag})) + require.True(t, completed) +} + +func TestCustomCommandMatcherWithFlags(t *testing.T) { + for _, matched := range []bool{false, true} { + t.Run(fmt.Sprint(matched), func(t *testing.T) { + calls := 0 + var seen []string + cmd := &Command{ + Name: "app", + Writer: io.Discard, + ErrWriter: io.Discard, + Flags: []Flag{&StringFlag{Name: "region", Value: "root"}}, + SuggestCommandFunc: func(_ []*Command, name string) string { + calls++ + require.Equal(t, "ship", name) + if matched { + return "deploy" + } + return name + }, + Action: func(_ context.Context, c *Command) error { + require.False(t, matched) + require.Equal(t, []string{"ship", "cargo"}, c.Args().Slice()) + seen = append(seen, c.String("region")) + return nil + }, + Commands: []*Command{{ + Name: "deploy", + Flags: []Flag{&StringFlag{Name: "region", Value: "child"}}, + Action: func(_ context.Context, c *Command) error { + require.True(t, matched) + require.Equal(t, []string{"cargo"}, c.Args().Slice()) + seen = append(seen, c.String("region")) + return nil + }, + }}, + } + for _, region := range []string{"west", "east"} { + require.NoError(t, cmd.Run(t.Context(), []string{"app", "ship", "--region", region, "cargo"})) + } + require.Equal(t, 2, calls) + require.Equal(t, []string{"west", "east"}, seen) + }) + } +} + func TestCommand_Int(t *testing.T) { pCmd := &Command{ Flags: []Flag{