deno_cli_parser 0.10.0

Zero-cost CLI argument parser for the Deno CLI
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
// Copyright 2018-2026 the Deno authors. MIT license.
//! Shell completion script generators.
//!
//! Generate completion scripts from static `CommandDef` definitions
//! for bash, zsh, fish, and powershell.

use crate::types::*;

/// Generate a completion script for the given shell.
pub fn generate(shell: &str, cmd: &CommandDef) -> Vec<u8> {
  match shell {
    "bash" => generate_bash(cmd),
    "zsh" => generate_zsh(cmd),
    "fish" => generate_fish(cmd),
    "powershell" => generate_powershell(cmd),
    _ => Vec::new(),
  }
}

fn generate_bash(cmd: &CommandDef) -> Vec<u8> {
  let name = cmd.name;
  let mut out = String::new();

  // Collect all subcommand names
  let subcmds: Vec<&str> = cmd.subcommands.iter().map(|s| s.name).collect();
  let subcmd_list = subcmds.join(" ");

  out.push_str(&format!(
    r#"_deno() {{
    local i cur prev opts cmds
    COMPREPLY=()
    cur="${{COMP_WORDS[COMP_CWORD]}}"
    prev="${{COMP_WORDS[COMP_CWORD-1]}}"
    cmd=""
    opts=""

    for i in ${{COMP_WORDS[@]}}
    do
        case "${{cmd}},${{i}}" in
            ",${{COMP_WORDS[0]}}")
                cmd="{name}"
                ;;
"#
  ));

  // Add subcommand detection
  for sub in cmd.subcommands {
    out.push_str(&format!(
            "            \"{name},{}\")\n                cmd=\"{name}__{}\"\n                ;;\n",
            sub.name,
            sub.name.replace('-', "__"),
        ));
  }

  out
    .push_str("            *)\n                ;;\n        esac\n    done\n\n");

  // Root command completions
  let root_flags: Vec<String> = cmd
    .all_args()
    .filter(|a| !a.hidden && !a.positional)
    .filter_map(|a| a.long.map(|l| format!("--{l}")))
    .collect();

  out.push_str(&format!(
    "    case \"${{cmd}}\" in\n        {name})\n            opts=\"{} {}\"\n",
    subcmd_list,
    root_flags.join(" ")
  ));
  out.push_str(
    "            if [[ ${cur} == -* || ${COMP_CWORD} -eq 1 ]] ; then\n",
  );
  out.push_str(
    "                COMPREPLY=( $(compgen -W \"${opts}\" -- \"${cur}\") )\n",
  );
  out.push_str("                return 0\n            fi\n");
  out.push_str(
    "            COMPREPLY=( $(compgen -W \"${opts}\" -- \"${cur}\") )\n",
  );
  out.push_str("            return 0\n            ;;\n");

  // Subcommand completions
  for sub in cmd.subcommands {
    let sub_flags: Vec<String> = sub
      .all_args()
      .filter(|a| !a.hidden && !a.positional)
      .filter_map(|a| a.long.map(|l| format!("--{l}")))
      .collect();

    out.push_str(&format!(
      "        {name}__{})\n            opts=\"{}\"\n",
      sub.name.replace('-', "__"),
      sub_flags.join(" "),
    ));
    out.push_str(
      "            COMPREPLY=( $(compgen -W \"${opts}\" -- \"${cur}\") )\n",
    );
    out.push_str("            return 0\n            ;;\n");
  }

  out.push_str("    esac\n}\n\n");
  out.push_str(&format!(
    "complete -F _{name} -o bashdefault -o default {name}\n"
  ));

  out.into_bytes()
}

