-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathcompletion_test.go
More file actions
571 lines (487 loc) · 15.5 KB
/
Copy pathcompletion_test.go
File metadata and controls
571 lines (487 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
package cli
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCompletionHelp(t *testing.T) {
tests := []struct {
name string
args []string
}{
{
name: "short help flag",
args: []string{"foo", completionCommandName, "-h"},
},
{
name: "long help flag",
args: []string{"foo", completionCommandName, "--help"},
},
{
name: "completion bash short help flag",
args: []string{"foo", completionCommandName, "bash", "-h"},
},
{
name: "completion bash long help flag",
args: []string{"foo", completionCommandName, "bash", "--help"},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
out := &bytes.Buffer{}
cmd := &Command{
EnableShellCompletion: true,
Writer: out,
Flags: []Flag{
&StringFlag{
Name: "required-flag",
Required: true,
},
},
}
r := require.New(t)
r.NoError(cmd.Run(buildTestContext(t), test.args))
r.Contains(out.String(), "USAGE")
r.NotContains(out.String(), "GLOBAL OPTIONS")
})
}
}
func TestCompletionDisable(t *testing.T) {
cmd := &Command{}
err := cmd.Run(buildTestContext(t), []string{"foo", completionCommandName})
assert.Error(t, err, "Expected error for no help topic for completion")
}
func TestCompletionEnable(t *testing.T) {
out := &bytes.Buffer{}
cmd := &Command{
EnableShellCompletion: true,
Writer: out,
Flags: []Flag{
&StringFlag{
Name: "goo",
Required: true,
},
},
}
r := require.New(t)
r.NoError(cmd.Run(buildTestContext(t), []string{"foo", completionCommandName}))
r.Contains(out.String(), "USAGE")
}
func TestCompletionEnableDiffCommandName(t *testing.T) {
out := &bytes.Buffer{}
cmd := &Command{
EnableShellCompletion: true,
ShellCompletionCommandName: "junky",
Writer: out,
}
r := require.New(t)
r.NoError(cmd.Run(buildTestContext(t), []string{"foo", "junky"}))
r.Contains(out.String(), "USAGE")
}
func TestCompletionShell(t *testing.T) {
for k := range shellCompletions {
out := &bytes.Buffer{}
t.Run(k, func(t *testing.T) {
cmd := &Command{
EnableShellCompletion: true,
Writer: out,
}
r := require.New(t)
r.NoError(cmd.Run(buildTestContext(t), []string{"foo", completionCommandName, k}))
r.NotEmpty(out.String(), "Expected non-empty completion output for shell %q", k)
})
}
}
func TestCompletionSubcommandOrder(t *testing.T) {
// The completion subcommands must appear in a deterministic order so that
// help output (and docs generated from it) does not change between runs.
// Previously they were built by iterating a map, whose order Go randomizes.
want := []string{"bash", "zsh", "fish", "pwsh"}
// Build several times to guard against intra-process variation.
for range 10 {
cmd := buildCompletionCommand("foo")
got := make([]string, 0, len(cmd.Commands))
for _, sub := range cmd.Commands {
got = append(got, sub.Name)
}
assert.Equal(t, want, got)
}
// Every shell in shellCompletions must be represented in the ordered list.
assert.Len(t, completionShells, len(shellCompletions))
for shell := range shellCompletions {
assert.Contains(t, completionShells, shell)
}
}
func TestCompletionBashNoShebang(t *testing.T) {
// Regression test for https://github.com/urfave/cli/issues/2259
// Bash completion scripts are sourced, not executed, so they must not
// start with a `#!` shebang (flagged by Debian lintian as
// `bash-completion-with-hashbang`).
cmd := &Command{
EnableShellCompletion: true,
}
r := require.New(t)
bashRender := shellCompletions["bash"]
r.NotNil(bashRender, "bash completion renderer should exist")
output, err := bashRender(cmd, "myapp")
r.NoError(err)
r.NotEmpty(output, "bash completion output should not be empty")
r.False(strings.HasPrefix(output, "#!"), "bash completion should not start with a shebang")
}
func TestCompletionBashAppendsSpace(t *testing.T) {
// Regression test for https://github.com/urfave/cli/issues/2332
// Do not register bash completions with `-o nospace`: after a command or
// subcommand completion, Bash should append a space so the next word can be
// completed without manually typing one.
cmd := &Command{
EnableShellCompletion: true,
}
r := require.New(t)
bashRender := shellCompletions["bash"]
r.NotNil(bashRender, "bash completion renderer should exist")
output, err := bashRender(cmd, "myapp")
r.NoError(err)
r.NotContains(output, "-o nospace", "bash completion should append spaces after completed words")
r.Contains(output, "complete -o bashdefault -o default -F __myapp_bash_autocomplete myapp")
}
func TestCompletionBashGreedyColonParsing(t *testing.T) {
// Regression test for https://github.com/urfave/cli/issues/2335
// The bash completion template uses fmt.Sprintf, so
// literal "%" in the template must be escaped as "%%". The token
// extraction must use the greedy ${line%%:*} (double %%) to split on
// the *first* colon. A single % would use ${line%:*} which splits on
// the *last* colon, breaking descriptions that contain colons
// (e.g. "export:Export configs such as: compose-config").
cmd := &Command{
EnableShellCompletion: true,
}
r := require.New(t)
bashRender := shellCompletions["bash"]
r.NotNil(bashRender, "bash completion renderer should exist")
output, err := bashRender(cmd, "myapp")
r.NoError(err)
// After fmt.Sprintf, the rendered script must contain ${line%%:*}
// (greedy match) not ${line%:*} (non-greedy match).
r.Contains(output, `${line%%:*}`, "token extraction should use greedy %% to match first colon")
r.NotContains(output, `${line%:*}`, "token extraction must not use non-greedy single % (splits on last colon)")
}
func TestCompletionFishFormat(t *testing.T) {
// Regression test for https://github.com/urfave/cli/issues/2285
// Fish completion was broken due to incorrect format specifiers
cmd := &Command{
Name: "myapp",
EnableShellCompletion: true,
}
r := require.New(t)
// Test the fish shell completion renderer directly
fishRender := shellCompletions["fish"]
r.NotNil(fishRender, "fish completion renderer should exist")
output, err := fishRender(cmd, "myapp")
r.NoError(err)
// Verify the function name is correctly formatted
r.Contains(output, "function __myapp_perform_completion", "function name should contain app name")
// Verify no format errors (like %! or (string=) which indicate broken fmt.Sprintf)
r.NotContains(output, "%!", "output should not contain format errors")
r.NotContains(output, "(string=", "output should not contain invalid fish syntax")
// Verify the complete commands reference the app correctly
r.Contains(output, "complete -c myapp", "complete command should reference app name")
r.Contains(output, "(__myapp_perform_completion)", "completion function should be registered")
}
func TestCompletionFishOmitsPositionalTokenFromDynamicCompletion(t *testing.T) {
cmd := &Command{
Name: "myapp",
EnableShellCompletion: true,
}
r := require.New(t)
fishRender := shellCompletions["fish"]
r.NotNil(fishRender, "fish completion renderer should exist")
output, err := fishRender(cmd, "myapp")
r.NoError(err)
r.Contains(output, `if string match -q -- "-*" $lastArg`)
r.Contains(output, "set results ($args[1] $args[2..-1] $lastArg --generate-shell-completion 2> /dev/null)")
r.Contains(output, "set results ($args[1] $args[2..-1] --generate-shell-completion 2> /dev/null)")
}
func TestCompletionBashOmitsPositionalTokenFromDynamicCompletion(t *testing.T) {
cmd := &Command{
Name: "myapp",
EnableShellCompletion: true,
}
r := require.New(t)
bashRender := shellCompletions["bash"]
r.NotNil(bashRender, "bash completion renderer should exist")
output, err := bashRender(cmd, "myapp")
r.NoError(err)
r.Contains(output, `if [[ "${current_word}" == "-"* ]]; then`)
r.Contains(output, `printf '%s %s --generate-shell-completion' "${words_before_cursor[*]}" "${current_word}"`)
r.Contains(output, `printf '%s --generate-shell-completion' "${words_before_cursor[*]}"`)
}
func TestCompletionSubcommand(t *testing.T) {
tests := []struct {
name string
args []string
contains string
msg string
msgArgs []any
notContains bool
}{
{
name: "subcommand general completion",
args: []string{"foo", "bar", completionFlag},
contains: "xyz",
msg: "Expected output to contain shell name %[1]q",
msgArgs: []any{
"xyz",
},
},
{
name: "subcommand flag completion",
args: []string{"foo", "bar", "-", completionFlag},
contains: "l1",
msg: "Expected output to contain shell name %[1]q",
msgArgs: []any{
"l1",
},
},
{
name: "subcommand double dash shows long flags",
args: []string{"foo", "bar", "--", completionFlag},
contains: "--l1",
msg: "Expected output to contain flag %[1]q",
msgArgs: []any{
"--l1",
},
},
{
name: "sub sub command general completion",
args: []string{"foo", "bar", "xyz", completionFlag},
contains: "-g",
msg: "Expected output to contain flag %[1]q",
msgArgs: []any{
"-g",
},
notContains: true,
},
{
name: "sub sub command flag completion",
args: []string{"foo", "bar", "xyz", "-", completionFlag},
contains: "-g",
msg: "Expected output to contain flag %[1]q",
msgArgs: []any{
"-g",
},
},
{
name: "sub sub command double dash shows flags",
args: []string{"foo", "bar", "xyz", "--", completionFlag},
contains: "--help",
msg: "Expected output to contain flag %[1]q",
msgArgs: []any{
"--help",
},
},
{
name: "sub sub command no completion extra args",
args: []string{"foo", "bar", "xyz", "--", "sargs", completionFlag},
contains: "-g",
msg: "Expected output to contain flag %[1]q",
msgArgs: []any{
"-g",
},
notContains: true,
},
{
name: "subcommand partial double dash flag completion",
args: []string{"foo", "bar", "--l", completionFlag},
contains: "--l1",
msg: "Expected output to contain flag %[1]q",
msgArgs: []any{
"--l1",
},
},
{
name: "sub sub command partial double dash flag completion",
args: []string{"foo", "bar", "xyz", "--he", completionFlag},
contains: "--help",
msg: "Expected output to contain flag %[1]q",
msgArgs: []any{
"--help",
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
out := &bytes.Buffer{}
cmd := &Command{
EnableShellCompletion: true,
Writer: out,
Commands: []*Command{
{
Name: "bar",
Flags: []Flag{
&StringFlag{
Name: "l1",
},
},
Action: func(ctx context.Context, c *Command) error { return nil },
Commands: []*Command{
{
Name: "xyz",
Flags: []Flag{
&StringFlag{
Name: "g",
Aliases: []string{
"t",
},
},
},
Action: func(ctx context.Context, c *Command) error { return nil },
},
},
},
},
}
r := require.New(t)
r.NoError(cmd.Run(buildTestContext(t), test.args))
if test.notContains {
r.NotContainsf(out.String(), test.contains, test.msg, test.msgArgs...)
} else {
r.Containsf(out.String(), test.contains, test.msg, test.msgArgs...)
}
})
}
}
func TestCompletionSubcommandCustomShellComplete(t *testing.T) {
out := &bytes.Buffer{}
cmd := &Command{
EnableShellCompletion: true,
Writer: out,
Commands: []*Command{
{
Name: "index",
Commands: []*Command{
{
Name: "show",
ShellComplete: func(ctx context.Context, cmd *Command) {
fmt.Fprintln(cmd.Root().Writer, "custom-index")
},
Action: func(ctx context.Context, cmd *Command) error { return nil },
},
},
},
},
}
r := require.New(t)
r.NoError(cmd.Run(buildTestContext(t), []string{"foo", "index", "show", completionFlag}))
r.Equal("custom-index\n", out.String())
}
func TestCompletionRunsBeforeChain(t *testing.T) {
type contextKey struct{}
out := &bytes.Buffer{}
cmd := &Command{
EnableShellCompletion: true,
Writer: out,
Before: func(ctx context.Context, cmd *Command) (context.Context, error) {
return context.WithValue(ctx, contextKey{}, "ready"), nil
},
Commands: []*Command{
{
Name: "index",
Commands: []*Command{
{
Name: "show",
ShellComplete: func(ctx context.Context, cmd *Command) {
fmt.Fprintln(cmd.Root().Writer, ctx.Value(contextKey{}))
},
Action: func(ctx context.Context, cmd *Command) error { return nil },
},
},
},
},
}
r := require.New(t)
r.NoError(cmd.Run(buildTestContext(t), []string{"foo", "index", "show", completionFlag}))
r.Equal("ready\n", out.String())
}
func TestCompletionReturnsBeforeError(t *testing.T) {
beforeErr := errors.New("load config")
completed := false
cmd := &Command{
EnableShellCompletion: true,
Writer: io.Discard,
Before: func(ctx context.Context, cmd *Command) (context.Context, error) {
return nil, beforeErr
},
ShellComplete: func(ctx context.Context, cmd *Command) {
completed = true
},
}
err := cmd.Run(buildTestContext(t), []string{"foo", completionFlag})
require.ErrorIs(t, err, beforeErr)
assert.False(t, completed)
}
func TestCompletionInvalidShell(t *testing.T) {
cmd := &Command{
EnableShellCompletion: true,
}
unknownShellName := "junky-sheell"
err := cmd.Run(buildTestContext(t), []string{"foo", completionCommandName, unknownShellName})
assert.ErrorContains(t, err, fmt.Sprintf("No help topic for '%s'", unknownShellName))
}
func TestCompletionShellRenderError(t *testing.T) {
unknownShellName := "junky-sheell"
enableError := true
shellCompletions[unknownShellName] = func(c *Command, appName string) (string, error) {
if enableError {
return "", fmt.Errorf("can't do completion")
}
return "something", nil
}
// buildCompletionCommand only turns shells listed in completionShells into
// subcommands, so register the injected shell there too (restoring the
// original slice afterward) for it to be reachable.
defer func(orig []string) { completionShells = orig }(completionShells)
completionShells = append(completionShells, unknownShellName)
defer func() {
delete(shellCompletions, unknownShellName)
}()
cmd := &Command{
EnableShellCompletion: true,
}
err := cmd.Run(buildTestContext(t), []string{"foo", completionCommandName, unknownShellName})
assert.ErrorContains(t, err, "can't do completion")
}
type mockWriter struct {
err error
}
func (mw *mockWriter) Write(p []byte) (int, error) {
if mw.err != nil {
return 0, mw.err
}
return len(p), nil
}
func TestCompletionShellWriteError(t *testing.T) {
shellName := "mock-shell"
shellCompletions[shellName] = func(c *Command, appName string) (string, error) {
return "something", nil
}
// buildCompletionCommand only turns shells listed in completionShells into
// subcommands, so register the injected shell there too (restoring the
// original slice afterward) for it to be reachable.
defer func(orig []string) { completionShells = orig }(completionShells)
completionShells = append(completionShells, shellName)
defer func() {
delete(shellCompletions, shellName)
}()
cmd := &Command{
EnableShellCompletion: true,
Writer: &mockWriter{err: fmt.Errorf("writer error")},
}
err := cmd.Run(buildTestContext(t), []string{"foo", completionCommandName, shellName})
assert.ErrorContains(t, err, "writer error")
}