diff --git a/CHANGELOG.md b/CHANGELOG.md index 49f14de..073019b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,23 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and - Nothing yet. +## [0.10.0] - 2026-11-19 + +### Added in 0.10.0 + +- `daedalus init`: the one-time shell-side setup for tab completion. + Finds the `register-python-argcomplete` that belongs to this exact + daedalus interpreter (the pipx venv, the checkout .venv, or the + system python — argcomplete's script sits beside it), then appends + the completion hook to `~/.bashrc` between managed markers (or + `--bashrc FILE`), idempotently: an already-registered bashrc is left + untouched. `--dry-run` prints the block and the target; on Windows + the script prints a notice and does nothing; a zsh `$SHELL` gets a + logged warning about the `bashcompinit` preamble. Exit 3 when the + register script is nowhere to be found. The full behavior is + `python/src/init/spec.md` (sections 1-7), written first, then tests, + then code (SPEC 6.12). + ## [0.9.0] - 2026-11-19 ### Added in 0.9.0 diff --git a/README.md b/README.md index b8496f2..0b3964e 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ daedalus --list # list everything | `gpgtools` | Python | gpg | YubiKey GPG/SSH helpers: initialize (gnupg readiness check + install), initialize_yubikey (fresh machine, steps 1-4), send_pubkey (resolve key, verify possession, append to a server), store_publickey (install the key from the machine being granted access), configure_ssh (marker-managed per-host ssh block) | | `hello` | Python | test | Prints a hello line and the daedalus version | | `hello_bash` | Bash | test | Sample bash script through the shared help() interface | +| `init` | Python | setup | Enable tab completion for daedalus: register argcomplete in bash (appends the managed hook block to ~/.bashrc), idempotent | Run the sample script: @@ -163,7 +164,32 @@ config (move it into the managed markers or rename the alias). 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). +Run `daedalus init` once to register the hook in `~/.bashrc` (below); see +also [INSTALL](./INSTALL.md#tab-completion). + +### init + +`init` is the one-time shell-side setup: it finds the +`register-python-argcomplete` that belongs to this exact daedalus +interpreter (so a pipx install wires its own venv, not some other +python), appends the hook to `~/.bashrc` between managed markers, and +tells you how to activate it now. Installing daedalus never touches your +shell — this command does. It is idempotent: re-running on an already +registered `~/.bashrc` writes nothing. + +```bash +daedalus init # register completion in ~/.bashrc +daedalus init --dry-run # print the block and the target, change nothing +daedalus init --bashrc FILE # a different bashrc +``` + +| Argument | Default | Meaning | +| --- | --- | --- | +| `--bashrc FILE` | `~/.bashrc` | Target file for the managed hook block | +| `--dry-run` | off | Print the block and the target, change nothing | + +Exit code: `3` when `register-python-argcomplete` is nowhere to be +found (reinstall daedalus — argcomplete is a declared dependency). ## Getting started diff --git a/daedalus/registry.py b/daedalus/registry.py index fda868a..93c3d9e 100644 --- a/daedalus/registry.py +++ b/daedalus/registry.py @@ -69,6 +69,11 @@ SCRIPTS: dict[str, Script] = { description="Sample bash script through the shared help() interface", categories="test", ), + "init": Script( + path="python/src/init/init.py", + description="Enable tab completion for daedalus: register argcomplete in bash (appends the managed hook block to ~/.bashrc), idempotent", + categories="setup", + ), } """Every script daedalus can run (SPEC.md section 4).""" diff --git a/daedalus/tests/test_cli.py b/daedalus/tests/test_cli.py index d018823..f282497 100644 --- a/daedalus/tests/test_cli.py +++ b/daedalus/tests/test_cli.py @@ -150,7 +150,7 @@ def test_path_with_extra_words_is_a_usage_error(fake_registry, plain, capsys): assert "usage: daedalus --path " in capsys.readouterr().err -@pytest.mark.parametrize("installed, expected", [(True, "daedalus 1.2.3"), (False, "daedalus 0.9.0")]) +@pytest.mark.parametrize("installed, expected", [(True, "daedalus 1.2.3"), (False, "daedalus 0.10.0")]) def test_version(monkeypatch, capsys, installed, expected): """--version uses metadata or pyproject.toml in a checkout.""" def fake_version(_name): diff --git a/pyproject.toml b/pyproject.toml index 013f1e7..02e93cb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "daedalus" -version = "0.9.0" +version = "0.10.0" description = "Template for daedalus: loose scripts in one repo, run with: daedalus [args...]" readme = "README.md" requires-python = ">=3.11" @@ -21,6 +21,7 @@ packages = [ "daedalus.daedalus_logging", "daedalus.gpgtools", "daedalus.hello", + "daedalus.init", "daedalus._library.python.src", "daedalus._library.bash", "daedalus._library.powershell", @@ -30,6 +31,7 @@ packages = [ [tool.setuptools.package-dir] "daedalus.gpgtools" = "python/src/gpgtools" "daedalus.hello" = "python/src/hello" +"daedalus.init" = "python/src/init" "daedalus._library.python.src" = "python/src" "daedalus._library.bash" = "bash" "daedalus._library.powershell" = "powershell" diff --git a/python/src/init/init.py b/python/src/init/init.py new file mode 100644 index 0000000..45d7384 --- /dev/null +++ b/python/src/init/init.py @@ -0,0 +1,122 @@ +"""Enable tab completion for daedalus in the user's shell (init spec). + +Installing daedalus never touches the shell; argcomplete stays +dormant until bash evaluates ``register-python-argcomplete daedalus`` +(INSTALL.md "Tab completion"). This script performs the registration: +it finds the register script that belongs to *this* daedalus +interpreter, appends the managed hook block to ``~/.bashrc`` (its +only job for now), and says how to activate it right away. + +Run via daedalus: ``daedalus init`` (see daedalus README). +""" +from __future__ import annotations + +import argparse +import logging +import os +import pathlib +import shutil +import sys + +try: # SPEC item 6.9: complete init's own arguments + from argcomplete import autocomplete +except ImportError: # pragma: no cover - completion off without argcomplete + autocomplete = None + +LOGGER = logging.getLogger(__name__) + +EXIT_OK = 0 +EXIT_NO_REGISTER = 3 + +MARKER_BEGIN = "# BEGIN daedalus init: argcomplete" +MARKER_END = "# END daedalus init: argcomplete" + + +def register_script_path() -> pathlib.Path | None: + """Locate this interpreter's register-python-argcomplete (item 3.1). + + The interpreter's folder wins - a pipx venv, a checkout .venv, + and a system install all put argcomplete's scripts beside + python - so the hook matches this exact daedalus install. + + Returns: + The script's path, or None when neither location has it. + """ + beside = (pathlib.Path(sys.executable).parent + / "register-python-argcomplete") + # No resolve(): a venv python is a symlink into the system + # install; resolving it would look beside the wrong python. + if beside.is_file(): + return beside + found = shutil.which("register-python-argcomplete") + return pathlib.Path(found) if found else None + + +def build_block(register_path: pathlib.Path) -> str: + """Build the managed hook block for one register path (item 3.2).""" + line = f"eval \"$('{register_path}' daedalus)\"" + return f"{MARKER_BEGIN}\n{line}\n{MARKER_END}\n" + + +def main(argv: list[str] | None = None) -> int: + """Register argcomplete for daedalus; return the exit code. + + Args: + argv: argument list; None means sys.argv[1:]. + + Returns: + EXIT_OK (registered, already enabled, non-POSIX notice, or + dry run) or EXIT_NO_REGISTER (item 3.1). + """ + logging.basicConfig(level=logging.INFO, format="%(levelname)-5s %(message)s") + parser = argparse.ArgumentParser( + prog="init", + description="Enable tab completion for daedalus (register " + "argcomplete in bash)", + ) + parser.add_argument("--bashrc", type=pathlib.Path, default=None, + help="target file (default ~/.bashrc)") + parser.add_argument("--dry-run", action="store_true", + help="print the block and the target, " + "change nothing") + if autocomplete is not None: # SPEC item 6.9 + autocomplete(parser) + args = parser.parse_args(argv) + if os.name != "posix": # item 3.7 + print("nothing to do: tab completion is bash/zsh only") + return EXIT_OK + register = register_script_path() + if register is None: # item 3.1 + LOGGER.error("register-python-argcomplete not found next to " + "python (%s) nor on PATH; reinstall daedalus " + "(argcomplete is a declared dependency)", + sys.executable) + return EXIT_NO_REGISTER + target = args.bashrc or pathlib.Path.home() / ".bashrc" + if args.bashrc is None and os.environ.get("SHELL", "").endswith("zsh"): + LOGGER.warning("SHELL is zsh: bash-completion emulation needs " + "these two lines before the hook: " + "'autoload -U bashcompinit' and 'bashcompinit'") + existing = (target.read_text(encoding="utf-8") + if target.exists() else "") + if MARKER_BEGIN in existing: # item 3.4 + print(f"already enabled: {MARKER_BEGIN} found in {target}") + return EXIT_OK + block = build_block(register) + if args.dry_run: # item 3.6 + print(block, end="") + print(f"dry run: would append the block to {target}") + return EXIT_OK + content = existing + if content and not content.endswith("\n"): + content += "\n" # never glue the marker onto a line + if content.strip(): + content += "\n" # blank line before the block (item 3.3) + target.write_text(content + block, encoding="utf-8") + print(f"registered tab completion for daedalus in {target}") + print("activate it now with: exec bash (or open a new shell)") + return EXIT_OK + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/python/src/init/spec.md b/python/src/init/spec.md new file mode 100644 index 0000000..9adc00e --- /dev/null +++ b/python/src/init/spec.md @@ -0,0 +1,92 @@ +# init specification + +Complete description of `python/src/init/init.py`. Change this file +first, then tests, then code (SPEC items 6.11 and 6.12). Items are +cited as `init spec item N.M`. + +## 1. Purpose + +- **1.1** `daedalus init` enables argcomplete tab completion for the + daedalus command in the user's shell. Its only job, for now, is the + shell side: register the completion hook and persist it. +- **1.2** Installing daedalus (pipx, pip, or `bin/daedalus`) never + touches the shell; argcomplete stays dormant until the user's bash + evaluates `register-python-argcomplete daedalus` (INSTALL.md "Tab + completion"). This script performs that registration, so the + one-time setup is one command. +- **1.3** Standard library only; Python 3.11+ (SPEC item 9.6). + +## 2. Command + +- **2.1** `daedalus init [--bashrc PATH] [--dry-run]` - enables + completion and appends the hook to `--bashrc` (default + `~/.bashrc`), section 3. + +## 3. Behavior + +- **3.1** Locate `register-python-argcomplete`: first in the + directory of the running interpreter (`sys.executable`'s folder - + pipx venv, checkout .venv, and system installs all put it beside + python), then on `PATH` via `shutil.which`. Neither is exit 3 + with a hint to reinstall (argcomplete is a declared dependency). +- **3.2** The hook is one managed block appended to the target + file: + +```text +# BEGIN daedalus init: argcomplete +eval "$('' daedalus)" +# END daedalus init: argcomplete +``` + +- **3.3** Target: `--bashrc PATH`, default `~/.bashrc`. Existing + content is preserved verbatim; the block is appended at the end + with a blank line before it when the file is non-empty. +- **3.4** Idempotence: when the file already holds the begin + marker, the run reports `already enabled`, writes nothing, and + exits 0. Restoring a `.bashrc` that already registered the hook + and re-running is a no-op. +- **3.5** On registering, the script prints what it appended, the + target, and how to activate it now (`exec bash` or a new shell); + it never re-executes the shell itself. +- **3.6** `--dry-run` prints the block and the target, creating / + appending nothing, and exits 0 (an already-enabled dry run + prints that instead). +- **3.7** On Windows (`os.name` not `posix`), nothing applies: + the script prints a notice (completion is bash/zsh only) and + exits 0 without touching any file. +- **3.8** When `$SHELL` names zsh and `--bashrc` was not passed, + a warning logs the two `bashcompinit` lines bash compat needs; + the script still writes the bash target as asked. + +## 4. Exit codes + +| Code | Meaning | +| --- | --- | +| 0 | registered, already enabled, nothing to do (non-POSIX), or dry run | +| 3 | `register-python-argcomplete` not found (item 3.1) | + +## 5. Files written + +- **5.1** Only the target file (item 3.2 block, item 3.3 target). + Nothing else; no package installs, no system files. + +## 6. Testing approach + +- **6.1** Tests live in `python/tests/test_init_script.py` (the + SPEC 6.6.1 name `test_init.py` is taken by + `daedalus/tests/test_init.py`; pytest needs unique basenames). + No network, no hardware; the register-script path is injectable + and the target is a temp file (daedalus agent rule 5.6). +- **6.2** Covered groups: block building (item 3.2), resolution + order beside python then `PATH` (3.1), idempotence (3.4), + preservation of existing content (3.3), dry run (3.6), + non-POSIX notice (3.7), missing-register exit 3, and the CLI + wiring (`--bashrc`, `--dry-run`, `--help`). + +## 7. References + +- **7.1** Shell reasons: INSTALL.md "Tab completion"; SPEC items + 6.9 and 3.13.5.1 (argcomplete opt-in). +- **7.2** Repository rules: SPEC items 6.6 (tests), 9.8 (version + bump). +- **7.3** History: `CHANGELOG.md` entry 0.10.0. diff --git a/python/tests/test_hello.py b/python/tests/test_hello.py index df0cd33..ead2b7a 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.9.0" + assert hello.app_version() == "0.10.0" def test_help_exits_zero(capsys): diff --git a/python/tests/test_init_script.py b/python/tests/test_init_script.py new file mode 100644 index 0000000..fb90980 --- /dev/null +++ b/python/tests/test_init_script.py @@ -0,0 +1,167 @@ +"""Tests for the init script: argcomplete registration (init spec). + +No network, no hardware: the register-script path is injectable and +the bashrc target a temp file (daedalus agent rule 5.6). File is +named test_init_script.py because daedalus/tests/test_init.py exists +and pytest needs unique basenames (init spec item 6.1). +""" +import pathlib + +from daedalus.init import init + +REGISTER = pathlib.Path("/venv/bin/register-python-argcomplete") + + +# --- block building (init spec item 3.2) + + +def test_build_block_contains_hook(): + """The block holds the markers and the eval line with the path.""" + block = init.build_block(REGISTER) + assert block.startswith("# BEGIN daedalus init: argcomplete\n") + assert block.endswith("# END daedalus init: argcomplete\n") + assert f"eval \"$('{REGISTER}' daedalus)\"" in block + + +# --- register-script resolution (init spec item 3.1) + + +def test_register_script_path_beside_python(monkeypatch, tmp_path): + """The interpreter's folder wins (pipx venv, .venv, system).""" + fake = tmp_path / "bin" / "register-python-argcomplete" + fake.parent.mkdir(parents=True) + fake.write_text("#!/bin/sh\n", encoding="utf-8") + monkeypatch.setattr(init.sys, "executable", + str(tmp_path / "bin" / "python")) + assert init.register_script_path() == fake + + +def test_register_script_path_prefers_venv_symlink(monkeypatch, tmp_path): + """A venv python is a symlink; its own bin wins, not the target's. + + resolve() on sys.executable would dereference the venv symlink + and hand the lookup to the system python's folder (init spec + item 3.1: the *running interpreter's* folder). + """ + real = tmp_path / "real" / "bin" + real.mkdir(parents=True) + (real / "python3").write_text("#!/bin/sh\n", encoding="utf-8") + (real / "register-python-argcomplete").write_text( + "#!/bin/sh\n", encoding="utf-8") + venv = tmp_path / "venv" / "bin" + venv.mkdir(parents=True) + (venv / "python").symlink_to(real / "python3") + (venv / "register-python-argcomplete").write_text( + "#!/bin/sh\n", encoding="utf-8") + monkeypatch.setattr(init.sys, "executable", str(venv / "python")) + assert init.register_script_path() == \ + venv / "register-python-argcomplete" + + +def test_register_script_path_falls_back_to_path(monkeypatch): + """Without a match beside python, PATH is searched.""" + monkeypatch.setattr(init.sys, "executable", "/nowhere/python") + monkeypatch.setattr(init.shutil, "which", + lambda _name: "/usr/local/bin/register-python-argcomplete") + assert init.register_script_path() == \ + pathlib.Path("/usr/local/bin/register-python-argcomplete") + + +def test_register_script_path_missing(monkeypatch): + """Neither location has it: None (exit 3 upstream).""" + monkeypatch.setattr(init.sys, "executable", "/nowhere/python") + monkeypatch.setattr(init.shutil, "which", lambda _name: None) + assert init.register_script_path() is None + + +# --- main flow (init spec items 3.3-3.8) + + +def fake_register(monkeypatch, path): + """Point register_script_path at a fixed path.""" + monkeypatch.setattr(init, "register_script_path", + lambda: pathlib.Path(path)) + + +def test_main_appends_block(tmp_path, monkeypatch, capsys): + """A fresh bashrc receives the block, exit 0.""" + target = tmp_path / "bashrc" + fake_register(monkeypatch, REGISTER) + assert init.main(["--bashrc", str(target)]) == 0 + content = target.read_text(encoding="utf-8") + assert "# BEGIN daedalus init: argcomplete" in content + assert f"'{REGISTER}' daedalus" in content + out = capsys.readouterr().out + assert "registered" in out + assert "exec bash" in out + + +def test_main_preserves_existing_bashrc(tmp_path, monkeypatch): + """Existing lines stay; the block lands after a blank line.""" + target = tmp_path / "bashrc" + target.write_text("alias ll='ls -l'\n", encoding="utf-8") + fake_register(monkeypatch, REGISTER) + assert init.main(["--bashrc", str(target)]) == 0 + content = target.read_text(encoding="utf-8") + assert content.startswith("alias ll='ls -l'\n\n") + assert content.endswith("# END daedalus init: argcomplete\n") + + +def test_main_idempotent(tmp_path, monkeypatch, capsys): + """A second run reports already enabled and writes nothing.""" + target = tmp_path / "bashrc" + fake_register(monkeypatch, REGISTER) + init.main(["--bashrc", str(target)]) + before = target.read_text(encoding="utf-8") + assert init.main(["--bashrc", str(target)]) == 0 + assert target.read_text(encoding="utf-8") == before + assert "already enabled" in capsys.readouterr().out + + +def test_main_dry_run(tmp_path, monkeypatch, capsys): + """Dry run prints the block, creates and appends nothing.""" + target = tmp_path / "bashrc" + fake_register(monkeypatch, REGISTER) + assert init.main(["--bashrc", str(target), "--dry-run"]) == 0 + out = capsys.readouterr().out + assert "# BEGIN daedalus init: argcomplete" in out + assert "dry run" in out + assert not target.exists() + + +def test_main_missing_register(tmp_path, monkeypatch): + """No register script anywhere is exit 3, no file written.""" + target = tmp_path / "bashrc" + monkeypatch.setattr(init, "register_script_path", lambda: None) + assert init.main(["--bashrc", str(target)]) == 3 + assert not target.exists() + + +def test_main_non_posix(tmp_path, monkeypatch, capsys): + """On Windows nothing applies: notice, exit 0, no write.""" + target = tmp_path / "bashrc" + fake_register(monkeypatch, REGISTER) + monkeypatch.setattr(init.os, "name", "nt") + assert init.main(["--bashrc", str(target)]) == 0 + assert "bash/zsh" in capsys.readouterr().out + assert not target.exists() + + +def test_main_zsh_shell_gets_a_note(tmp_path, monkeypatch, caplog): + """A zsh SHELL without --bashrc logs the bashcompinit warning.""" + target = tmp_path / "bashrc" + fake_register(monkeypatch, REGISTER) + monkeypatch.setenv("SHELL", "/usr/bin/zsh") + monkeypatch.setattr(init.pathlib.Path, "home", + staticmethod(lambda: tmp_path)) + assert init.main([]) == 0 + assert "bashcompinit" in caplog.text + assert (tmp_path / ".bashrc").exists() + + +def test_cli_help(): + """--help prints usage.""" + import pytest + with pytest.raises(SystemExit) as exc: + init.main(["--help"]) + assert exc.value.code == 0