/// Render an arg's help text as the `[description]` suffix of a zsh
/// `_arguments` spec, ready to be embedded in a single-quoted shell string.
///
/// Returns an empty string when there is no help text: `'-h[]'` is accepted by
/// zsh, but an empty description is noise, and only the full spec matters.
/// Descriptions are truncated to the first line (Deno's help strings are often
/// multi-line, and a raw newline inside `_arguments` breaks the spec) and `[`,
/// `]` and `\` are backslash-escaped so the description can't terminate early.
fn zsh_description(help: &str) -> String {
  let first_line = help.lines().next().unwrap_or_default().trim();
  if first_line.is_empty() {
    return String::new();
  }
  let mut escaped = String::with_capacity(first_line.len() + 2);
  escaped.push('[');
  for c in first_line.chars() {
    match c {
      '\\' | '[' | ']' => {
        escaped.push('\\');
        escaped.push(c);
      }
      // Escape for the surrounding single-quoted shell string.
      '\'' => escaped.push_str("'\\''"),
      _ => escaped.push(c),
    }
  }
  escaped.push(']');
  escaped
}

/// Render a flag as a single-quoted zsh `_arguments` spec, including its short
/// form when it has one.
fn zsh_flag_spec(arg: &ArgDef, long: &str) -> String {
  let desc = zsh_description(arg.help);
  match arg.short {
    Some(short) => {
      format!("'(-{short} --{long})'{{-{short},--{long}}}'{desc}'")
    }
    None => format!("'--{long}{desc}'"),
  }
}

fn generate_zsh(cmd: &CommandDef) -> Vec<u8> {
  let name = cmd.name;
  let mut out = String::new();

  out.push_str(&format!("#compdef {name}\n\n"));

  // Subcommands
  out.push_str("_deno_commands() {\n    local commands; commands=(\n");
  for sub in cmd.subcommands {
    if sub.name == "help" {
      continue;
    }
    // `_describe` entries are `name:description` on a single line, so only the
    // first line of the (often multi-paragraph) about text is usable.
    let about = sub
      .about
      .lines()
      .next()
      .unwrap_or_default()
      .trim()
      .replace('\'', "'\\''");
    out.push_str(&format!("        '{}:{}'\n", sub.name, about));
  }
  out.push_str(
    "    )\n    _describe -t commands 'deno commands' commands\n}\n\n",
  );

  // `deno [flags] <script>` runs the default subcommand, so the first
  // positional can be either a subcommand or a script file.
  let default_sub = cmd
    .default_subcommand
    .and_then(|name| cmd.find_subcommand(name));
  if default_sub.is_some() {
    out.push_str(
      "_deno_commands_or_files() {\n    _alternative \\\n        'commands:command:_deno_commands' \\\n        'files:file:_files'\n}\n\n",
    );
  }

  // Main function
  out.push_str(&format!("_{name}() {{\n"));
  out.push_str("    local line state\n\n");
  out.push_str("    _arguments -C \\\n");

  // Global flags, plus the default subcommand's flags since they are accepted
  // before the script in a bare invocation (e.g. `deno -A main.ts`).
  let mut seen = std::collections::HashSet::new();
  let root_args = cmd
    .all_args()
    .chain(default_sub.into_iter().flat_map(|sub| sub.all_args()));
  for arg in root_args.filter(|a| !a.hidden && !a.positional) {
    if let Some(long) = arg.long
      && seen.insert(long)
    {
      out.push_str(&format!("        {} \\\n", zsh_flag_spec(arg, long)));
    }
  }

  if default_sub.is_some() {
    out.push_str("        \":: :_deno_commands_or_files\" \\\n");
  } else {
    out.push_str("        \":: :_deno_commands\" \\\n");
  }
  out.push_str("        \"*::arg:->args\" \\\n");
  out.push_str("        && ret=0\n\n");

  // Subcommand handling
  out.push_str("    case $state in\n    (args)\n");
  out.push_str("        case $line[1] in\n");

  for sub in cmd.subcommands {
    if sub.name == "help" {
      continue;
    }
    out.push_str(&format!(
      "        {})\n            _arguments \\\n",
      sub.name
    ));
    for arg in sub.all_args().filter(|a| !a.hidden && !a.positional) {
      if let Some(long) = arg.long {
        out.push_str(&format!(
          "                {} \\\n",
          zsh_flag_spec(arg, long)
        ));
      }
    }
    out.push_str("                '*:file:_files'\n            ;;\n");
  }
  if default_sub.is_some() {
    // Anything else in the first position is a script for the default
    // subcommand; complete its arguments as files. The script itself is
    // already handled by `_deno_commands_or_files` above.
    out.push_str(
      "        *)\n            (( CURRENT > 1 )) && _files\n            ;;\n",
    );
  }

  out.push_str("        esac\n    ;;\n    esac\n}\n\n");
  out.push_str(&format!("_{name} \"$@\"\n"));

  out.into_bytes()
}

