Skip to content
Merged
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
7 changes: 7 additions & 0 deletions command_run.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"unicode"
)

type helpShownKey struct{}

func (cmd *Command) parseArgsFromStdin() ([]string, error) {
type state int
const (
Expand Down Expand Up @@ -176,6 +178,7 @@ func (cmd *Command) run(ctx context.Context, osArgs []string) (_ context.Context

cmd.isInError = true
if cmd.checkHelp() {
ctx = context.WithValue(ctx, helpShownKey{}, true)
if cmd.parent == nil {
_ = ShowRootCommandHelp(cmd)
} else {
Expand Down Expand Up @@ -210,6 +213,7 @@ func (cmd *Command) run(ctx context.Context, osArgs []string) (_ context.Context
}

if cmd.checkHelp() {
ctx = context.WithValue(ctx, helpShownKey{}, true)
return ctx, helpCommandAction(ctx, cmd)
} else {
tracef("no help is wanted (cmd=%[1]q)", cmd.Name)
Expand All @@ -234,6 +238,9 @@ func (cmd *Command) run(ctx context.Context, osArgs []string) (_ context.Context

if cmd.After != nil && !cmd.Root().shellCompletion {
defer func() {
if ctx.Value(helpShownKey{}) != nil {
return
}
if err := cmd.After(ctx, cmd); err != nil {
err = cmd.handleExitCoder(ctx, err)

Expand Down
44 changes: 44 additions & 0 deletions command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1810,6 +1810,50 @@ func TestCommand_AfterFunc(t *testing.T) {
assert.Equal(t, 0, counts.SubCommand, "Subcommand not executed when expected")
}

func TestCommand_AfterNotCalledOnSubcommandHelp(t *testing.T) {
var afterCalled bool
cmd := &Command{
After: func(_ context.Context, _ *Command) error {
afterCalled = true
return nil
},
Commands: []*Command{
{
Name: "sub",
Action: func(context.Context, *Command) error {
return nil
},
},
},
}

err := cmd.Run(buildTestContext(t), []string{"app", "sub", "--help"})
require.NoError(t, err)
assert.False(t, afterCalled, "After should not be called when --help is passed to subcommand")
}

func TestCommand_AfterStillCalledOnNormalSubcommand(t *testing.T) {
var afterCalled bool
cmd := &Command{
After: func(_ context.Context, _ *Command) error {
afterCalled = true
return nil
},
Commands: []*Command{
{
Name: "sub",
Action: func(context.Context, *Command) error {
return nil
},
},
},
}

err := cmd.Run(buildTestContext(t), []string{"app", "sub"})
require.NoError(t, err)
assert.True(t, afterCalled, "After should be called on normal subcommand execution")
}

func TestCommandNoHelpFlag(t *testing.T) {
oldFlag := HelpFlag
defer func() {
Expand Down
Loading