Skip to content
Myr

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

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Fixes #1816 Previously, arguments with a dash as the second character (e.g., 1-ff00:0:1) were detected as a flag by mistake. This resulted in auto completion misbehaving if such an argument was last in the argument list during invocation.

authored by Dominik Roos · committed by GitHub · parent bf11ab6 · Browse files · 2 files+65 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+65 added−1 removed

  • other:+65 added−1 removed

2 files+65 added−1 removed

modified:command.go+1 added-1 removed
690 unmodified lines
691 return args692}693694func isFlagArg(arg string) bool {695 return ((len(arg) >= 3 && arg[1] == '-') ||695 return ((len(arg) >= 3 && arg[0:2] == "--") ||696 (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-'))697}698699// Find the target command given the args and command tree
1135 unmodified lines
modified:completions_test.go+64 added
3113 unmodified lines
3114 }3115 })3116 }3117}31183119func TestArgsNotDetectedAsFlagsCompletionInGo(t *testing.T) {3120 // Regression test that ensures the bug described in3121 // https://github.com/spf13/cobra/issues/1816 does not occur anymore.31223123 root := Command{3124 Use: "root",3125 ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {3126 return []string{"service", "1-123", "11-123"}, ShellCompDirectiveNoFileComp3127 },3128 }31293130 completion := `service31311-123313211-1233133:43134Completion ended with directive: ShellCompDirectiveNoFileComp3135`31363137 testcases := []struct {3138 desc string3139 args []string3140 expectedOutput string3141 }{3142 {3143 desc: "empty",3144 args: []string{""},3145 expectedOutput: completion,3146 },3147 {3148 desc: "service only",3149 args: []string{"service", ""},3150 expectedOutput: completion,3151 },3152 {3153 desc: "service last",3154 args: []string{"1-123", "service", ""},3155 expectedOutput: completion,3156 },3157 {3158 desc: "two digit prefixed dash last",3159 args: []string{"service", "11-123", ""},3160 expectedOutput: completion,3161 },3162 {3163 desc: "one digit prefixed dash last",3164 args: []string{"service", "1-123", ""},3165 expectedOutput: completion,3166 },3167 }3168 for _, tc := range testcases {3169 t.Run(tc.desc, func(t *testing.T) {3170 args := []string{ShellCompNoDescRequestCmd}3171 args = append(args, tc.args...)3172 output, err := executeCommand(&root, args...)3173 switch {3174 case err == nil && output != tc.expectedOutput:3175 t.Errorf("expected: %q, got: %q", tc.expectedOutput, output)3176 case err != nil:3177 t.Errorf("Unexpected error %q", err)3178 }3179 })3180 }3181}