Skip to content

Commit

Permalink
Merge pull request #1933 from suzuki-shunsuke/fix-shell-completion-wi…
Browse files Browse the repository at this point in the history
…th-double-dash

fix: disable shell completion if double dash is included in arguments (v3)
  • Loading branch information
dearchap authored Jun 29, 2024
2 parents ab4b592 + d16cc40 commit fd760fc
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
9 changes: 9 additions & 0 deletions help.go
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,15 @@ func checkShellCompleteFlag(c *Command, arguments []string) (bool, []string) {
return false, arguments
}

for _, arg := range arguments {
// If arguments include "--", shell completion is disabled
// because after "--" only positional arguments are accepted.
// https://unix.stackexchange.com/a/11382
if arg == "--" {
return false, arguments
}
}

return true, arguments[:pos]
}

Expand Down
65 changes: 65 additions & 0 deletions help_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1662,3 +1662,68 @@ GLOBAL OPTIONS:
`, output.String())
}

func Test_checkShellCompleteFlag(t *testing.T) {
t.Parallel()
tests := []struct {
name string
cmd *Command
arguments []string
wantShellCompletion bool
wantArgs []string
}{
{
name: "disable-shell-completion",
arguments: []string{"--generate-shell-completion"},
cmd: &Command{},
wantShellCompletion: false,
wantArgs: []string{"--generate-shell-completion"},
},
{
name: "child-disable-shell-completion",
arguments: []string{"--generate-shell-completion"},
cmd: &Command{
parent: &Command{},
},
wantShellCompletion: false,
wantArgs: []string{"--generate-shell-completion"},
},
{
name: "last argument isn't --generate-shell-completion",
arguments: []string{"foo"},
cmd: &Command{
EnableShellCompletion: true,
},
wantShellCompletion: false,
wantArgs: []string{"foo"},
},
{
name: "arguments include double dash",
arguments: []string{"--", "foo", "--generate-shell-completion"},
cmd: &Command{
EnableShellCompletion: true,
},
wantShellCompletion: false,
wantArgs: []string{"--", "foo", "--generate-shell-completion"},
},
{
name: "shell completion",
arguments: []string{"foo", "--generate-shell-completion"},
cmd: &Command{
EnableShellCompletion: true,
},
wantShellCompletion: true,
wantArgs: []string{"foo"},
},
}

for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
shellCompletion, args := checkShellCompleteFlag(tt.cmd, tt.arguments)
assert.Equal(t, tt.wantShellCompletion, shellCompletion)
assert.Equal(t, tt.wantArgs, args)
})
}
}

0 comments on commit fd760fc

Please sign in to comment.