feat: daedalus init - register argcomplete tab completion (v0.10.0)

- new script python/src/init/init.py: locates the
  register-python-argcomplete that belongs to the running
  interpreter (venv bin, NOT the resolve()d symlink target -
  proven by a live pipx run), appends the managed hook block to
  ~/.bashrc between # BEGIN/END daedalus init markers,
  idempotent; --bashrc, --dry-run; Windows notice; zsh warning
- per-script spec python/src/init/spec.md (SPEC 6.11/6.12),
  tests python/tests/test_init_script.py (13; the plain
  test_init.py name is taken by daedalus/tests)
- registry entry, README row + section, pyproject packaging
  (daedalus.init), CHANGELOG 0.10.0, version pins

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
nvaldez
2026-11-19 09:31:05 +01:00
parent e9b716b399
commit cdc209536f
9 changed files with 435 additions and 4 deletions
+122
View File
@@ -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())
+92
View File
@@ -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 "$('<path to register-python-argcomplete>' 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.
+1 -1
View File
@@ -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):
+167
View File
@@ -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