fn generate_fish(cmd: &CommandDef) -> Vec<u8> {
  let name = cmd.name;
  let mut out = String::new();

  // Disable file completions by default
  out.push_str(&format!("complete -c {name} -e\n\n"));

  // Condition helpers
  out.push_str(&format!(
    "function __fish_{name}_no_subcommand\n    for i in (commandline -opc)\n"
  ));
  for sub in cmd.subcommands {
    out.push_str(&format!(
      "        if test $i = '{}'\n            return 1\n        end\n",
      sub.name
    ));
  }
  out.push_str("    end\n    return 0\nend\n\n");

  // Subcommand completions
  for sub in cmd.subcommands {
    if sub.name == "help" {
      continue;
    }
    out.push_str(&format!(
      "complete -c {name} -n __fish_{name}_no_subcommand -a {} -d '{}'\n",
      sub.name,
      sub.about.replace('\'', "\\'"),
    ));
  }
  out.push('\n');

  // Global flags
  for arg in cmd.all_args().filter(|a| !a.hidden && !a.positional) {
    if let Some(long) = arg.long {
      let desc = arg.help.replace('\'', "\\'");
      if let Some(short) = arg.short {
        out.push_str(&format!(
          "complete -c {name} -s {short} -l {long} -d '{desc}'\n"
        ));
      } else {
        out.push_str(&format!("complete -c {name} -l {long} -d '{desc}'\n"));
      }
    }
  }
  out.push('\n');

  // Per-subcommand flags
  for sub in cmd.subcommands {
    if sub.name == "help" {
      continue;
    }
    for arg in sub.all_args().filter(|a| !a.hidden && !a.positional) {
      if let Some(long) = arg.long {
        let desc = arg.help.replace('\'', "\\'");
        out.push_str(&format!(
                    "complete -c {name} -n '__fish_seen_subcommand_from {}' -l {long} -d '{desc}'\n",
                    sub.name
                ));
      }
    }
  }

  out.into_bytes()
}

