Skip to content

Completion

duho.completion

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

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 three emitters (bash, zsh, fish) 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'] 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()) dataclass

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

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
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
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 = root.prog
    func = _func_name(root_prog)

    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('    local cmd_path=""')
    lines.append('    local i=1')
    lines.append('    while [ $i -lt $COMP_CWORD ]; do')
    lines.append('        case "${COMP_WORDS[i]}" in')
    lines.append('            -*) ;;')
    lines.append('            *) cmd_path="${cmd_path} ${COMP_WORDS[i]}" ;;')
    lines.append('        esac')
    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 = " ".join(sorted({f for opt in spec.options for f in opt.flags}))
        subcmds = " ".join(sorted(spec.subcommands))
        key = spec.prog[len(root_prog):].strip()
        lines.append(f'    if [ "$cmd_path" = "{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 = " ".join(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.split()) if opts else []
        if subcmds:
            candidates.extend(subcmds.split())
        for pos in spec.positionals:
            if pos.choices:
                candidates.extend(pos.choices)

        if candidates:
            words = " ".join(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} {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
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
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 = root.prog

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

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

        for name, sub in spec.subcommands.items():
            parts = [f"complete -c {root_prog}"] + cond_args + ["-a", name]
            docstring = sub.prog
            parts.extend(["-d", f"'{docstring}'"])
            lines.append(" ".join(parts))

        for opt in spec.options:
            long_flags = [f for f in opt.flags if f.startswith("--")]
            short_flags = [f for f in opt.flags if not f.startswith("--") and f.startswith("-")]
            parts = [f"complete -c {root_prog}"] + cond_args
            for lf in long_flags:
                parts.extend(["-l", lf.lstrip("-")])
            for sf in short_flags:
                parts.extend(["-s", sf.lstrip("-")])
            if opt.takes_value:
                parts.append("-r")
                if opt.choices:
                    values = " ".join(opt.choices)
                    parts.extend(["-a", f"'{values}'"])
                elif opt.is_path:
                    parts.append("-F")
            lines.append(" ".join(parts))

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

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

zsh(parser, prog=None)

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

Uses _arguments/_describe: subcommand names and option choices are rendered as (a b c) value lists; Path-typed args delegate to _files.

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

    Uses `_arguments`/`_describe`: subcommand names and option choices are
    rendered as `(a b c)` value lists; Path-typed args delegate to `_files`.
    """
    root = _walk(parser, prog=prog)
    root_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 -a subcmds")
    lines.append("    local context state state_descr line")
    lines.append("    typeset -A opt_args")
    lines.append("")
    lines.append("    local cmd_path=\"${words[2,CURRENT-1]}\"")
    lines.append("")

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

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