daedalus 0.3.0: argparse CLI + argcomplete shell completion, script-arg delegation
- cli.py rewritten on argparse (build_parser, REMAINDER pass-through: everything after the script name still belongs to the script); help/errors are argparse-rendered, exit code 2 kept for all daedalus errors - completions.py (new): category-aware candidates for argcomplete - script names + unused labels narrowed by typed labels (daedalus test h<TAB> -> hello); --path completes scripts; after a completed script name daedalus offers nothing of its own and delegates .py scripts to their own parser via the run_python_script child with a rewritten COMP_LINE (daedalus hello -<TAB> -> hello's -h --help); SPEC 6.9 documents the autocomplete(parser) opt-in - SPEC: item 1.5 reuse-first third-party policy, 3.8/3.10/3.11 argparse texts, 3.13 completion catalog, 6.9 script opt-in, 9.6 argcomplete dependency - argcomplete>=3.3 as runtime dep (guarded import: CLI runs without it); register-python-argcomplete line for ~/.bashrc; PYTHON_ARGCOMPLETE_OK marker in bin/daedalus; README/INSTALL/CHANGELOG updated; hello opts in - tests: argparse CLI suites, completer units, end-to-end argcomplete probes through the bash fd-8 protocol and the delegation exec chain (autotest green, coverage 97%) Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
@@ -10,6 +10,35 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and
|
|||||||
|
|
||||||
- Nothing yet.
|
- 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<TAB>` completes `hello`, category
|
||||||
|
labels complete together with the scripts they filter (`daedalus test
|
||||||
|
h<TAB>`), options complete after `-`, and `--path <name>` 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 -<TAB>` 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
|
## [0.2.0] - 2026-11-18
|
||||||
|
|
||||||
### Added in 0.2.0
|
### Added in 0.2.0
|
||||||
|
|||||||
+42
@@ -6,6 +6,7 @@ bundles every registered one and works from any directory.
|
|||||||
|
|
||||||
- [Install](#install)
|
- [Install](#install)
|
||||||
- [Usage](#usage)
|
- [Usage](#usage)
|
||||||
|
- [Tab completion](#tab-completion)
|
||||||
- [Add a script](#add-a-script)
|
- [Add a script](#add-a-script)
|
||||||
- [Development](#development)
|
- [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
|
shared code), file and console logging to `~/.daedalus/debug.log`, and
|
||||||
their `sys.argv` and exit code passed through unchanged.
|
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<TAB> # completes hello
|
||||||
|
daedalus test <TAB><TAB> # lists the scripts (and labels) for the prefix
|
||||||
|
daedalus --<TAB> # 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 -<TAB>` 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
|
## Add a script
|
||||||
|
|
||||||
- Put the file in the folder for its type:
|
- Put the file in the folder for its type:
|
||||||
|
|||||||
@@ -22,13 +22,20 @@ daedalus --list # list everything
|
|||||||
Run the sample script:
|
Run the sample script:
|
||||||
|
|
||||||
```bash
|
```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 hello # same, through the category prefix
|
||||||
daedalus test # list the scripts in the 'test' category
|
daedalus test # list the scripts in the 'test' category
|
||||||
```
|
```
|
||||||
|
|
||||||
`daedalus --list` prints the version, a `script` / `type` / `categories`
|
`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
|
## Getting started
|
||||||
|
|
||||||
|
|||||||
@@ -49,8 +49,13 @@ added (section 6).
|
|||||||
- **1.4** Scripts are written in Python, bash, PowerShell, or batch. The
|
- **1.4** Scripts are written in Python, bash, PowerShell, or batch. The
|
||||||
CLI picks the interpreter from the file suffix and passes arguments,
|
CLI picks the interpreter from the file suffix and passes arguments,
|
||||||
terminal, and exit code straight through.
|
terminal, and exit code straight through.
|
||||||
- **1.5** The CLI itself uses only the Python standard library. Python
|
- **1.5** Reuse first: when a popular, widely tested, trusted
|
||||||
3.11 or newer.
|
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
|
## 2. Layout
|
||||||
|
|
||||||
@@ -59,12 +64,13 @@ added (section 6).
|
|||||||
```text
|
```text
|
||||||
daedalus/
|
daedalus/
|
||||||
├── bin/
|
├── 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.bat # Windows launcher (cmd / PowerShell)
|
||||||
├── daedalus/ # The CLI package
|
├── daedalus/ # The CLI package
|
||||||
│ ├── __init__.py # PACKAGE_DIR, REPO_ROOT, LIBRARY_ROOT, checkout imports
|
│ ├── __init__.py # PACKAGE_DIR, REPO_ROOT, LIBRARY_ROOT, checkout imports
|
||||||
│ ├── __main__.py # python -m daedalus
|
│ ├── __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
|
│ ├── registry.py # Script, SCRIPTS, category helpers
|
||||||
│ ├── runners.py # Suffix -> interpreter command, run
|
│ ├── runners.py # Suffix -> interpreter command, run
|
||||||
│ ├── run_python_script.py # Child entry for .py scripts (logging, argv)
|
│ ├── 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.3** `python -m daedalus` from the repository root.
|
||||||
- **3.7.4** The installed command is the entry point
|
- **3.7.4** The installed command is the entry point
|
||||||
`daedalus = daedalus.cli:main`.
|
`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
|
```text
|
||||||
usage: daedalus <name> [args...] run a script; args go to the script
|
usage: daedalus [-h] [-l | --list] [--version] [--path <name>] [<category> ...] [<name> [args ...]]
|
||||||
daedalus <category> [category...] list scripts (AND when multiple)
|
|
||||||
daedalus <category>… <name> [args...] run when script has every category
|
One CLI, many small scripts, each with tests (SPEC.md).
|
||||||
daedalus [-l | --list] list all registered scripts
|
|
||||||
daedalus --path <name> print the path of a script
|
positional arguments:
|
||||||
daedalus --version print the installed version
|
<category|name> category labels to filter or list, then the script name to
|
||||||
daedalus -h | --help show this help
|
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 <name> print the path of a script
|
||||||
|
|
||||||
|
Forms: daedalus <name> [args...] runs a script; daedalus <category>
|
||||||
|
[category...] lists the scripts with every category (AND when several);
|
||||||
|
daedalus <category>... <name> [args...] runs a script that has every category.
|
||||||
```
|
```
|
||||||
|
|
||||||
- **3.9** The version is resolved in this order:
|
- **3.9** The version is resolved in this order:
|
||||||
@@ -187,39 +205,60 @@ usage: daedalus <name> [args...] run a script; args go to the
|
|||||||
- **3.9.2** `project.version` from `REPO_ROOT/pyproject.toml` (a
|
- **3.9.2** `project.version` from `REPO_ROOT/pyproject.toml` (a
|
||||||
checkout that is not installed).
|
checkout that is not installed).
|
||||||
- **3.9.3** The string `unknown`.
|
- **3.9.3** The string `unknown`.
|
||||||
- **3.10** Argument resolution. Options are recognized only as the first
|
- **3.10** Argument resolution. One `argparse.ArgumentParser`
|
||||||
token:
|
(`prog="daedalus"`, `allow_abbrev=False`, subclass whose `error()`
|
||||||
|
raises `UsageError` instead of exiting):
|
||||||
|
|
||||||
```text
|
```text
|
||||||
dispatch(argv):
|
parser arguments:
|
||||||
if argv is empty or argv[0] in ("-l", "--list"): list(all scripts); return 0
|
-l | --list store_true flag
|
||||||
if argv[0] in ("-h", "--help"): print usage; return 0
|
--version store_true flag
|
||||||
if argv[0] == "--version": print "daedalus " + version; return 0
|
--path <name>
|
||||||
if argv[0] == "--path":
|
words positional, nargs "*", metavar <category|name>
|
||||||
require exactly one more token, else usage error
|
script_args positional, argparse.REMAINDER, metavar [args ...]
|
||||||
print absolute path of lookup(argv[1]) # file need not exist
|
|
||||||
|
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: <message>" 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 <name>"
|
||||||
|
print absolute path of lookup(--path value) # file need not exist
|
||||||
return 0
|
return 0
|
||||||
if argv[0] starts with "-": usage error "unknown option"
|
prefix = leading words entries while is_category_label(entry)
|
||||||
prefix = leading tokens while is_category_label(token)
|
rest = remaining words entries
|
||||||
rest = remaining tokens
|
|
||||||
if prefix and rest is empty:
|
if prefix and rest is empty:
|
||||||
scripts = scripts having every label in prefix
|
scripts = scripts having every label in prefix
|
||||||
if none: usage error "no scripts for categories"
|
if none: usage error "no scripts for categories"
|
||||||
list(scripts); return 0
|
list(scripts); return 0
|
||||||
if prefix: script = lookup_in(prefix, rest[0]); return run(script, rest[1:])
|
if rest: script = lookup_in(prefix, rest[0]) when prefix else lookup(rest[0])
|
||||||
return run(lookup(argv[0]), argv[1:])
|
return run(script, rest[1:] + script_args)
|
||||||
|
|
||||||
main(argv = sys.argv[1:]):
|
|
||||||
try dispatch(argv)
|
|
||||||
on usage or runner error: print "daedalus: <message>" to stderr; return 2
|
|
||||||
```
|
```
|
||||||
|
|
||||||
- **3.11** Error messages (each printed as `daedalus: <message>`):
|
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 <name> --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: <message>` on stderr with exit code 2:
|
||||||
|
|
||||||
| Case | Message |
|
| Case | Message |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `--path` without exactly one name | `usage: daedalus --path <name>` |
|
| `--path` without a value | `argument --path: expected one argument` |
|
||||||
| Unknown option | `unknown option '<opt>'; run 'daedalus --help'` |
|
| `--path` with extra words | `usage: daedalus --path <name>` |
|
||||||
|
| Unknown option | `unrecognized arguments: <opt>` |
|
||||||
| Unknown script, close matches exist | `unknown script '<name>'; did you mean: <m1>, <m2>` |
|
| Unknown script, close matches exist | `unknown script '<name>'; did you mean: <m1>, <m2>` |
|
||||||
| Unknown script, no close match | `unknown script '<name>'; run 'daedalus --list'` |
|
| Unknown script, no close match | `unknown script '<name>'; run 'daedalus --list'` |
|
||||||
| Categories match no script | `no scripts for categories: <a>, <b>` |
|
| Categories match no script | `no scripts for categories: <a>, <b>` |
|
||||||
@@ -229,6 +268,45 @@ main(argv = sys.argv[1:]):
|
|||||||
- **3.12** Close matches are up to 3 names with similarity ratio at least
|
- **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
|
0.6 (Python `difflib.get_close_matches` defaults). After a category
|
||||||
prefix, only scripts in those categories are candidates.
|
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<TAB>` completes `hello`. Candidates are sorted.
|
||||||
|
- **3.13.4** `--path <name>` 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
|
## 4. Registry
|
||||||
|
|
||||||
@@ -380,6 +458,14 @@ SCRIPTS: dict[str, Script] = {
|
|||||||
- **6.7** Bump `version` in `pyproject.toml` and add a `CHANGELOG.md`
|
- **6.7** Bump `version` in `pyproject.toml` and add a `CHANGELOG.md`
|
||||||
entry.
|
entry.
|
||||||
- **6.8** Run `python autotest.py`. It must pass before pushing.
|
- **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 <category>... <name> -<TAB>` 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
|
## 7. Quality gates
|
||||||
|
|
||||||
@@ -445,7 +531,8 @@ autotest results
|
|||||||
`pip install -r requirements.txt`, then `python autotest.py`. The
|
`pip install -r requirements.txt`, then `python autotest.py`. The
|
||||||
sanity diff base is passed as `SANITY_DIFF_BASE`.
|
sanity diff base is passed as `SANITY_DIFF_BASE`.
|
||||||
- **7.11** `requirements.txt` holds the tools: `pytest`, `pytest-cov`,
|
- **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
|
## 8. Conventions
|
||||||
|
|
||||||
@@ -499,9 +586,11 @@ autotest results
|
|||||||
resolve to (section 10).
|
resolve to (section 10).
|
||||||
- **9.5** Tests under `*/tests/`, bytecode, and `.gitkeep` are not
|
- **9.5** Tests under `*/tests/`, bytecode, and `.gitkeep` are not
|
||||||
packaged.
|
packaged.
|
||||||
- **9.6** Runtime dependencies: none; the CLI uses only the standard
|
- **9.6** Runtime dependencies follow SPEC item 1.5 (reuse first): the
|
||||||
library. A script that needs third-party packages says so in its own
|
wheel declares `argcomplete >= 3` for shell completion (SPEC item
|
||||||
help text and fails with a clear message when they are missing;
|
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.
|
`DAEDALUS_PYTHON` (SPEC item 5.2) points it at their environment.
|
||||||
Test and lint tools stay in `requirements.txt`.
|
Test and lint tools stay in `requirements.txt`.
|
||||||
- **9.7** Tests build the wheel from a copy of the checkout and check:
|
- **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 |
|
| 16 | `run_python_script.py` and `daedalus_logging` (section 11) | Done |
|
||||||
| 17 | `daedalus.<folder>` imports in checkouts and installs (section 10) | Done |
|
| 17 | `daedalus.<folder>` imports in checkouts and installs (section 10) | Done |
|
||||||
| 18 | Listing table with version line, wrapped descriptions, and color (SPEC item 3.3) | 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 |
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# Run the daedalus CLI from this checkout without installing it.
|
# Run the daedalus CLI from this checkout without installing it.
|
||||||
|
# PYTHON_ARGCOMPLETE_OK
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
repo_root="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/.." && pwd)"
|
repo_root="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/.." && pwd)"
|
||||||
export PYTHONPATH="${repo_root}${PYTHONPATH:+:${PYTHONPATH}}"
|
export PYTHONPATH="${repo_root}${PYTHONPATH:+:${PYTHONPATH}}"
|
||||||
|
|||||||
+69
-25
@@ -1,9 +1,11 @@
|
|||||||
"""daedalus command line: list, locate, and run registered scripts.
|
"""daedalus command line: list, locate, and run registered scripts.
|
||||||
|
|
||||||
Entry point for ``daedalus <name> [args...]``; see SPEC.md section 3.
|
``daedalus <name> [args...]`` parsed with argparse; completion via
|
||||||
|
argcomplete; see SPEC.md section 3.
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
import difflib
|
import difflib
|
||||||
import importlib.metadata
|
import importlib.metadata
|
||||||
import os
|
import os
|
||||||
@@ -12,17 +14,25 @@ import sys
|
|||||||
import textwrap
|
import textwrap
|
||||||
import tomllib
|
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 REPO_ROOT
|
||||||
|
from daedalus import completions
|
||||||
from daedalus import registry
|
from daedalus import registry
|
||||||
from daedalus import runners
|
from daedalus import runners
|
||||||
|
|
||||||
USAGE = """usage: daedalus <name> [args...] run a script; args go to the script
|
USAGE = ("daedalus [-h] [-l | --list] [--version] [--path <name>] "
|
||||||
daedalus <category> [category...] list scripts (AND when multiple)
|
"[<category> ...] [<name> [args ...]]")
|
||||||
daedalus <category>… <name> [args...] run when script has every category
|
|
||||||
daedalus [-l | --list] list all registered scripts
|
PARSER_DESCRIPTION = "One CLI, many small scripts, each with tests (SPEC.md)."
|
||||||
daedalus --path <name> print the path of a script
|
|
||||||
daedalus --version print the installed version
|
PARSER_EPILOG = ("Forms: daedalus <name> [args...] runs a script; "
|
||||||
daedalus -h | --help show this help"""
|
"daedalus <category> [category...] lists the scripts with "
|
||||||
|
"every category (AND when several); daedalus <category>... "
|
||||||
|
"<name> [args...] runs a script that has every category.")
|
||||||
|
|
||||||
TYPE_COLUMN_MIN_WIDTH = 4
|
TYPE_COLUMN_MIN_WIDTH = 4
|
||||||
DESCRIPTION_INDENT = " " * 8
|
DESCRIPTION_INDENT = " " * 8
|
||||||
@@ -38,6 +48,35 @@ class UsageError(Exception):
|
|||||||
"""Bad daedalus arguments or an unknown script name."""
|
"""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="<name>",
|
||||||
|
help="print the path of a script")
|
||||||
|
words_action = parser.add_argument("words", metavar="<category|name>", 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:
|
def colors_enabled(stream=None) -> bool:
|
||||||
"""NO_COLOR unset/empty and (FORCE_COLOR or a terminal): SPEC item 3.3.6."""
|
"""NO_COLOR unset/empty and (FORCE_COLOR or a terminal): SPEC item 3.3.6."""
|
||||||
stream = sys.stdout if stream is None else stream
|
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}'")
|
raise UsageError(f"unknown script '{name}' for '{joined}'; run 'daedalus {joined}'")
|
||||||
|
|
||||||
|
|
||||||
def dispatch(argv: list[str]) -> int:
|
def dispatch(parsed: argparse.Namespace) -> int:
|
||||||
"""Handle daedalus options, categories, or run a script (SPEC item 3.10)."""
|
"""Handle the parsed daedalus arguments: options, lists, or run (SPEC item 3.10)."""
|
||||||
if not argv or argv[0] in ("-l", "--list"):
|
if parsed.list:
|
||||||
print(format_list(registry.SCRIPTS))
|
print(format_list(registry.SCRIPTS))
|
||||||
return 0
|
return 0
|
||||||
if argv[0] in ("-h", "--help"):
|
if parsed.version:
|
||||||
print(USAGE)
|
|
||||||
return 0
|
|
||||||
if argv[0] == "--version":
|
|
||||||
print(f"daedalus {version()}")
|
print(f"daedalus {version()}")
|
||||||
return 0
|
return 0
|
||||||
if argv[0] == "--path":
|
if parsed.path is not None:
|
||||||
if len(argv) != 2:
|
if parsed.words or parsed.script_args:
|
||||||
raise UsageError("usage: daedalus --path <name>")
|
raise UsageError("usage: daedalus --path <name>")
|
||||||
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
|
return 0
|
||||||
if argv[0].startswith("-"):
|
|
||||||
raise UsageError(f"unknown option {argv[0]!r}; run 'daedalus --help'")
|
|
||||||
prefix: list[str] = []
|
prefix: list[str] = []
|
||||||
rest = list(argv)
|
rest = list(parsed.words)
|
||||||
while rest and registry.is_category_label(rest[0]):
|
while rest and registry.is_category_label(rest[0]):
|
||||||
prefix.append(rest.pop(0))
|
prefix.append(rest.pop(0))
|
||||||
if prefix and not rest:
|
if prefix and not rest:
|
||||||
@@ -171,15 +208,22 @@ def dispatch(argv: list[str]) -> int:
|
|||||||
raise UsageError(f"no scripts for categories: {', '.join(prefix)}")
|
raise UsageError(f"no scripts for categories: {', '.join(prefix)}")
|
||||||
print(format_list(scripts))
|
print(format_list(scripts))
|
||||||
return 0
|
return 0
|
||||||
if prefix:
|
if rest:
|
||||||
return runners.run(lookup_in(prefix, rest[0]).absolute_path, rest[1:])
|
script = lookup_in(prefix, rest[0]) if prefix else lookup(rest[0])
|
||||||
return runners.run(lookup(rest[0]).absolute_path, rest[1:])
|
return runners.run(script.absolute_path, rest[1:] + parsed.script_args)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
def main(argv: list[str] | None = None) -> int:
|
def main(argv: list[str] | None = None) -> int:
|
||||||
"""CLI entry point; daedalus errors exit with 2 (SPEC item 3.10)."""
|
"""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:
|
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:
|
except (UsageError, runners.RunnerError) as error:
|
||||||
print(f"daedalus: {error}", file=sys.stderr)
|
print(f"daedalus: {error}", file=sys.stderr)
|
||||||
return 2
|
return 2
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -127,11 +127,15 @@ def test_list_no_color_wins(fake_registry, monkeypatch, capsys):
|
|||||||
|
|
||||||
@pytest.mark.parametrize("argv", [["-h"], ["--help"]])
|
@pytest.mark.parametrize("argv", [["-h"], ["--help"]])
|
||||||
def test_help(fake_registry, plain, capsys, argv):
|
def test_help(fake_registry, plain, capsys, argv):
|
||||||
"""--help prints the full usage with category forms (SPEC item 3.8)."""
|
"""-h/--help print the argparse rendering of the parser (SPEC item 3.8)."""
|
||||||
assert cli.main(argv) == 0
|
with pytest.raises(SystemExit) as caught:
|
||||||
|
cli.main(argv)
|
||||||
|
assert caught.value.code == 0
|
||||||
out = capsys.readouterr().out
|
out = capsys.readouterr().out
|
||||||
assert "daedalus <name> [args...]" in out
|
assert out.startswith("usage: daedalus")
|
||||||
assert "daedalus <category> [category...]" in out
|
assert "-l, --list" in out
|
||||||
|
assert "--path <name>" in out
|
||||||
|
assert "Forms: daedalus <name> [args...]" in out
|
||||||
|
|
||||||
|
|
||||||
def test_path(fake_registry, capsys):
|
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")
|
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 <name>" 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):
|
def test_version(monkeypatch, capsys, installed, expected):
|
||||||
"""--version uses metadata or pyproject.toml in a checkout."""
|
"""--version uses metadata or pyproject.toml in a checkout."""
|
||||||
def fake_version(_name):
|
def fake_version(_name):
|
||||||
@@ -154,8 +164,8 @@ def test_version(monkeypatch, capsys, installed, expected):
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("argv, message", [
|
@pytest.mark.parametrize("argv, message", [
|
||||||
(["--path"], "usage: daedalus --path"),
|
(["--path"], "argument --path: expected one argument"),
|
||||||
(["--bogus"], "unknown option '--bogus'; run 'daedalus --help'"),
|
(["--bogus"], "unrecognized arguments: --bogus"),
|
||||||
(["alpah"], "unknown script 'alpah'; did you mean: alpha"),
|
(["alpah"], "unknown script 'alpah'; did you mean: alpha"),
|
||||||
(["zzz"], "unknown script 'zzz'; run 'daedalus --list'"),
|
(["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"])]
|
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):
|
def test_runner_error_exits_2(fake_registry, plain, capsys):
|
||||||
"""A missing script file exits 2 instead of a traceback."""
|
"""A missing script file exits 2 instead of a traceback."""
|
||||||
assert cli.main(["alpha"]) == 2
|
assert cli.main(["alpha"]) == 2
|
||||||
@@ -287,3 +305,11 @@ def test_bash_launcher():
|
|||||||
launcher = str(REPO_ROOT / "bin" / "daedalus")
|
launcher = str(REPO_ROOT / "bin" / "daedalus")
|
||||||
assert run_cli("bash", launcher, "--list").returncode == 0
|
assert run_cli("bash", launcher, "--list").returncode == 0
|
||||||
assert run_cli("bash", launcher, "no_such_script").returncode == 2
|
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
|
||||||
|
|||||||
@@ -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<TAB> 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<TAB> completes hello through the argcomplete protocol."""
|
||||||
|
assert _candidates("daedalus h") == ["hello"]
|
||||||
|
|
||||||
|
|
||||||
|
@requires_argcomplete
|
||||||
|
def test_end_to_end_after_category_prefix():
|
||||||
|
"""daedalus test h<TAB> 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 <TAB> 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 -<TAB> 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 --<TAB> completes hello's --help through the prefix."""
|
||||||
|
assert _candidates("daedalus test hello --") == ["--help"]
|
||||||
+2
-2
@@ -4,11 +4,11 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "daedalus"
|
name = "daedalus"
|
||||||
version = "0.2.0"
|
version = "0.3.0"
|
||||||
description = "Template for daedalus: loose scripts in one repo, run with: daedalus <name> [args...]"
|
description = "Template for daedalus: loose scripts in one repo, run with: daedalus <name> [args...]"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.11"
|
requires-python = ">=3.11"
|
||||||
dependencies = []
|
dependencies = ["argcomplete>=3.3"]
|
||||||
|
|
||||||
[project.scripts]
|
[project.scripts]
|
||||||
daedalus = "daedalus.cli:main"
|
daedalus = "daedalus.cli:main"
|
||||||
|
|||||||
@@ -12,6 +12,11 @@ import pathlib
|
|||||||
import sys
|
import sys
|
||||||
import tomllib
|
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"
|
UNKNOWN = "unknown"
|
||||||
|
|
||||||
|
|
||||||
@@ -35,6 +40,8 @@ def main(argv: list[str] | None = None) -> int:
|
|||||||
"""Print ``hello from daedalus <version>``; return the exit code."""
|
"""Print ``hello from daedalus <version>``; return the exit code."""
|
||||||
parser = argparse.ArgumentParser(prog="hello",
|
parser = argparse.ArgumentParser(prog="hello",
|
||||||
description=__doc__.splitlines()[0])
|
description=__doc__.splitlines()[0])
|
||||||
|
if autocomplete is not None: # SPEC item 6.9
|
||||||
|
autocomplete(parser)
|
||||||
parser.parse_args(argv)
|
parser.parse_args(argv)
|
||||||
print(f"hello from daedalus {app_version()}")
|
print(f"hello from daedalus {app_version()}")
|
||||||
return 0
|
return 0
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ def test_app_version_falls_back_to_pyproject(monkeypatch):
|
|||||||
raise hello.importlib.metadata.PackageNotFoundError(_name)
|
raise hello.importlib.metadata.PackageNotFoundError(_name)
|
||||||
|
|
||||||
monkeypatch.setattr(hello.importlib.metadata, "version", not_found)
|
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):
|
def test_help_exits_zero(capsys):
|
||||||
|
|||||||
@@ -5,3 +5,4 @@ pymarkdownlnt>=0.9.20
|
|||||||
pyyaml>=6.0
|
pyyaml>=6.0
|
||||||
shellcheck-py>=0.10
|
shellcheck-py>=0.10
|
||||||
setuptools>=68
|
setuptools>=68
|
||||||
|
argcomplete>=3.3
|
||||||
|
|||||||
Reference in New Issue
Block a user