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