Skip to content

Completion

duho.completion

Shell completion script generation (bash/zsh/fish/powershell).

Decision (do not revisit): STATIC script generation -- these functions emit a self-contained completion script the user installs once, NOT a dynamic argcomplete-style hook that re-invokes the program on every Tab. Zero runtime dependency, zero per-invocation cost: a core differentiator vs. argcomplete.

All four emitters (bash, zsh, fish, powershell) share one parser-tree walk (_walk) that turns a built argparse.ArgumentParser into a plain, shell-agnostic CompletionSpec. Only the emitters know shell syntax.

Completion data is read off the built parser's private attrs (parser._actions, parser._subparsers) -- the same internal contract parsers.py already relies on elsewhere in this codebase.

__all__ = ['CompletionOption', 'CompletionPositional', 'CompletionSpec', 'bash', 'zsh', 'fish', 'powershell'] module-attribute

CompletionOption(flags, takes_value, choices=None, is_path=False) dataclass

One optional argument (e.g. --name/-n).

choices = None class-attribute instance-attribute

flags instance-attribute

is_path = False class-attribute instance-attribute

takes_value instance-attribute

CompletionPositional(name, choices=None, is_path=False) dataclass

One positional argument.

choices = None class-attribute instance-attribute

is_path = False class-attribute instance-attribute

name instance-attribute

CompletionSpec(prog, options=list(), positionals=list(), subcommands=dict(), help='') dataclass

Shell-agnostic view of a single (sub)parser and its subcommand tree.

help = '' class-attribute instance-attribute

options = _dc.field(default_factory=list) class-attribute instance-attribute

positionals = _dc.field(default_factory=list) class-attribute instance-attribute

prog instance-attribute

subcommands = _dc.field(default_factory=dict) class-attribute instance-attribute

bash(parser, prog=None)

Emit a self-contained bash completion script for parser.

