diff --git a/CHANGELOG.md b/CHANGELOG.md index 7749fcb..01ec5e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,35 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and - Nothing yet. +## [0.3.0] - 2026-11-18 + +### Added in 0.3.0 + +- Shell completion via [argcomplete](https://github.com/kislyuk/argcomplete) + (new dependency): `daedalus hel` completes `hello`, category + labels complete together with the scripts they filter (`daedalus test + h`), options complete after `-`, and `--path ` completes + script names. Activate with + `eval "$(register-python-argcomplete daedalus)"` (INSTALL.md). +- Script arguments complete from the script's own parser (SPEC item + 3.13.5.1): once the script name is typed, daedalus delegates the rest + of the line to the script — `daedalus hello -` offers hello's + `-h` / `--help`, never daedalus's options. A Python script opts in + with `argcomplete.autocomplete(parser)` (SPEC item 6.9). +- `daedalus/completions.py`: the candidate functions argcomplete calls. + +### Changed in 0.3.0 + +- The CLI argument handling now uses `argparse` + (`daedalus.cli.build_parser`): `-h/--help` prints the argparse + rendering, and parser-level errors keep the argparse messages (exit + code 2 stays). Options are parsed anywhere before the script words; + everything after the script name still goes to the script (SPEC item + 3.1 unchanged). +- SPEC item 1.5 policy: reuse a popular, tested, trusted third-party + package when it exists instead of writing our own; argcomplete is + the first such dependency (SPEC item 9.6). + ## [0.2.0] - 2026-11-18 ### Added in 0.2.0 diff --git a/INSTALL.md b/INSTALL.md index 2610c19..5c08e48 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -6,6 +6,7 @@ bundles every registered one and works from any directory. - [Install](#install) - [Usage](#usage) +- [Tab completion](#tab-completion) - [Add a script](#add-a-script) - [Development](#development) @@ -119,6 +120,47 @@ Python scripts run through `daedalus/run_python_script.py`: they get shared code), file and console logging to `~/.daedalus/debug.log`, and their `sys.argv` and exit code passed through unchanged. +## Tab completion + +Completion is built with [argcomplete](https://github.com/kislyuk/argcomplete); +it completes script names, category labels, and options — including +script names after category labels. + +Bash: register once per shell, e.g. in `~/.bashrc` (the program on +`PATH` must be able to `import argcomplete`): + +```bash +eval "$(register-python-argcomplete daedalus)" +``` + +zsh: + +```bash +autoload -U bashcompinit && bashcompinit +eval "$(register-python-argcomplete daedalus)" +``` + +Try it in a new shell: + +```bash +daedalus hel # completes hello +daedalus test # lists the scripts (and labels) for the prefix +daedalus -- # completes the daedalus options +``` + +Notes: + +- `register-python-argcomplete` ships with the argcomplete package; it + comes with the pipx/pip install (a daedalus dependency since 0.3.0) + or with your system package (Debian: `python3-argcomplete`). +- Arguments after the script name belong to the script: a Python script + that calls `argcomplete.autocomplete(parser)` (SPEC item 6.9) completes + its own arguments — `daedalus hello -` offers hello's `-h`, + `--help`. Otherwise the shell offers file names there. +- A checkout run through `bin/daedalus` completes when the `python3` + it runs can `import argcomplete` and the marker comment stays in the + launcher (SPEC item 3.13.7). + ## Add a script - Put the file in the folder for its type: diff --git a/README.md b/README.md index 8634627..20a8c84 100644 --- a/README.md +++ b/README.md @@ -22,13 +22,20 @@ daedalus --list # list everything Run the sample script: ```bash -daedalus hello # hello from daedalus 0.2.0 +daedalus hello # hello from daedalus 0.3.0 daedalus test hello # same, through the category prefix daedalus test # list the scripts in the 'test' category ``` `daedalus --list` prints the version, a `script` / `type` / `categories` -table, and each description wrapped under its row. +table, and each description wrapped under each row. + +## Shell completion + +Bash (and other shells argcomplete supports) completes script names and +category labels: `daedalus hel` + TAB completes `hello`, `daedalus test h` + +TAB completes `hello` inside the category, and options complete after `-`. +See [INSTALL](./INSTALL.md#tab-completion). ## Getting started diff --git a/SPEC.md b/SPEC.md index 2a5ba4d..1faf5b7 100644 --- a/SPEC.md +++ b/SPEC.md @@ -49,8 +49,13 @@ added (section 6). - **1.4** Scripts are written in Python, bash, PowerShell, or batch. The CLI picks the interpreter from the file suffix and passes arguments, terminal, and exit code straight through. -- **1.5** The CLI itself uses only the Python standard library. Python - 3.11 or newer. +- **1.5** Reuse first: when a popular, widely tested, trusted + third-party package already solves a problem, use it instead of + writing our own code; the Python standard library covers the rest. + Python 3.11 or newer. Dependency policy: SPEC item 9.6. Today the one + dependency is argcomplete, for shell completion (SPEC item 3.13); + its import is guarded, so the CLI also runs where it is not + installed — completion is then off. ## 2. Layout @@ -59,12 +64,13 @@ added (section 6). ```text daedalus/ ├── bin/ -│ ├── daedalus # Linux launcher (bash), no install needed +│ ├── daedalus # Linux launcher (bash), no install needed; PYTHON_ARGCOMPLETE_OK marker │ └── daedalus.bat # Windows launcher (cmd / PowerShell) ├── daedalus/ # The CLI package │ ├── __init__.py # PACKAGE_DIR, REPO_ROOT, LIBRARY_ROOT, checkout imports │ ├── __main__.py # python -m daedalus -│ ├── cli.py # Argument handling, list, path, dispatch +│ ├── cli.py # argparse parser, list, path, dispatch +│ ├── completions.py # Completion candidates for argcomplete │ ├── registry.py # Script, SCRIPTS, category helpers │ ├── runners.py # Suffix -> interpreter command, run │ ├── run_python_script.py # Child entry for .py scripts (logging, argv) @@ -170,16 +176,28 @@ sample_script_name py general, linux - **3.7.3** `python -m daedalus` from the repository root. - **3.7.4** The installed command is the entry point `daedalus = daedalus.cli:main`. -- **3.8** `--help` prints this text: +- **3.8** `-h` / `--help` prints the argparse rendering of the parser in + SPEC item 3.10 (80 columns shown; wrapped to the terminal width): ```text -usage: daedalus [args...] run a script; args go to the script - daedalus [category...] list scripts (AND when multiple) - daedalus … [args...] run when script has every category - daedalus [-l | --list] list all registered scripts - daedalus --path print the path of a script - daedalus --version print the installed version - daedalus -h | --help show this help +usage: daedalus [-h] [-l | --list] [--version] [--path ] [ ...] [ [args ...]] + +One CLI, many small scripts, each with tests (SPEC.md). + +positional arguments: + category labels to filter or list, then the script name to + run + [args ...] arguments passed to the script + +options: + -h, --help show this help message and exit + -l, --list list all registered scripts + --version print the installed version + --path print the path of a script + +Forms: daedalus [args...] runs a script; daedalus +[category...] lists the scripts with every category (AND when several); +daedalus ... [args...] runs a script that has every category. ``` - **3.9** The version is resolved in this order: @@ -187,39 +205,60 @@ usage: daedalus [args...] run a script; args go to the - **3.9.2** `project.version` from `REPO_ROOT/pyproject.toml` (a checkout that is not installed). - **3.9.3** The string `unknown`. -- **3.10** Argument resolution. Options are recognized only as the first - token: +- **3.10** Argument resolution. One `argparse.ArgumentParser` + (`prog="daedalus"`, `allow_abbrev=False`, subclass whose `error()` + raises `UsageError` instead of exiting): ```text -dispatch(argv): - if argv is empty or argv[0] in ("-l", "--list"): list(all scripts); return 0 - if argv[0] in ("-h", "--help"): print usage; return 0 - if argv[0] == "--version": print "daedalus " + version; return 0 - if argv[0] == "--path": - require exactly one more token, else usage error - print absolute path of lookup(argv[1]) # file need not exist +parser arguments: + -l | --list store_true flag + --version store_true flag + --path + words positional, nargs "*", metavar + script_args positional, argparse.REMAINDER, metavar [args ...] + +main(argv = sys.argv[1:]): + parser = build_parser() + argcomplete.autocomplete(parser) when importable (SPEC item 3.13) + try: + parsed = parser.parse_args(argv) + return dispatch(parsed) + on usage or runner error: print "daedalus: " to stderr; return 2 + +dispatch(parsed): + if --list or ((words and script_args both empty) and no option set): + list(all scripts); return 0 + if --version: print "daedalus " + version; return 0 + if --path: + if words or script_args is not empty: usage error "usage: daedalus --path " + print absolute path of lookup(--path value) # file need not exist return 0 - if argv[0] starts with "-": usage error "unknown option" - prefix = leading tokens while is_category_label(token) - rest = remaining tokens + prefix = leading words entries while is_category_label(entry) + rest = remaining words entries if prefix and rest is empty: scripts = scripts having every label in prefix if none: usage error "no scripts for categories" list(scripts); return 0 - if prefix: script = lookup_in(prefix, rest[0]); return run(script, rest[1:]) - return run(lookup(argv[0]), argv[1:]) - -main(argv = sys.argv[1:]): - try dispatch(argv) - on usage or runner error: print "daedalus: " to stderr; return 2 + if rest: script = lookup_in(prefix, rest[0]) when prefix else lookup(rest[0]) + return run(script, rest[1:] + script_args) ``` -- **3.11** Error messages (each printed as `daedalus: `): +With argparse, options are parsed wherever argparse sees them before +the positionals start (the old first-token-only rule is gone), but +everything after the first positional word that argparse cannot bind +to `words` is captured by `script_args` (REMAINDER) and passed through +(SPEC item 3.1): `daedalus --help` still shows the **script's** +help. + +- **3.11** Error messages: parser errors carry the argparse message, + registry errors keep their exact texts; each is printed as + `daedalus: ` on stderr with exit code 2: | Case | Message | | --- | --- | -| `--path` without exactly one name | `usage: daedalus --path ` | -| Unknown option | `unknown option ''; run 'daedalus --help'` | +| `--path` without a value | `argument --path: expected one argument` | +| `--path` with extra words | `usage: daedalus --path ` | +| Unknown option | `unrecognized arguments: ` | | Unknown script, close matches exist | `unknown script ''; did you mean: , ` | | Unknown script, no close match | `unknown script ''; run 'daedalus --list'` | | Categories match no script | `no scripts for categories: , ` | @@ -229,6 +268,45 @@ main(argv = sys.argv[1:]): - **3.12** Close matches are up to 3 names with similarity ratio at least 0.6 (Python `difflib.get_close_matches` defaults). After a category prefix, only scripts in those categories are candidates. +- **3.13** Shell completion for the parser above (SPEC item 3.10) comes + from argcomplete (SPEC item 1.5): + - **3.13.1** `main` calls `argparse` completion via + `argcomplete.autocomplete(parser)` before `parse_args`, when + argcomplete is importable. Without argcomplete the CLI runs + unchanged, with completion off. + - **3.13.2** Activation (bash): `eval "$(register-python-argcomplete + daedalus)"` in `~/.bashrc`; `register-python-argcomplete` ships with + argcomplete. Other shells argcomplete supports (zsh, fish, tcsh, + powershell) register the same way. + - **3.13.3** Completing a `words` entry (SPEC item 3.10): + `daedalus/completions.py` offers every registered script name and + every category label in use, narrowed by prefix; category labels + already typed are not offered again, and script candidates narrow to + the scripts that have every typed label (SPEC item 3.4): `daedalus + test h` completes `hello`. Candidates are sorted. + - **3.13.4** `--path ` completes script names. + - **3.13.5** After a registered script name has been typed (completed, + before the word being completed), the rest of the line belongs to + the script (SPEC item 3.1): daedalus offers nothing of its own — + not its options, and never the working-directory file listing (the + `script_args` action keeps its empty completer, SPEC 3.10). + - **3.13.5.1** A `.py` script is asked to complete its own + arguments: daedalus re-execs the interpreter command of its + runner (SPEC item 5.8) with the argument words as the script's + argv, `COMP_LINE` rewritten to start at the script name, + `COMP_POINT` adjusted, the completion environment passed + through, and the completion channel (fd 8) inherited. The script + completes its arguments (SPEC item 6.9); quoting in the words is + not preserved in the rewrite. + - **3.13.5.2** bash, PowerShell, and batch scripts get no + candidates: the shell default completion (file names) applies. + - **3.13.6** The completion hook re-runs the `daedalus` command on + `PATH`: the program that runs on TAB must import argcomplete + (installed dependency, or the dev venv, or the system package) and + must reach `autocomplete` before parsing. + - **3.13.7** `bin/daedalus` carries a `# PYTHON_ARGCOMPLETE_OK` comment + in its first kilobyte: argcomplete versions that scan for the + marker require it. ## 4. Registry @@ -380,6 +458,14 @@ SCRIPTS: dict[str, Script] = { - **6.7** Bump `version` in `pyproject.toml` and add a `CHANGELOG.md` entry. - **6.8** Run `python autotest.py`. It must pass before pushing. +- **6.9** A Python script opts in to completing its own arguments + (SPEC item 3.13.5.1): right after building its parser it calls + `argcomplete.autocomplete(parser)` behind a guarded import (SPEC item + 1.5). `daedalus ... -` then completes the + script's own options; without the call, such words fall back to the + shell default, and a TAB can run the script itself (argcomplete + semantics — scripts that must not run on TAB do not opt in or keep + their parser behind a subcommand). ## 7. Quality gates @@ -445,7 +531,8 @@ autotest results `pip install -r requirements.txt`, then `python autotest.py`. The sanity diff base is passed as `SANITY_DIFF_BASE`. - **7.11** `requirements.txt` holds the tools: `pytest`, `pytest-cov`, - `pycodestyle`, `pymarkdownlnt`, `pyyaml`, `shellcheck-py`, `setuptools`. + `pycodestyle`, `pymarkdownlnt`, `pyyaml`, `shellcheck-py`, `setuptools`, + and `argcomplete` (the runtime dependency, so the completion tests run). ## 8. Conventions @@ -499,9 +586,11 @@ autotest results resolve to (section 10). - **9.5** Tests under `*/tests/`, bytecode, and `.gitkeep` are not packaged. -- **9.6** Runtime dependencies: none; the CLI uses only the standard - library. A script that needs third-party packages says so in its own - help text and fails with a clear message when they are missing; +- **9.6** Runtime dependencies follow SPEC item 1.5 (reuse first): the + wheel declares `argcomplete >= 3` for shell completion (SPEC item + 3.13); everything else is the standard library. A script that needs + other third-party packages says so in its own help text and fails + with a clear message when they are missing; `DAEDALUS_PYTHON` (SPEC item 5.2) points it at their environment. Test and lint tools stay in `requirements.txt`. - **9.7** Tests build the wheel from a copy of the checkout and check: @@ -587,3 +676,4 @@ on import daedalus: | 16 | `run_python_script.py` and `daedalus_logging` (section 11) | Done | | 17 | `daedalus.` imports in checkouts and installs (section 10) | Done | | 18 | Listing table with version line, wrapped descriptions, and color (SPEC item 3.3) | Done | +| 19 | argparse parser and argcomplete shell completion (SPEC items 3.10, 3.13) | Done | diff --git a/bin/daedalus b/bin/daedalus index e5d2901..f628df7 100755 --- a/bin/daedalus +++ b/bin/daedalus @@ -1,5 +1,6 @@ #!/usr/bin/env bash # Run the daedalus CLI from this checkout without installing it. +# PYTHON_ARGCOMPLETE_OK set -euo pipefail repo_root="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/.." && pwd)" export PYTHONPATH="${repo_root}${PYTHONPATH:+:${PYTHONPATH}}" diff --git a/daedalus/cli.py b/daedalus/cli.py index 99c2dc3..65d133b 100644 --- a/daedalus/cli.py +++ b/daedalus/cli.py @@ -1,9 +1,11 @@ """daedalus command line: list, locate, and run registered scripts. -Entry point for ``daedalus [args...]``; see SPEC.md section 3. +``daedalus [args...]`` parsed with argparse; completion via +argcomplete; see SPEC.md section 3. """ from __future__ import annotations +import argparse import difflib import importlib.metadata import os @@ -12,17 +14,25 @@ import sys import textwrap import tomllib +try: # SPEC item 1.5: completion is optional and never breaks the CLI + from argcomplete import autocomplete as _autocomplete +except ImportError: # pragma: no cover - only hit without argcomplete + _autocomplete = None + from daedalus import REPO_ROOT +from daedalus import completions from daedalus import registry from daedalus import runners -USAGE = """usage: daedalus [args...] run a script; args go to the script - daedalus [category...] list scripts (AND when multiple) - daedalus … [args...] run when script has every category - daedalus [-l | --list] list all registered scripts - daedalus --path print the path of a script - daedalus --version print the installed version - daedalus -h | --help show this help""" +USAGE = ("daedalus [-h] [-l | --list] [--version] [--path ] " + "[ ...] [ [args ...]]") + +PARSER_DESCRIPTION = "One CLI, many small scripts, each with tests (SPEC.md)." + +PARSER_EPILOG = ("Forms: daedalus [args...] runs a script; " + "daedalus [category...] lists the scripts with " + "every category (AND when several); daedalus ... " + " [args...] runs a script that has every category.") TYPE_COLUMN_MIN_WIDTH = 4 DESCRIPTION_INDENT = " " * 8 @@ -38,6 +48,35 @@ class UsageError(Exception): """Bad daedalus arguments or an unknown script name.""" +class DaedalusParser(argparse.ArgumentParser): + """Parser that raises UsageError instead of exiting (SPEC item 3.11).""" + + def error(self, message: str) -> None: + """argparse would exit(2); return the message through main instead.""" + raise UsageError(message) + + +def build_parser() -> DaedalusParser: + """The daedalus parser: options, category words, script args (SPEC item 3.10).""" + parser = DaedalusParser(prog="daedalus", usage=USAGE, allow_abbrev=False, + description=PARSER_DESCRIPTION, epilog=PARSER_EPILOG) + parser.add_argument("-l", "--list", action="store_true", + help="list all registered scripts") + parser.add_argument("--version", action="store_true", + help="print the installed version") + path_action = parser.add_argument("--path", metavar="", + help="print the path of a script") + words_action = parser.add_argument("words", metavar="", nargs="*", + help="category labels to filter or list, then the script name to run") + script_args_action = parser.add_argument("script_args", metavar="[args ...]", + nargs=argparse.REMAINDER, + help="arguments passed to the script") + path_action.completer = completions.scripts_completer + words_action.completer = completions.words_completer + script_args_action.completer = completions.script_args_completer + return parser + + def colors_enabled(stream=None) -> bool: """NO_COLOR unset/empty and (FORCE_COLOR or a terminal): SPEC item 3.3.6.""" stream = sys.stdout if stream is None else stream @@ -143,26 +182,24 @@ def lookup_in(prefix: list[str], name: str) -> registry.Script: raise UsageError(f"unknown script '{name}' for '{joined}'; run 'daedalus {joined}'") -def dispatch(argv: list[str]) -> int: - """Handle daedalus options, categories, or run a script (SPEC item 3.10).""" - if not argv or argv[0] in ("-l", "--list"): +def dispatch(parsed: argparse.Namespace) -> int: + """Handle the parsed daedalus arguments: options, lists, or run (SPEC item 3.10).""" + if parsed.list: print(format_list(registry.SCRIPTS)) return 0 - if argv[0] in ("-h", "--help"): - print(USAGE) - return 0 - if argv[0] == "--version": + if parsed.version: print(f"daedalus {version()}") return 0 - if argv[0] == "--path": - if len(argv) != 2: + if parsed.path is not None: + if parsed.words or parsed.script_args: raise UsageError("usage: daedalus --path ") - print(lookup(argv[1]).absolute_path) + print(lookup(parsed.path).absolute_path) + return 0 + if not parsed.words and not parsed.script_args: + print(format_list(registry.SCRIPTS)) return 0 - if argv[0].startswith("-"): - raise UsageError(f"unknown option {argv[0]!r}; run 'daedalus --help'") prefix: list[str] = [] - rest = list(argv) + rest = list(parsed.words) while rest and registry.is_category_label(rest[0]): prefix.append(rest.pop(0)) if prefix and not rest: @@ -171,15 +208,22 @@ def dispatch(argv: list[str]) -> int: raise UsageError(f"no scripts for categories: {', '.join(prefix)}") print(format_list(scripts)) return 0 - if prefix: - return runners.run(lookup_in(prefix, rest[0]).absolute_path, rest[1:]) - return runners.run(lookup(rest[0]).absolute_path, rest[1:]) + if rest: + script = lookup_in(prefix, rest[0]) if prefix else lookup(rest[0]) + return runners.run(script.absolute_path, rest[1:] + parsed.script_args) + return 0 def main(argv: list[str] | None = None) -> int: """CLI entry point; daedalus errors exit with 2 (SPEC item 3.10).""" + parser = build_parser() + if completions.handles_script_args(): # SPEC item 3.13.5: delegated or silent + return 0 + if _autocomplete is not None: # SPEC item 3.13.1 + _autocomplete(parser) try: - return dispatch(sys.argv[1:] if argv is None else argv) + parsed = parser.parse_args(sys.argv[1:] if argv is None else argv) + return dispatch(parsed) except (UsageError, runners.RunnerError) as error: print(f"daedalus: {error}", file=sys.stderr) return 2 diff --git a/daedalus/completions.py b/daedalus/completions.py new file mode 100644 index 0000000..2d05155 --- /dev/null +++ b/daedalus/completions.py @@ -0,0 +1,111 @@ +"""Completion candidates and delegation for the daedalus CLI (SPEC item 3.13). + +argcomplete calls the candidate functions while the shell completes the +command line; they are plain functions on the registry, so the logic +runs without argcomplete installed too (SPEC items 1.5, 3.13.1). When a +registered script name is already typed, completion of the remaining +words is delegated to the script itself (SPEC item 3.13.5.1). +""" +from __future__ import annotations + +import os + +from daedalus import registry +from daedalus import runners + + +def scripts_completer(prefix: str, **_kwargs) -> list[str]: + """Every script name starting with prefix; used by --path (SPEC item 3.13.4).""" + return sorted(name for name in registry.SCRIPTS if name.startswith(prefix)) + + +def script_args_completer(*_args, **_kwargs) -> list[str]: + """No candidates from daedalus: the args belong to the script (SPEC item 3.1). + + Without this, argcomplete would fall back to its file completer and + list the whole working directory on an empty word (SPEC item 3.13.5); + the shell's own default still offers file names. + """ + return [] + + +def words_completer(prefix: str, **kwargs) -> list[str]: + """Candidates for the word being typed in words (SPEC item 3.13.3). + + Typed category labels are not offered again and narrow the script + candidates to the scripts that have every typed label. Once a word is + neither a label nor listable as one, the rest of the line belongs to + the script and nothing is completed (SPEC item 3.1); the shell default + (file names) then applies. + """ + parsed_args = kwargs.get("parsed_args") + typed = list(getattr(parsed_args, "words", None) or []) + prefix_labels: list[str] = [] + for word in typed: + if not registry.is_category_label(word): + return [] + prefix_labels.append(word) + candidates = (registry.used_categories() - set(prefix_labels)) | set( + registry.scripts_matching_categories(prefix_labels)) + return sorted(name for name in candidates if name.startswith(prefix)) + + +def _cursor_words() -> tuple[list[str], str]: + """Words completed before the cursor and the word being completed now.""" + comp_line = os.environ.get("COMP_LINE") or "" + comp_point = os.environ.get("COMP_POINT") or str(len(comp_line)) + try: + from argcomplete import lexers + except ImportError: + return [], "" + _prequote, partial, _suffix, words, _pos = lexers.split_line( + comp_line, int(comp_point)) + return list(words), partial + + +def script_args_delegation() -> tuple[registry.Script, str, list[str]] | None: + """(script, child COMP_LINE, script argv tail) once a script name is completed. + + The walk mirrors dispatch (SPEC item 3.10): leading category labels, + then the script name. The line handed to the script starts at the + script name, with the tail words and the word being completed, so the + script's own parser completes them (SPEC item 3.13.5.1). + """ + if "_ARGCOMPLETE" not in os.environ: + return None + words, partial = _cursor_words() + args = list(words[1:]) + prefix: list[str] = [] + while args and registry.is_category_label(args[0]): + prefix.append(args.pop(0)) + if not args or args[0] not in registry.SCRIPTS: + return None + name = args[0] + script = registry.SCRIPTS[name] + tail = [*args[1:], partial] + comp_line = " ".join([name, *tail]) + return script, comp_line, tail + + +def _exec_delegate(command: str, argv: list[str], env: dict[str, str]) -> None: + """Replace this process with the script runner (fd 8 travels along).""" + os.execve(command, argv, env) + + +def handles_script_args(execute=_exec_delegate) -> bool: + """True when the completion belongs to the script's own args (SPEC item 3.13.5). + + A .py script is execed through its runner command with the completion + environment rewritten to start at the script name (SPEC item 3.13.5.1); + other suffixes get no candidates at all (SPEC item 3.13.5.2). + """ + plan = script_args_delegation() + if plan is None: + return False + script, comp_line, tail = plan + path = script.absolute_path + if path.suffix.lower() == ".py" and path.is_file(): + command = runners.python_command(path) + env = dict(os.environ, COMP_LINE=comp_line, COMP_POINT=str(len(comp_line))) + execute(command[0], [*command, *tail], env) + return True diff --git a/daedalus/tests/test_cli.py b/daedalus/tests/test_cli.py index 586641c..bb4bb44 100644 --- a/daedalus/tests/test_cli.py +++ b/daedalus/tests/test_cli.py @@ -127,11 +127,15 @@ def test_list_no_color_wins(fake_registry, monkeypatch, capsys): @pytest.mark.parametrize("argv", [["-h"], ["--help"]]) def test_help(fake_registry, plain, capsys, argv): - """--help prints the full usage with category forms (SPEC item 3.8).""" - assert cli.main(argv) == 0 + """-h/--help print the argparse rendering of the parser (SPEC item 3.8).""" + with pytest.raises(SystemExit) as caught: + cli.main(argv) + assert caught.value.code == 0 out = capsys.readouterr().out - assert "daedalus [args...]" in out - assert "daedalus [category...]" in out + assert out.startswith("usage: daedalus") + assert "-l, --list" in out + assert "--path " in out + assert "Forms: daedalus [args...]" in out def test_path(fake_registry, capsys): @@ -140,7 +144,13 @@ def test_path(fake_registry, capsys): assert capsys.readouterr().out.strip() == str(LIBRARY_ROOT / "python/src/alpha/alpha.py") -@pytest.mark.parametrize("installed, expected", [(True, "daedalus 1.2.3"), (False, "daedalus 0.2.0")]) +def test_path_with_extra_words_is_a_usage_error(fake_registry, plain, capsys): + """--path takes exactly one name; more is a usage error (SPEC item 3.11).""" + assert cli.main(["--path", "alpha", "media"]) == 2 + assert "usage: daedalus --path " in capsys.readouterr().err + + +@pytest.mark.parametrize("installed, expected", [(True, "daedalus 1.2.3"), (False, "daedalus 0.3.0")]) def test_version(monkeypatch, capsys, installed, expected): """--version uses metadata or pyproject.toml in a checkout.""" def fake_version(_name): @@ -154,8 +164,8 @@ def test_version(monkeypatch, capsys, installed, expected): @pytest.mark.parametrize("argv, message", [ - (["--path"], "usage: daedalus --path"), - (["--bogus"], "unknown option '--bogus'; run 'daedalus --help'"), + (["--path"], "argument --path: expected one argument"), + (["--bogus"], "unrecognized arguments: --bogus"), (["alpah"], "unknown script 'alpah'; did you mean: alpha"), (["zzz"], "unknown script 'zzz'; run 'daedalus --list'"), ]) @@ -173,6 +183,14 @@ def test_dispatch_passes_args_through(fake_registry, plain, monkeypatch): assert calls == [(LIBRARY_ROOT / "python/src/alpha/alpha.py", ["--help", "x"])] +def test_flags_after_the_script_name_go_to_the_script(fake_registry, plain, monkeypatch): + """A daedalus option typed after the script name is passed through (SPEC item 3.1).""" + calls = [] + monkeypatch.setattr(runners, "run", lambda path, args: calls.append((path, args)) or 7) + assert cli.main(["media", "beta_tool", "-l", "x"]) == 7 + assert calls == [(LIBRARY_ROOT / "bash/beta_tool.sh", ["-l", "x"])] + + def test_runner_error_exits_2(fake_registry, plain, capsys): """A missing script file exits 2 instead of a traceback.""" assert cli.main(["alpha"]) == 2 @@ -287,3 +305,11 @@ def test_bash_launcher(): launcher = str(REPO_ROOT / "bin" / "daedalus") assert run_cli("bash", launcher, "--list").returncode == 0 assert run_cli("bash", launcher, "no_such_script").returncode == 2 + + +@pytest.mark.skipif(os.name == "nt", reason="bash launcher is for Linux") +def test_bash_launcher_carries_completion_marker(): + """bin/daedalus starts with the PYTHON_ARGCOMPLETE_OK comment (SPEC item 3.13.7).""" + launcher = REPO_ROOT / "bin" / "daedalus" + head = launcher.read_bytes()[:1024] + assert b"PYTHON_ARGCOMPLETE_OK" in head diff --git a/daedalus/tests/test_completions.py b/daedalus/tests/test_completions.py new file mode 100644 index 0000000..c641f88 --- /dev/null +++ b/daedalus/tests/test_completions.py @@ -0,0 +1,267 @@ +"""Tests for daedalus.completions (SPEC item 3.13). + +The candidate functions are plain callables, so the category logic runs +without argcomplete; the end-to-end probe replays what the bash hook does +when argcomplete is importable. +""" +import importlib.util +import os +import shlex +import subprocess +import sys +import types + +import pytest + +from daedalus import REPO_ROOT +from daedalus import completions +from daedalus import registry + +FAKE_SCRIPTS = { + "alpha": registry.Script("python/src/alpha/alpha.py", "First tool"), + "beta_tool": registry.Script("bash/beta_tool.sh", "Second tool", + categories=("media", "linux")), + "gamma": registry.Script("powershell/gamma.ps1", "Third tool", categories="media"), + "hello": registry.Script("python/src/hello/hello.py", "Says hello", categories="test"), +} + + +@pytest.fixture +def fake_registry(monkeypatch): + """Replace SCRIPTS with a registry that has several categories.""" + monkeypatch.setattr(registry, "SCRIPTS", dict(FAKE_SCRIPTS)) + + +def words_completer(prefix: str, typed: list) -> list: + """Call words_completer the way argcomplete does (SPEC item 3.13.3).""" + parsed = types.SimpleNamespace(words=typed, script_args=[]) + result = completions.words_completer(prefix, action=None, parsed_args=parsed, + parser=None) + return list(result) + + +def test_first_word_offers_scripts_and_labels(fake_registry): + """Completing the first word offers every script and category (SPEC item 3.13.3).""" + assert words_completer("", []) == ["alpha", "beta_tool", "gamma", "general", + "hello", "linux", "media", "test"] + + +def test_first_word_narrows_by_prefix(fake_registry): + """Only candidates starting with the partial word are offered.""" + assert words_completer("he", []) == ["hello"] + assert words_completer("hel", []) == ["hello"] + assert words_completer("zzz", []) == [] + + +def test_category_prefix_narrows_scripts(fake_registry): + """Typed labels narrow the scripts to the ones that have every label.""" + assert words_completer("", ["media"]) == ["beta_tool", "gamma", + "general", "linux", "test"] + + +def test_category_prefix_narrows_by_prefix(fake_registry): + """daedalus media b offers beta_tool, not alpha (the user's case).""" + assert words_completer("b", ["media"]) == ["beta_tool"] + assert words_completer("h", ["test"]) == ["hello"] + + +def test_typed_labels_are_not_offered_again(fake_registry): + """A category already typed is not a candidate again.""" + assert "media" not in words_completer("", ["media"]) + assert "media" not in words_completer("med", ["media"]) + + +def test_after_a_script_name_nothing_is_completed(fake_registry): + """After the script name the candidates are empty: pass-through (SPEC item 3.13.5).""" + assert words_completer("", ["hello"]) == [] + assert words_completer("x", ["alpha"]) == [] + + +def test_unknown_word_stops_completion(fake_registry): + """A word that is neither a label nor a script stops completion.""" + assert words_completer("", ["not_a_label"]) == [] + + +def test_scripts_completer_for_path(fake_registry): + """--path completes every script name, narrowed by prefix (SPEC item 3.13.4).""" + assert completions.scripts_completer("al", parsed_args=None) == ["alpha"] + assert completions.scripts_completer("", parsed_args=None) == sorted(FAKE_SCRIPTS) + + +def test_parser_attaches_the_completers(fake_registry): + """build_parser wires the completers onto the actions (SPEC item 3.13.1).""" + from daedalus import cli + parser = cli.build_parser() + by_dest = {action.dest: action for action in parser._actions} + assert by_dest["words"].completer is completions.words_completer + assert by_dest["path"].completer is completions.scripts_completer + assert by_dest["script_args"].completer("", parsed_args=None) == [] + + +def test_script_args_complete_to_nothing(): + """daedalus never completes the script's own args (SPEC item 3.1).""" + assert completions.script_args_completer("", parsed_args=None) == [] + assert completions.script_args_completer("-") == [] + + +def set_comp_line(monkeypatch, line: str, point: int | None = None) -> None: + """Set the env exactly the way the argcomplete bash hook does.""" + monkeypatch.setenv("_ARGCOMPLETE", "1") + monkeypatch.setenv("COMP_LINE", line) + monkeypatch.setenv("COMP_POINT", str(point if point is not None else len(line))) + + +def test_delegation_after_script_name(fake_registry, monkeypatch): + """Completing daedalus hello - delegates to hello's parser (SPEC item 3.13.5.1).""" + set_comp_line(monkeypatch, "daedalus hello -") + assert completions.script_args_delegation() == (FAKE_SCRIPTS["hello"], "hello -", ["-"]) + + +def test_delegation_after_category_prefix(fake_registry, monkeypatch): + """Delegation also works through a category prefix.""" + set_comp_line(monkeypatch, "daedalus test hello --") + assert completions.script_args_delegation() == (FAKE_SCRIPTS["hello"], "hello --", ["--"]) + + +def test_delegation_keeps_trailing_space(fake_registry, monkeypatch): + """An empty word being completed stays an empty word for the script.""" + set_comp_line(monkeypatch, "daedalus hello ") + assert completions.script_args_delegation() == (FAKE_SCRIPTS["hello"], "hello ", [""]) + + +def test_delegation_only_after_completed_script_name(fake_registry, monkeypatch): + """No delegation while the script name itself is being completed.""" + set_comp_line(monkeypatch, "daedalus he") + assert completions.script_args_delegation() is None + set_comp_line(monkeypatch, "daedalus test he") + assert completions.script_args_delegation() is None + set_comp_line(monkeypatch, "daedalus hello") + assert completions.script_args_delegation() is None + + +def test_delegation_needs_the_argcomplete_env(fake_registry, monkeypatch): + """Outside completion mode there is nothing to delegate.""" + monkeypatch.delenv("_ARGCOMPLETE", raising=False) + set_comp_line(monkeypatch, "daedalus hello ") + monkeypatch.delenv("_ARGCOMPLETE", raising=False) + assert completions.script_args_delegation() is None + + +def test_handles_delegates_py_scripts(fake_registry, monkeypatch): + """A .py script runs through run_python_script with the rewritten line.""" + from daedalus import runners + set_comp_line(monkeypatch, "daedalus hello x") + calls = [] + + def fake_execute(command, argv, env): + calls.append((command, argv, env)) + + assert completions.handles_script_args(execute=fake_execute) is True + _command, argv, env = calls[0] + assert argv[1:4] == [str(runners.PYTHON_CHILD), + str(FAKE_SCRIPTS["hello"].absolute_path), "x"] + assert env["COMP_LINE"] == "hello x" + assert env["COMP_POINT"] == "7" + + +def test_handles_silences_non_py_scripts(fake_registry, monkeypatch): + """Non-python scripts just offer nothing (SPEC item 3.13.5.2).""" + set_comp_line(monkeypatch, "daedalus beta_tool x") + executed = [] + assert completions.handles_script_args(execute=executed.append) is True + assert executed == [] + + +def test_handles_false_without_script_word(fake_registry, monkeypatch): + """Without a completed script name, daedalus completes itself.""" + set_comp_line(monkeypatch, "daedalus test ") + assert completions.handles_script_args() is False + set_comp_line(monkeypatch, "daedalus -") + assert completions.handles_script_args() is False + + +def test_main_delegates_before_parsing(fake_registry, monkeypatch, capsys): + """main hands script-arg completion over before any parsing or running.""" + from daedalus import cli + monkeypatch.setattr(completions, "handles_script_args", lambda execute=None: True) + assert cli.main(["hello", "-x"]) == 0 + assert capsys.readouterr().out == "" + + +def _probe(comp_line: str) -> str: + """Replay the argcomplete hook for comp_line and return the candidates.""" + env = dict( + os.environ, + _ARGCOMPLETE="1", + COMP_LINE=comp_line, + COMP_POINT=str(len(comp_line)), + _ARGCOMPLETE_IFS="\n", + _ARGCOMPLETE_SHELL="bash", + NO_COLOR="1", + ) + command = f"exec 8>&1; exec 1>/dev/null; exec 2>/dev/null; {shlex.quote(sys.executable)} -m daedalus" + result = subprocess.run(["bash", "-c", command], env=env, cwd=str(REPO_ROOT), + capture_output=True, text=True, check=False) + return result.stdout + + +requires_argcomplete = pytest.mark.skipif( + importlib.util.find_spec("argcomplete") is None, + reason="end-to-end completion needs argcomplete", +) + + +def _candidates(comp_line: str) -> list: + """The candidate words from the argcomplete hook for comp_line.""" + return [line.strip() for line in _probe(comp_line).splitlines() if line.strip()] + + +@requires_argcomplete +def test_end_to_end_first_word(): + """daedalus h completes hello through the argcomplete protocol.""" + assert _candidates("daedalus h") == ["hello"] + + +@requires_argcomplete +def test_end_to_end_after_category_prefix(): + """daedalus test h completes hello (the sub parser case).""" + assert _candidates("daedalus test h") == ["hello"] + + +@requires_argcomplete +def test_end_to_end_empty_word_lists_only_candidates(): + """On an empty word, only daedalus offers: options plus scripts and labels.""" + candidates = _candidates("daedalus test ") + assert "hello" in candidates + assert ".md" not in " ".join(candidates) + + +@requires_argcomplete +def test_end_to_end_options_for_dash_prefix(): + """A word starting with - completes daedalus's options, not scripts (SPEC item 3.10).""" + candidates = _candidates("daedalus --") + assert "--list" in candidates + assert "--path" in candidates + assert "hello" not in candidates + + +@requires_argcomplete +def test_end_to_end_after_script_name_offers_no_daedalus_candidates(): + """daedalus hello delegates: hello's own options, none of daedalus's (SPEC item 3.13.5).""" + assert _candidates("daedalus hello ") == ["-h", "--help"] + + +@requires_argcomplete +def test_end_to_end_script_options_come_from_the_script(): + """daedalus hello - delegates: hello's options, never daedalus's (3.13.5.1).""" + candidates = _candidates("daedalus hello -") + assert "-h" in candidates + assert "--help" in candidates + assert "--list" not in candidates + assert "--path" not in candidates + + +@requires_argcomplete +def test_end_to_end_delegation_through_category(): + """daedalus test hello -- completes hello's --help through the prefix.""" + assert _candidates("daedalus test hello --") == ["--help"] diff --git a/pyproject.toml b/pyproject.toml index ba68dc5..60ff805 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,11 +4,11 @@ build-backend = "setuptools.build_meta" [project] name = "daedalus" -version = "0.2.0" +version = "0.3.0" description = "Template for daedalus: loose scripts in one repo, run with: daedalus [args...]" readme = "README.md" requires-python = ">=3.11" -dependencies = [] +dependencies = ["argcomplete>=3.3"] [project.scripts] daedalus = "daedalus.cli:main" diff --git a/python/src/hello/hello.py b/python/src/hello/hello.py index 675c57c..60386ba 100644 --- a/python/src/hello/hello.py +++ b/python/src/hello/hello.py @@ -12,6 +12,11 @@ import pathlib import sys import tomllib +try: # SPEC item 6.9: complete hello's own arguments + from argcomplete import autocomplete +except ImportError: # pragma: no cover - completion off without argcomplete + autocomplete = None + UNKNOWN = "unknown" @@ -35,6 +40,8 @@ def main(argv: list[str] | None = None) -> int: """Print ``hello from daedalus ``; return the exit code.""" parser = argparse.ArgumentParser(prog="hello", description=__doc__.splitlines()[0]) + if autocomplete is not None: # SPEC item 6.9 + autocomplete(parser) parser.parse_args(argv) print(f"hello from daedalus {app_version()}") return 0 diff --git a/python/tests/test_hello.py b/python/tests/test_hello.py index f038fe6..3ff3611 100644 --- a/python/tests/test_hello.py +++ b/python/tests/test_hello.py @@ -34,7 +34,7 @@ def test_app_version_falls_back_to_pyproject(monkeypatch): raise hello.importlib.metadata.PackageNotFoundError(_name) monkeypatch.setattr(hello.importlib.metadata, "version", not_found) - assert hello.app_version() == "0.2.0" + assert hello.app_version() == "0.3.0" def test_help_exits_zero(capsys): diff --git a/requirements.txt b/requirements.txt index 76b40fb..7c412e6 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,3 +5,4 @@ pymarkdownlnt>=0.9.20 pyyaml>=6.0 shellcheck-py>=0.10 setuptools>=68 +argcomplete>=3.3