Skip to content

Fix index out of range panic when Run is given no arguments - #2401

Open
mrueg wants to merge 1 commit into
urfave:mainfrom
mrueg:fix/panic-on-empty-osargs
Open

Fix index out of range panic when Run is given no arguments#2401
mrueg wants to merge 1 commit into
urfave:mainfrom
mrueg:fix/panic-on-empty-osargs

Conversation

@mrueg

@mrueg mrueg commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Command.Run indexes into the argument slice in two places without first checking that it is non-empty, so passing an empty slice panics instead of returning.

setupDefaults

Reads osArgs[0] to derive a default command name:

cmd := &cli.Command{Action: func(context.Context, *cli.Command) error { return nil }}
cmd.Run(context.Background(), []string{})
// panic: runtime error: index out of range [0] with length 0

Affects any root command that does not set Name explicitly.

checkShellCompleteFlag

Reads arguments[len(arguments)-1]:

cmd := &cli.Command{Name: "x", EnableShellCompletion: true}
cmd.Run(context.Background(), nil)
// panic: runtime error: index out of range [-1]

Affects any command with EnableShellCompletion set, named or not.

Fix

Guard both index accesses. A command invoked with no arguments now runs its Action as it would with any other argument list, and simply keeps an empty Name when there is no argv[0] to derive one from.

This is a pure robustness fix: in practice callers pass os.Args, which is never empty, so no working behaviour changes — the only reachable states previously were the two panics. It matters mostly for tests and for library consumers that build an argument slice programmatically.

Testing

Adds TestRunWithNoOsArgs (named / shell-completion-enabled / unnamed) and a no arguments at all case to the existing Test_checkShellCompleteFlag table. Both fail on main without the change.

🤖 Generated with Claude Code

Command.Run indexes into the argument slice in two places without first
checking that it is non-empty, so passing an empty slice panics rather
than returning:

  * setupDefaults reads osArgs[0] to derive a default command name,
    panicking with "index out of range [0] with length 0" for any root
    command that does not set Name explicitly.

  * checkShellCompleteFlag reads arguments[len(arguments)-1], panicking
    with "index out of range [-1]" whenever EnableShellCompletion is set.

Guard both. A command with no arguments now runs its Action, and simply
keeps an empty Name when there is no argv[0] to derive one from.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@mrueg
mrueg requested a review from a team as a code owner August 10, 2026 15:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant