Files
Strata/terminal/strata_cli/completion.py
T
Niko1221 9ff9e5c01b Terminal: strata complete --shell bash|zsh|fish prints a tab-completion script built from the CLI's own parser (#6086)
From PR #6087 (ackalker): the idea and the command name. The script is generated by strata_cli/completion.py from parser(), with no
optional package (the PR needed shtab, which the Terminal bundle does not carry). Completes commands, sub-commands, options and the
choices of options. The test runs the bash script in a real bash; zsh and fish are syntax-checked where those shells exist.
2026-11-19 14:14:07 +01:00

123 lines
5.1 KiB
Python

"""`strata complete`: a tab-completion script for bash, zsh and fish (#6086).
The script is generated from `cli.parser()`, the grammar the installed command really has, so it cannot drift from it and needs no
extra package (PR #6087 used `shtab`, which the hash-locked Terminal bundle does not carry). It completes every command, sub-command
and option, and the values of options that have a fixed list of choices."""
from __future__ import annotations
import argparse
import re
SHELLS = ("bash", "zsh", "fish")
class Node:
"""One level of the grammar: its sub-commands (name -> (help, Node)), its options and the choices of options that have them."""
def __init__(self) -> None:
self.subs: dict[str, tuple[str, "Node"]] = {}
self.options: list[str] = []
self.choices: dict[str, list[str]] = {}
def walk(ap: argparse.ArgumentParser) -> Node:
node = Node()
helps: dict[str, str] = {}
for action in ap._actions:
if isinstance(action, argparse._SubParsersAction):
for choice in action._choices_actions:
helps[choice.dest] = (choice.help or "").strip()
for name, sub in action.choices.items():
node.subs[name] = (helps.get(name, ""), walk(sub))
continue
for opt in action.option_strings:
if opt.startswith("--") or opt in ("-h",):
node.options.append(opt)
if action.choices and not isinstance(action.choices, dict):
node.choices[opt] = [str(c) for c in action.choices]
return node
def _paths(node: Node, prefix: tuple[str, ...] = ()):
yield prefix, node
for name, (_, sub) in node.subs.items():
yield from _paths(sub, prefix + (name,))
def _q(text: str) -> str:
"""One shell-safe word: the grammar only has letters, digits, `-`, `_` and `.`; anything else is dropped."""
return re.sub(r"[^A-Za-z0-9_.=-]", "", text)
def bash_script(ap: argparse.ArgumentParser) -> str:
root = walk(ap)
levels, steps, picks = [], [], []
for path, node in _paths(root):
key = "/" + "/".join(_q(p) for p in path) if path else ""
words = " ".join([_q(n) for n in node.subs] + [_q(o) for o in node.options])
levels.append(f' "{key}") words="{words}" ;;')
for name in node.subs:
steps.append(f'"{key}/{_q(name)}"')
for opt, values in node.choices.items():
picks.append(f' "{key}:{_q(opt)}") words="{" ".join(_q(v) for v in values)}" ;;')
return "\n".join([
"# bash completion for strata (generated by `strata complete --shell bash` from the installed command's own grammar)",
"_strata() {",
' local cur="${COMP_WORDS[COMP_CWORD]}" prev="" path="" i w words=""',
' [ "$COMP_CWORD" -gt 0 ] && prev="${COMP_WORDS[COMP_CWORD-1]}"',
' for ((i = 1; i < COMP_CWORD; i++)); do',
' w="${COMP_WORDS[i]}"',
' case "$path/$w" in',
" " + " | ".join(steps) + ') path="$path/$w" ;;' if steps else " *) ;;",
" esac",
" done",
' case "$path:$prev" in',
*picks,
" *)",
' case "$path" in',
*levels,
" esac ;;",
" esac",
' COMPREPLY=($(compgen -W "$words" -- "$cur"))',
"}",
"complete -F _strata strata",
"",
])
def zsh_script(ap: argparse.ArgumentParser) -> str:
"""zsh runs the bash function through its own bash-completion layer: one grammar, one function."""
return "\n".join([
"# zsh completion for strata (generated by `strata complete --shell zsh`; uses zsh's bash-completion layer)",
"autoload -U +X bashcompinit && bashcompinit",
"autoload -U +X compinit && compinit -u 2>/dev/null",
bash_script(ap).split("\n", 1)[1],
])
def fish_script(ap: argparse.ArgumentParser) -> str:
root = walk(ap)
lines = ["# fish completion for strata (generated by `strata complete --shell fish` from the installed command's own grammar)",
"complete -c strata -f"]
for path, node in _paths(root):
if not path:
cond = "__fish_use_subcommand"
else:
seen = "; and ".join(f"__fish_seen_subcommand_from {_q(p)}" for p in path)
nxt = " ".join(_q(n) for n in node.subs)
cond = seen + (f"; and not __fish_seen_subcommand_from {nxt}" if nxt else "")
for name, (help_text, _) in node.subs.items():
desc = help_text.replace("'", "").replace("\n", " ")[:80]
lines.append(f"complete -c strata -n '{cond}' -a {_q(name)} -d '{desc}'")
for opt in node.options:
if opt.startswith("--"):
values = node.choices.get(opt)
extra = f" -x -a '{' '.join(_q(v) for v in values)}'" if values else ""
lines.append(f"complete -c strata -n '{'__fish_seen_subcommand_from ' + _q(path[-1]) if path else 'true'}' -l {_q(opt[2:])}{extra}")
lines.append("")
return "\n".join(lines)
def script(ap: argparse.ArgumentParser, shell: str) -> str:
return {"bash": bash_script, "zsh": zsh_script, "fish": fish_script}[shell](ap)