Registers complete -F _<prog> <prog>. Choices use compgen -W, Path-typed args fall back to compgen -f/-d (native file/dir completion), non-Path/non-choice args get no candidates (bash's default filename completion still applies).

Source code in src/duho/completion.py
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
def bash(parser: _argparse.ArgumentParser, prog: "str | None" = None) -> str:
    """Emit a self-contained bash completion script for `parser`.

    Registers ``complete -F _<prog> <prog>``. Choices use `compgen -W`,
    Path-typed args fall back to `compgen -f`/`-d` (native file/dir
    completion), non-Path/non-choice args get no candidates (bash's default
    filename completion still applies).
    """
    root = _walk(parser, prog=prog)
    root_prog = _validate_prog(root.prog)
    func = _func_name(root_prog)

    # Flags that CONSUME a value: when one appears in COMP_WORDS its following
    # word is that value, not a subcommand -- skip it when reconstructing the
    # command path, or `myapp --env prod deploy` builds cmd_path "prod deploy"
    # and no completion matches (M8).
    value_flags = sorted(
        {f for spec in _all_specs(root) for opt in spec.options if opt.takes_value for f in opt.flags}
    )
    value_flags_pat = " ".join(value_flags)

    lines: "list[str]" = []
    lines.append(f"# bash completion for {root_prog}")
    lines.append(f"_{func}() {{")
    lines.append('    local cur prev words cword')
    lines.append('    COMPREPLY=()')
    lines.append('    cur="${COMP_WORDS[COMP_CWORD]}"')
    lines.append('    prev="${COMP_WORDS[COMP_CWORD-1]}"')
    lines.append('')
    lines.append('    # Walk COMP_WORDS to find which (sub)command we are in,')
    lines.append('    # skipping option flags AND the value that follows a')
    lines.append('    # value-taking flag.')
    lines.append(f'    local value_flags=" {value_flags_pat} "')
    lines.append('    local cmd_path=""')
    lines.append('    local i=1')
    lines.append('    local skip_next=0')
    lines.append('    while [ $i -lt $COMP_CWORD ]; do')
    lines.append('        local w="${COMP_WORDS[i]}"')
    lines.append('        if [ $skip_next -eq 1 ]; then')
    lines.append('            skip_next=0')
    lines.append('        else')
    lines.append('            case "$w" in')
    lines.append('                -*)')
    lines.append('                    case "$value_flags" in')
    lines.append('                        *" $w "*) skip_next=1 ;;')
    lines.append('                    esac')
    lines.append('                    ;;')
    lines.append('                *) cmd_path="${cmd_path} $w" ;;')
    lines.append('            esac')
    lines.append('        fi')
    lines.append('        i=$((i + 1))')
    lines.append('    done')
    lines.append('    cmd_path="$(echo "$cmd_path" | xargs)"')
    lines.append('')

    for spec in _all_specs(root):
        opts = sorted({f for opt in spec.options for f in opt.flags})
        key = spec.prog[len(root_prog):].strip()
        lines.append(f'    if [ "$cmd_path" = {_bashq(key)} ]; then')

        # prev-based value completion (choices/paths) for this command.
        value_opts = [o for o in spec.options if o.takes_value]
        if value_opts:
            lines.append('        case "$prev" in')
            for opt in value_opts:
                flag_pattern = "|".join(opt.flags)
                if opt.choices:
                    words = _bash_wordlist(list(opt.choices))
                    lines.append(f'            {flag_pattern})')
                    lines.append(f'                COMPREPLY=( $(compgen -W {words} -- "$cur") )')
                    lines.append('                return 0 ;;')
                elif opt.is_path:
                    lines.append(f'            {flag_pattern})')
                    lines.append('                COMPREPLY=( $(compgen -f -- "$cur") )')
                    lines.append('                return 0 ;;')
            lines.append('        esac')

        candidates = list(opts)
        candidates.extend(sorted(spec.subcommands))
        for pos in spec.positionals:
            if pos.choices:
                candidates.extend(pos.choices)

        if candidates:
            words = _bash_wordlist(candidates)
            lines.append(f'        COMPREPLY=( $(compgen -W {words} -- "$cur") )')
        else:
            lines.append('        COMPREPLY=( $(compgen -f -- "$cur") )')
        lines.append('        return 0')
        lines.append('    fi')

    lines.append('}')
    lines.append(f'complete -F _{func} {_bashq(root_prog)}')
    lines.append('')
    return "\n".join(lines)

fish(parser, prog=None)

Emit a fish completion script (complete -c <prog> ... lines) for parser.

Choices become -a, value-taking options get -r (require an argument), Path-typed options additionally get -F to enable fish's native file completion; subcommand-scoped rules are gated on __fish_seen_subcommand_from.

Source code in src/duho/completion.py
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
def fish(parser: _argparse.ArgumentParser, prog: "str | None" = None) -> str:
    """Emit a fish completion script (`complete -c <prog> ...` lines) for `parser`.

    Choices become `-a`, value-taking options get `-r` (require an
    argument), Path-typed options additionally get `-F` to enable fish's
    native file completion; subcommand-scoped rules are gated on
    `__fish_seen_subcommand_from`.
    """
    root = _walk(parser, prog=prog)
    root_prog = _validate_prog(root.prog)
    prog_q = _sq(root_prog)

    lines: "list[str]" = []
    lines.append(f"# fish completion for {root_prog}")
    lines.append(f"complete -c {prog_q} -f")
    lines.append("")

    for spec in _all_specs(root):
        cond = _fish_condition(spec, root)
        cond_args = ["-n", _sq(cond)] if cond else []

        for name, sub in spec.subcommands.items():
            parts = [f"complete -c {prog_q}"] + cond_args + ["-a", _sq(name)]
            # The one-line help, NOT the fully-qualified prog, as the description.
            description = sub.help or ""
            if description:
                parts.extend(["-d", _sq(description)])
            lines.append(" ".join(parts))

        for opt in spec.options:
            long_flags = [f for f in opt.flags if f.startswith("--")]
            # A single-dash MULTI-char flag (e.g. ``-rc``) is an old-style flag:
            # fish's ``-s`` is for a single character only, so use ``-o`` (M2/fish).
            short_flags = [
                f for f in opt.flags
                if not f.startswith("--") and f.startswith("-") and len(f.lstrip("-")) == 1
            ]
            old_flags = [
                f for f in opt.flags
                if not f.startswith("--") and f.startswith("-") and len(f.lstrip("-")) > 1
            ]
            parts = [f"complete -c {prog_q}"] + cond_args
            for lf in long_flags:
                parts.extend(["-l", _sq(lf.lstrip("-"))])
            for sf in short_flags:
                parts.extend(["-s", _sq(sf.lstrip("-"))])
            for of in old_flags:
                parts.extend(["-o", _sq(of.lstrip("-"))])
            if opt.takes_value:
                parts.append("-r")
                if opt.choices:
                    values = " ".join(str(c) for c in opt.choices)
                    parts.extend(["-a", _sq(values)])
                elif opt.is_path:
                    parts.append("-F")
            lines.append(" ".join(parts))

        for pos in spec.positionals:
            if pos.choices:
                values = " ".join(str(c) for c in pos.choices)
                parts = [f"complete -c {prog_q}"] + cond_args + ["-a", _sq(values)]
                lines.append(" ".join(parts))
            elif pos.is_path:
                parts = [f"complete -c {prog_q}"] + cond_args + ["-F"]
                lines.append(" ".join(parts))

    lines.append("")
    return "\n".join(lines)

powershell(parser, prog=None)

Emit a PowerShell completion script for parser.

Registers a Register-ArgumentCompleter -Native script block that walks the same CompletionSpec tree the other emitters use: it reconstructs the (sub)command path from the non-flag words on the line (skipping the value that follows a value-taking flag, mirroring the bash walker), then offers that command's flags, subcommand names, and choice values. When the previous token is a choice-bearing value flag, its choices are offered instead. A command that only takes a free/path value offers nothing, so PowerShell's own file completion takes over.

Every interpolated value (prog, flags, choices, command-path keys) is single-quoted with PS quote-doubling via :func:_psq (01-D3), so a hostile choice cannot break out of the generated script or be expanded.

Source code in src/duho/completion.py
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
def powershell(parser: _argparse.ArgumentParser, prog: "str | None" = None) -> str:
    """Emit a PowerShell completion script for `parser`.

    Registers a ``Register-ArgumentCompleter -Native`` script block that walks the
    same `CompletionSpec` tree the other emitters use: it reconstructs the
    (sub)command path from the non-flag words on the line (skipping the value that
    follows a value-taking flag, mirroring the bash walker), then offers that
    command's flags, subcommand names, and choice values. When the previous token
    is a choice-bearing value flag, its choices are offered instead. A command
    that only takes a free/path value offers nothing, so PowerShell's own file
    completion takes over.

    Every interpolated value (prog, flags, choices, command-path keys) is
    single-quoted with PS quote-doubling via :func:`_psq` (01-D3), so a hostile
    choice cannot break out of the generated script or be expanded.
    """
    root = _walk(parser, prog=prog)
    root_prog = _validate_prog(root.prog)

    # Flags that CONSUME a value: their following word is that value, not a
    # subcommand -- skip it when reconstructing the command path (mirrors bash M8).
    value_flags = sorted(
        {
            f
            for spec in _all_specs(root)
            for opt in spec.options
            if opt.takes_value
            for f in opt.flags
        }
    )

    lines: "list[str]" = []
    lines.append(f"# PowerShell completion for {root_prog}")
    lines.append(
        f"Register-ArgumentCompleter -Native -CommandName {_psq(root_prog)} "
        f"-ScriptBlock {{"
    )
    lines.append("    param($wordToComplete, $commandAst, $cursorPosition)")
    lines.append("")
    lines.append("    $elements = @($commandAst.CommandElements)")
    lines.append(
        "    $valueFlags = @(" + ", ".join(_psq(f) for f in value_flags) + ")"
    )
    lines.append("")
    lines.append("    # Reconstruct the (sub)command path from the non-flag words,")
    lines.append("    # skipping the value that follows a value-taking flag.")
    lines.append("    $cmdWords = @()")
    lines.append("    $skipNext = $false")
    lines.append("    for ($i = 1; $i -lt $elements.Count; $i++) {")
    lines.append("        $el = $elements[$i].Extent.Text")
    lines.append("        if ($el -eq $wordToComplete) { continue }")
    lines.append("        if ($skipNext) { $skipNext = $false; continue }")
    lines.append("        if ($el -like '-*') {")
    lines.append("            if ($valueFlags -contains $el) { $skipNext = $true }")
    lines.append("            continue")
    lines.append("        }")
    lines.append("        $cmdWords += $el")
    lines.append("    }")
    lines.append("    $cmdPath = ($cmdWords -join ' ')")
    lines.append("")
    lines.append("    # The token immediately before the word under the cursor.")
    lines.append("    $prev = ''")
    lines.append("    if ($elements.Count -ge 2) {")
    lines.append("        $lastText = $elements[$elements.Count - 1].Extent.Text")
    lines.append("        if ($lastText -eq $wordToComplete) {")
    lines.append(
        "            if ($elements.Count -ge 3) "
        "{ $prev = $elements[$elements.Count - 2].Extent.Text }"
    )
    lines.append("        } else {")
    lines.append("            $prev = $lastText")
    lines.append("        }")
    lines.append("    }")
    lines.append("")
    lines.append("    $candidates = @()")

    first = True
    for spec in _all_specs(root):
        key = spec.prog[len(root_prog):].strip()
        cond = "if" if first else "elseif"
        first = False
        lines.append(f"    {cond} ($cmdPath -eq {_psq(key)}) {{")
        general = _powershell_candidates(spec)
        choice_opts = [o for o in spec.options if o.takes_value and o.choices]
        if choice_opts:
            lines.append("        switch -Exact ($prev) {")
            for opt in choice_opts:
                values = ", ".join(_psq(c) for c in opt.choices)
                for flag in opt.flags:
                    lines.append(
                        f"            {_psq(flag)} {{ $candidates = @({values}); break }}"
                    )
            lines.append(f"            default {{ $candidates = @({general}) }}")
            lines.append("        }")
        else:
            lines.append(f"        $candidates = @({general})")
        lines.append("    }")

    lines.append("")
    lines.append(
        '    $candidates | Where-Object { $_ -like "$wordToComplete*" } '
        "| Sort-Object -Unique | ForEach-Object {"
    )
    lines.append(
        "        [System.Management.Automation.CompletionResult]::new("
        "$_, $_, 'ParameterValue', $_)"
    )
    lines.append("    }")
    lines.append("}")
    lines.append("")
    return "\n".join(lines)

zsh(parser, prog=None)

Emit a #compdef-style zsh completion script for parser.

Uses _arguments: subcommand names and option choices are rendered as (a b c) value lists; Path-typed args delegate to _files. The command path is rebuilt from the non-option words only, so a flag before the cursor no longer breaks completion (C12).

Source code in src/duho/completion.py
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
def zsh(parser: _argparse.ArgumentParser, prog: "str | None" = None) -> str:
    """Emit a `#compdef`-style zsh completion script for `parser`.

    Uses `_arguments`: subcommand names and option choices are rendered as
    `(a b c)` value lists; Path-typed args delegate to `_files`. The command path
    is rebuilt from the non-option words only, so a flag before the cursor no
    longer breaks completion (C12).
    """
    root = _walk(parser, prog=prog)
    root_prog = _validate_prog(root.prog)
    func = _func_name(root_prog)

    lines: "list[str]" = []
    lines.append(f"#compdef {root_prog}")
    lines.append("")
    lines.append(f"_{func}() {{")
    lines.append("    local context state state_descr line")
    lines.append("    typeset -A opt_args")
    lines.append("")
    lines.append("    # Reconstruct the (sub)command path from non-option words.")
    lines.append("    local -a path_words")
    lines.append("    integer idx=2")
    lines.append("    while (( idx < CURRENT )); do")
    lines.append('        if [[ "${words[idx]}" != -* ]]; then')
    lines.append('            path_words+=("${words[idx]}")')
    lines.append("        fi")
    lines.append("        (( idx++ ))")
    lines.append("    done")
    lines.append('    local cmd_path="${(j: :)path_words}"')
    lines.append("")

    for spec in _all_specs(root):
        key = spec.prog[len(root_prog):].strip()
        lines.append(f'    if [[ "$cmd_path" == {_sq(key)} ]]; then')
        lines.extend(_zsh_arguments_block(spec, indent="        "))
        lines.append("        return")
        lines.append("    fi")

    lines.append("}")
    lines.append("")
    lines.append(f"_{func} \"$@\"")
    lines.append("")
    return "\n".join(lines)