Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

completions: do not detect arguments with dash as 2nd char as flag #1817

Merged
merged 2 commits into from Jan 3, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion command.go
Expand Up @@ -692,7 +692,7 @@ Loop:
}

func isFlagArg(arg string) bool {
return ((len(arg) >= 3 && arg[1] == '-') ||
return ((len(arg) >= 3 && arg[0:2] == "--") ||
(len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))
}

Expand Down
64 changes: 64 additions & 0 deletions completions_test.go
Expand Up @@ -3115,3 +3115,67 @@ func TestCompletionCobraFlags(t *testing.T) {
})
}
}

func TestArgsNotDetectedAsFlagsCompletionInGo(t *testing.T) {
// Regression test that ensures the bug described in
// https://github.com/spf13/cobra/issues/1816 does not occur anymore.

root := Command{
Use: "root",
ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
return []string{"service", "1-123", "11-123"}, ShellCompDirectiveNoFileComp
},
}

completion := `service
1-123
11-123
:4
Completion ended with directive: ShellCompDirectiveNoFileComp
`

testcases := []struct {
desc string
args []string
expectedOutput string
}{
{
desc: "empty",
args: []string{""},
expectedOutput: completion,
},
{
desc: "service only",
args: []string{"service", ""},
expectedOutput: completion,
},
{
desc: "service last",
args: []string{"1-123", "service", ""},
expectedOutput: completion,
},
{
desc: "two digit prefixed dash last",
args: []string{"service", "11-123", ""},
expectedOutput: completion,
},
{
desc: "one digit prefixed dash last",
args: []string{"service", "1-123", ""},
expectedOutput: completion,
},
}
for _, tc := range testcases {
t.Run(tc.desc, func(t *testing.T) {
args := []string{ShellCompNoDescRequestCmd}
args = append(args, tc.args...)
output, err := executeCommand(&root, args...)
switch {
case err == nil && output != tc.expectedOutput:
t.Errorf("expected: %q, got: %q", tc.expectedOutput, output)
case err != nil:
t.Errorf("Unexpected error %q", err)
}
})
}
}