fn generate_powershell(cmd: &CommandDef) -> Vec<u8> {
  let name = cmd.name;
  let mut out = String::new();

  out.push_str(&format!(
        r#"Register-ArgumentCompleter -Native -CommandName '{name}' -ScriptBlock {{
    param($wordToComplete, $commandAst, $cursorPosition)
    $commandElements = $commandAst.CommandElements
    $command = @(
        '{name}'
        for ($i = 1; $i -lt $commandElements.Count; $i++) {{
            $element = $commandElements[$i]
            if ($element -isnot [StringConstantExpressionAst] -or
                $element.StringConstantType -ne [StringConstantType]::BareWord -or
                $element.Value.StartsWith('-') -or
                $element.Value -eq $wordToComplete) {{
                break
            }}
            $element.Value
        }}
    ) -join ';'

    $completions = @(switch ($command) {{
"#
    ));

  // Root completions
  out.push_str(&format!("        '{name}' {{\n"));
  for sub in cmd.subcommands {
    if sub.name == "help" {
      continue;
    }
    let about = sub.about.replace('\'', "''");
    out.push_str(&format!(
            "            [CompletionResult]::new('{}', '{}', [CompletionResultType]::ParameterValue, '{}')\n",
            sub.name, sub.name, about
        ));
  }
  out.push_str("        }\n");

  // Subcommand completions
  for sub in cmd.subcommands {
    if sub.name == "help" {
      continue;
    }
    out.push_str(&format!("        '{name};{}' {{\n", sub.name));
    for arg in sub.all_args().filter(|a| !a.hidden && !a.positional) {
      if let Some(long) = arg.long {
        let help = arg.help.replace('\'', "''");
        out.push_str(&format!(
                    "            [CompletionResult]::new('--{long}', '--{long}', [CompletionResultType]::ParameterName, '{help}')\n"
                ));
      }
    }
    out.push_str("        }\n");
  }

  out.push_str("    })\n\n");
  out.push_str(
        "    $completions.Where{ $_.CompletionText -like \"$wordToComplete*\" } |\n",
    );
  out.push_str("        Sort-Object -Property ListItemText\n}\n");

  out.into_bytes()
}

// ============================================================
// Dynamic completions
// ============================================================

/// The env var the registration scripts set (to the shell name) so that a
/// callback invocation of the binary is recognized as a completion request.
/// Mirrors clap_complete's env protocol.
pub const COMPLETE_ENV_VAR: &str = "COMPLETE";

/// Generate the *dynamic* completion registration script for `shell`
/// (bash/fish/zsh). Unlike [`generate`] (which bakes the full command tree into
/// a static script), this emits a small shell function that calls back into the
/// binary with `COMPLETE=<shell>` set, so completions are computed live by
/// [`try_complete`]. `bin` is the command name (e.g. `deno`); `completer` is
/// the shell-quoted path to the executable to invoke. The wire protocol
/// (`_CLAP_COMPLETE_INDEX`, `_CLAP_IFS`, `VAR=COMPLETE`) matches the scripts
/// clap_complete used to emit, so behavior is unchanged.
pub fn generate_dynamic(shell: &str, bin: &str, completer: &str) -> Vec<u8> {
  let escaped_name = bin.replace('-', "_");
  let script = match shell {
    "bash" => BASH_REGISTRATION
      .replace("NAME", &escaped_name)
      .replace("COMPLETER", completer)
      .replace("VAR", COMPLETE_ENV_VAR)
      .replace("BIN", bin),
    "zsh" => ZSH_REGISTRATION
      .replace("NAME", &escaped_name)
      .replace("COMPLETER", completer)
      .replace("VAR", COMPLETE_ENV_VAR)
      .replace("BIN", bin),
    "fish" => format!(
      "complete --keep-order --exclusive --command {bin} --arguments \
       \"({var}=fish {completer} -- (commandline --current-process --tokenize \
       --cut-at-cursor) (commandline --current-token))\"\n",
      var = COMPLETE_ENV_VAR,
    ),
    _ => String::new(),
  };
  script.into_bytes()
}

// Reproduced from clap_complete 4.5's `env::Bash::write_registration` so the
// callback protocol is identical after dropping the clap_complete dependency.
const BASH_REGISTRATION: &str = r#"
_clap_complete_NAME() {
    local IFS=$'\013'
    local _CLAP_COMPLETE_INDEX=${COMP_CWORD}
    local _CLAP_COMPLETE_COMP_TYPE=${COMP_TYPE}
    if compopt +o nospace 2> /dev/null; then
        local _CLAP_COMPLETE_SPACE=false
    else
        local _CLAP_COMPLETE_SPACE=true
    fi
    local words=("${COMP_WORDS[@]}")
    if [[ "${BASH_VERSINFO[0]}" -ge 4 ]]; then
        words[COMP_CWORD]="$2"
    fi
    COMPREPLY=( $( \
        _CLAP_IFS="$IFS" \
        _CLAP_COMPLETE_INDEX="$_CLAP_COMPLETE_INDEX" \
        _CLAP_COMPLETE_COMP_TYPE="$_CLAP_COMPLETE_COMP_TYPE" \
        _CLAP_COMPLETE_SPACE="$_CLAP_COMPLETE_SPACE" \
        VAR="bash" \
        "COMPLETER" -- "${words[@]}" \
    ) )
    if [[ $? != 0 ]]; then
        unset COMPREPLY
    elif [[ $_CLAP_COMPLETE_SPACE == false ]] && [[ "${COMPREPLY-}" =~ [=/:]$ ]]; then
        compopt -o nospace
    fi
}
if [[ "${BASH_VERSINFO[0]}" -eq 4 && "${BASH_VERSINFO[1]}" -ge 4 || "${BASH_VERSINFO[0]}" -gt 4 ]]; then
    complete -o nospace -o bashdefault -o nosort -F _clap_complete_NAME BIN
else
    complete -o nospace -o bashdefault -F _clap_complete_NAME BIN
fi
"#;

// Reproduced from Deno's custom `ZshCompleterUnsorted` (a modified
// clap_complete zsh script that preserves candidate order via `-o nosort`).
const ZSH_REGISTRATION: &str = r#"#compdef BIN
function _clap_dynamic_completer_NAME() {
  local _CLAP_COMPLETE_INDEX=$(expr $CURRENT - 1)
  local _CLAP_IFS=$'\n'

  local completions=("${(@f)$( \
      _CLAP_IFS="$_CLAP_IFS" \
      _CLAP_COMPLETE_INDEX="$_CLAP_COMPLETE_INDEX" \
      VAR="zsh" \
      COMPLETER -- "${words[@]}" 2>/dev/null \
  )}")

  if [[ -n $completions ]]; then
      local -a dirs=()
      local -a other=()
      local completion
      for completion in $completions; do
          local value="${completion%%:*}"
          if [[ "$value" == */ ]]; then
              local dir_no_slash="${value%/}"
              if [[ "$completion" == *:* ]]; then
                  local desc="${completion#*:}"
                  dirs+=("$dir_no_slash:$desc")
              else
                  dirs+=("$dir_no_slash")
              fi
          else
              other+=("$completion")
          fi
      done
      [[ -n $dirs ]] && _describe -V 'values' dirs -o nosort -S '/' -r '/'
      [[ -n $other ]] && _describe -V 'values' other -o nosort
  fi
}

compdef _clap_dynamic_completer_NAME BIN"#;

/// A completion candidate: the value to insert, and optional help text.
pub type Candidate = (String, Option<String>);

/// Produces completion candidates for a positional argument the built-in
/// engine can't resolve on its own (e.g. `deno task <TAB>` -> task names read
/// from `deno.json`). Called with the active (sub)command and the current
/// partial word. Returning an empty vec falls back to the shell's default
/// (file) completion. This lives CLI-side so the parser crate needs no
/// config/workspace dependencies.
pub type PositionalCompleter<'a> =
  dyn Fn(&CommandDef, &str) -> Vec<Candidate> + 'a;

/// Handle dynamic shell completion. Called when `COMPLETE` env var is set.
///
/// Reads the command line from `args`, determines what to complete based on
/// cursor position, and writes completion candidates to stdout using the
/// clap_complete env protocol (`_CLAP_COMPLETE_INDEX` for the cursor position,
/// `_CLAP_IFS` for the bash output separator), so the registration scripts
/// emitted by [`generate_dynamic`] drive it unchanged.
///
/// Returns `true` if completions were handled.
#[allow(clippy::disallowed_methods, reason = "reads completion index from env")]
pub fn try_complete(
  cmd: &CommandDef,
  args: &[String],
  shell: &str,
  positional_completer: &PositionalCompleter,
) -> bool {
  let index = std::env::var("_CLAP_COMPLETE_INDEX")
    .ok()
    .and_then(|s| s.parse::<usize>().ok())
    .unwrap_or(args.len().saturating_sub(1));

  let words: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
  let current = words.get(index).copied().unwrap_or("");

  let (active_cmd, _) = find_active_command(cmd, &words);
  let candidates = get_candidates(
    active_cmd,
    cmd,
    current,
    &words,
    index,
    positional_completer,
  );

  let stdout = std::io::stdout();
  let mut out = std::io::BufWriter::new(stdout.lock());

  use std::io::Write;
  // bash consumes candidates split on `_CLAP_IFS` (the registration script sets
  // it to `\013`); zsh/fish are newline-separated with a per-shell help suffix.
  let bash_ifs = std::env::var("_CLAP_IFS").ok();
  for (i, (value, help)) in candidates.iter().enumerate() {
    match shell {
      "zsh" => {
        if let Some(h) = help {
          let _ = writeln!(out, "{}:{}", value, h);
        } else {
          let _ = writeln!(out, "{}", value);
        }
      }
      "fish" => {
        if let Some(h) = help {
          let _ = writeln!(out, "{}\t{}", value, first_line(h));
        } else {
          let _ = writeln!(out, "{}", value);
        }
      }
      _ => {
        // bash: separate values by _CLAP_IFS, no trailing separator.
        if i > 0 {
          let _ = write!(out, "{}", bash_ifs.as_deref().unwrap_or("\n"));
        }
        let _ = write!(out, "{}", value);
      }
    }
  }

  true
}

fn first_line(s: &str) -> &str {
  s.lines().next().unwrap_or_default()
}

fn find_active_command<'a>(
  root: &'a CommandDef,
  words: &[&str],
) -> (&'a CommandDef, Option<usize>) {
  for (i, word) in words.iter().enumerate().skip(1) {
    if word.starts_with('-') {
      continue;
    }
    if let Some(sub) = root.find_subcommand(word) {
      return (sub, Some(i));
    }
    break;
  }
  (root, None)
}

fn get_candidates(
  active_cmd: &CommandDef,
  root: &CommandDef,
  current: &str,
  words: &[&str],
  index: usize,
  positional_completer: &PositionalCompleter,
) -> Vec<Candidate> {
  let mut candidates = Vec::new();

  // If the previous word is a flag that takes a value, defer entirely to the
  // shell's file completion (mirrors clap emitting no candidates there).
  if index >= 2 {
    let prev = words.get(index - 1).copied().unwrap_or("");
    if prev.starts_with('-') && !prev.contains('=') {
      let flag_name = prev.trim_start_matches('-');
      let takes_value = active_cmd
        .all_args()
        .chain(root.all_args().filter(|a| a.global))
        .any(|a| {
          (a.long == Some(flag_name)
            || a.short.is_some_and(|c| c.to_string() == flag_name))
            && !matches!(a.action, ArgAction::SetTrue | ArgAction::Count)
            && a.num_args != NumArgs::Exact(0)
        });
      if takes_value {
        return candidates; // file completion
      }
    }
  }

  let want_flag = current.starts_with('-');
  let in_subcommand = words
    .iter()
    .skip(1)
    .any(|w| !w.starts_with('-') && root.find_subcommand(w).is_some());

  // Value candidates come first, matching clap's ordering: subcommand names at
  // the root, or positional values inside a subcommand (e.g. `deno task <TAB>`
  // -> task names via the CLI-provided completer). Skipped when the user is
  // clearly typing a flag (`-...`).
  if !want_flag {
    let mut values: Vec<Candidate> = if !in_subcommand {
      root
        .subcommands
        .iter()
        .filter(|s| s.name != "help" && s.name != "json_reference")
        .filter(|s| s.name.starts_with(current))
        .map(|s| {
          let help = (!s.about.is_empty()).then(|| s.about.to_string());
          (s.name.to_string(), help)
        })
        .collect()
    } else {
      positional_completer(active_cmd, current)
        .into_iter()
        .filter(|(value, _)| value.starts_with(current))
        .collect()
    };
    // clap's completion engine sorts candidates; the shells' `--keep-order` /
    // `nosort` then preserve that order, so match it (the spec `.out` files
    // encode this alphabetical ordering).
    values.sort_by(|a, b| a.0.cmp(&b.0));
    candidates.extend(values);
  }

  // Then flags: long flags are always offered (so `deno task <TAB>` also lists
  // `--config` etc.); short flags only when the user has typed a leading `-`.
  let mut flags: Vec<Candidate> = Vec::new();
  for arg in active_cmd
    .all_args()
    .chain(root.all_args().filter(|a| a.global))
  {
    if arg.hidden || arg.positional {
      continue;
    }
    if let Some(long) = arg.long {
      let flag = format!("--{long}");
      if flag.starts_with(current) {
        let help = (!arg.help.is_empty()).then(|| arg.help.to_string());
        flags.push((flag, help));
      }
    }
    if want_flag && let Some(short) = arg.short {
      let flag = format!("-{short}");
      if flag.starts_with(current) && current.len() <= 2 {
        flags.push((flag, None));
      }
    }
  }
  flags.sort_by(|a, b| a.0.cmp(&b.0));
  candidates.extend(flags);

  candidates
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::defs::DENO_ROOT;

  fn no_positional(_: &CommandDef, _: &str) -> Vec<Candidate> {
    Vec::new()
  }

  /// Drive the engine the way `try_complete` does, but return the candidates
  /// instead of writing them to stdout.
  fn complete(
    words: &[&str],
    index: usize,
    pc: &PositionalCompleter,
  ) -> Vec<Candidate> {
    let current = words.get(index).copied().unwrap_or("");
    let (active, _) = find_active_command(&DENO_ROOT, words);
    get_candidates(active, &DENO_ROOT, current, words, index, pc)
  }

  fn values(c: &[Candidate]) -> Vec<&str> {
    c.iter().map(|(v, _)| v.as_str()).collect()
  }

  #[test]
  fn completes_subcommands_at_root() {
    let c = complete(&["deno", ""], 1, &no_positional);
    let v = values(&c);
    assert!(v.contains(&"run"), "{v:?}");
    assert!(v.contains(&"task"), "{v:?}");
    assert!(v.contains(&"test"), "{v:?}");
    // internal-only subcommands are hidden
    assert!(!v.contains(&"json_reference"), "{v:?}");
  }

  #[test]
  fn completes_subcommand_prefix() {
    let c = complete(&["deno", "ru"], 1, &no_positional);
    let v = values(&c);
    assert!(v.contains(&"run"), "{v:?}");
    assert!(!v.contains(&"task"), "{v:?}");
  }

  #[test]
  fn completes_flags_in_subcommand() {
    let c = complete(&["deno", "run", "--no-r"], 2, &no_positional);
    let v = values(&c);
    assert!(v.iter().all(|f| f.starts_with("--no-r")), "{v:?}");
    assert!(v.contains(&"--no-remote"), "{v:?}");
  }

  #[test]
  fn hidden_permission_flags_are_not_offered() {
    // Permission args are `hidden` (they're documented in the after-help
    // "Permission options" section instead), and clap's `.hide(true)` kept
    // them out of clap_complete's candidates too — so stay consistent.
    let c = complete(&["deno", "run", "--allow-r"], 2, &no_positional);
    assert!(c.is_empty(), "{:?}", values(&c));
  }

  #[test]
  fn value_taking_flag_defers_to_file_completion() {
    // `run --config <TAB>`: --config takes a value, so no candidates (the shell
    // does file completion).
    let c = complete(&["deno", "run", "--config", ""], 3, &no_positional);
    assert!(c.is_empty(), "{:?}", values(&c));
  }

  #[test]
  fn positional_completer_supplies_task_names_then_flags() {
    fn tasks(cmd: &CommandDef, _: &str) -> Vec<Candidate> {
      assert_eq!(cmd.name, "task");
      vec![
        ("build".to_string(), Some("Build".to_string())),
        ("test".to_string(), None),
      ]
    }
    let c = complete(&["deno", "task", ""], 2, &tasks);
    let v = values(&c);
    // task names come first...
    assert_eq!(&v[0..2], &["build", "test"], "{v:?}");
    // ...then the subcommand's long flags (e.g. --config) are also offered.
    assert!(v.iter().any(|f| f.starts_with("--")), "{v:?}");
  }

  #[test]
  fn generate_bash_uses_real_newlines() {
    let s = String::from_utf8(generate("bash", &DENO_ROOT)).unwrap();
    assert!(
      s.contains("\"deno,run\")\n                cmd=\"deno__run\""),
      "{s}"
    );
    assert!(s.contains("            *)\n                ;;"), "{s}");
  }

  #[test]
  fn generate_zsh_short_flags_keep_their_dash() {
    // Regression test for #36713: the brace expansion dropped the `-` on the
    // short form, so `deno <TAB>` made zsh bail out with
    // `_arguments:comparguments:327: invalid argument: (-h --help)h[]`.
    let s =
      String::from_utf8(generate("zsh", &crate::defs::DENO_ROOT)).unwrap();
    assert!(s.contains("'(-h --help)'{-h,--help}'"), "{s}");
    assert!(!s.contains("'(-h --help)'{h,--help}'"), "{s}");
    for line in s.lines() {
      let line = line.trim();
      assert!(
        !line.starts_with("'(-") || line.contains("'{-"),
        "short flag lost its dash: {line}"
      );
    }
  }

  #[test]
  fn generate_zsh_completes_files_for_bare_run() {
    // Regression test for #36959: `deno -A ./<TAB>` only offered subcommands
    // for the first positional and nothing after a non-subcommand word, so
    // script paths never completed for a bare `deno [flags] <script>`.
    let s =
      String::from_utf8(generate("zsh", &crate::defs::DENO_ROOT)).unwrap();
    assert!(s.contains("_deno_commands_or_files() {"), "{s}");
    assert!(s.contains("'files:file:_files'"), "{s}");
    assert!(s.contains("\":: :_deno_commands_or_files\""), "{s}");
    assert!(
      s.contains("        *)\n            (( CURRENT > 1 )) && _files\n"),
      "{s}"
    );
    // The default subcommand's flags are accepted at the root.
    let root = &s[s.find("_deno() {").unwrap()..s.find("case $state").unwrap()];
    assert!(root.contains("'--watch["), "{root}");
    assert_eq!(root.matches("'--env-file[").count(), 1, "{root}");
  }

  #[test]
  fn generate_zsh_descriptions_are_single_line_and_escaped() {
    let s =
      String::from_utf8(generate("zsh", &crate::defs::DENO_ROOT)).unwrap();
    // A spec line must be exactly one line, so no description may leak a
    // newline out of its `_arguments` entry.
    for line in s.lines() {
      let line = line.trim();
      if line.starts_with('\'') {
        assert!(line.ends_with("' \\") || line.ends_with('\''), "{line}");
      }
    }
    // `--help` has no help text, so it gets no `[]` description at all.
    assert!(s.contains("'(-h --help)'{-h,--help}'' \\"), "{s}");
  }

  #[test]
  fn zsh_description_escapes_and_truncates() {
    assert_eq!(zsh_description(""), "");
    assert_eq!(zsh_description("Print version"), "[Print version]");
    assert_eq!(zsh_description("first\nsecond"), "[first]");
    assert_eq!(
      zsh_description("[possible values: a, b]"),
      "[\\[possible values: a, b\\]]"
    );
    assert_eq!(zsh_description("don't"), "[don'\\''t]");
  }

  #[test]
  fn generate_dynamic_bash_uses_callback_protocol() {
    let s =
      String::from_utf8(generate_dynamic("bash", "deno", "/bin/deno")).unwrap();
    assert!(s.contains("_clap_complete_deno"), "{s}");
    assert!(s.contains("_CLAP_COMPLETE_INDEX"), "{s}");
    assert!(s.contains("/bin/deno"), "{s}");
    assert!(s.contains("-F _clap_complete_deno deno"), "{s}");
  }

  #[test]
  fn generate_dynamic_fish_is_exclusive_keep_order() {
    let s =
      String::from_utf8(generate_dynamic("fish", "deno", "/bin/deno")).unwrap();
    assert!(s.contains("complete --keep-order --exclusive"), "{s}");
    assert!(s.contains("COMPLETE=fish"), "{s}");
  }

  #[test]
  fn generate_dynamic_zsh_preserves_order() {
    let s =
      String::from_utf8(generate_dynamic("zsh", "deno", "/bin/deno")).unwrap();
    assert!(s.contains("#compdef deno"), "{s}");
    assert!(s.contains("_clap_dynamic_completer_deno"), "{s}");
    assert!(s.contains("-o nosort"), "{s}");
  }
}