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
2 changes: 1 addition & 1 deletion command_setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func (cmd *Command) setupDefaults(osArgs []string) {
cmd.ShellComplete = DefaultCompleteWithFlags
}

if cmd.Name == "" && isRoot {
if cmd.Name == "" && isRoot && len(osArgs) > 0 {
name := filepath.Base(osArgs[0])
tracef("setting cmd.Name from first arg basename (cmd=%[1]q)", name)
cmd.Name = name
Expand Down
26 changes: 26 additions & 0 deletions command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6450,3 +6450,29 @@ func TestCommand_Walk_NilFn(t *testing.T) {
cmd := &Command{Name: "foo"}
assert.Nil(t, cmd.Walk(nil))
}

// TestRunWithNoOsArgs checks that Run does not panic when handed an empty
// argument slice.
func TestRunWithNoOsArgs(t *testing.T) {
for _, tst := range []struct {
name string
cmd *Command
}{
{name: "plain", cmd: &Command{Name: "foo"}},
{name: "shell completion enabled", cmd: &Command{Name: "foo", EnableShellCompletion: true}},
{name: "no name", cmd: &Command{}},
} {
t.Run(tst.name, func(t *testing.T) {
called := false
tst.cmd.Action = func(context.Context, *Command) error {
called = true
return nil
}

require.NotPanics(t, func() {
require.NoError(t, tst.cmd.Run(buildTestContext(t), []string{}))
})
assert.True(t, called)
})
}
}
4 changes: 4 additions & 0 deletions help.go
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,10 @@ func checkShellCompleteFlag(c *Command, arguments []string) (bool, []string) {
return false, arguments
}

if len(arguments) == 0 {
return false, arguments
}

pos := len(arguments) - 1
lastArg := arguments[pos]

Expand Down
9 changes: 9 additions & 0 deletions help_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1945,6 +1945,15 @@ func Test_checkShellCompleteFlag(t *testing.T) {
wantShellCompletion: true,
wantArgs: []string{"foo", "--"},
},
{
name: "no arguments at all",
arguments: []string{},
cmd: &Command{
EnableShellCompletion: true,
},
wantShellCompletion: false,
wantArgs: []string{},
},
}

for _, tt := range tests {
Expand Down