10 Commits

Author SHA1 Message Date
nvaldez aa813f0c89 fix: README repo-relative links 404 on PyPI (v0.13.1)
PyPI renders the README alone; ./INSTALL.md, ./SPEC.md and
./CHANGELOG.md have nothing to resolve against. Links now point
at the public Gitea repository (anchors kept). 0.13.0's page is
immutable and keeps its broken links; the project page shows the
newest release's README. Found by the owner on the 0.13.0 page.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-11-19 11:06:27 +01:00
nvaldez bd1a10487c feat: PyPI distribution renamed daedalus-tools; PEP 625 artifact names (v0.13.0)
PyPI policy-blocks the plain name: the 0.12.1 upload was rejected
with "The name 'daedalus' isn't allowed" (near the existing
daedalus-cli and pydaedalus projects). The distribution is now
daedalus-tools; command, imports, registry, and the repository
name stay daedalus. hello's installed-version lookup follows.
publish now derives artifact file names from the PEP 625
normalized name (daedalus_tools-<version>.tar.gz) - with a
hyphenated project name the previously constructed names would
have missed what setuptools writes to dist/ (publish spec 3.2,
new regression test).

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-11-19 10:58:33 +01:00
nvaldez 6145ae33e8 fix: publish tag guard - v<version> must be among git tag --points-at (v0.12.1)
The first live run of daedalus publish on the v0.12.0 release was
rejected by its own tag guard: git describe --exact-match returns
whichever name git picks (here: latest), not the version tag, when
several tags share the release commit. The guard now checks that
v<version> is among git tag --points-at HEAD; moving tags on the
same commit are fine (publish spec 3.3.2, reproduced by a new test).

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-11-19 10:33:56 +01:00
nvaldez 7ebce2109e feat: daedalus publish - guarded PyPI release (v0.12.0)
- new script python/src/publish/publish.py: guards (clean tree,
  HEAD exactly tagged v<version>, version not yet on PyPI,
  build+twine present), then the chained python -m build (the
  sdist must rebuild the wheel, SPEC 9.2.1) and twine check;
  --upload sends exactly this version's sdist+wheel, credentials
  stay with twine (~/.pypirc or prompt, __token__)
- spec python/src/publish/spec.md (sections 1-7) first, then
  tests (13) in python/tests/test_publish.py, then code
  (SPEC 6.12)
- fix release-blocking sdist defect (SPEC 9.2.1): empty
  powershell/ and batch/ folders now carry README placeholders
  and MANIFEST.in ships them, so an sdist installs again
- release tooling in requirements.txt; registry entry, README
  row + section, CHANGELOG 0.12.0, version pins

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-11-19 10:27:57 +01:00
nvaldez 41c8b99bd6 feat: gpgtools ssh-config-summary - per-host table of gpg-enabled logins (v0.11.0)
- read-only: one row per marker-managed block in ~/.ssh/config (or
  --config PATH): alias, hostname, user, key id (first 8 chars of
  the identity's SHA256 fingerprint via ssh-keygen -lf, material
  digest as fallback), and the fallback identity's name
- no managed blocks / missing config: fact + configure_ssh hint,
  exit 0 always (read-only command)
- spec items 2.8 + section 13 first, then tests, then code (SPEC
  6.12); 10 new tests (100 in test_gpgtools.py), registry
  description, README section, CHANGELOG 0.11.0, version pins

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-11-19 09:49:35 +01:00
nvaldez cdc209536f 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>
2026-11-19 09:31:05 +01:00
nvaldez e9b716b399 feat: gpgtools configure_ssh, store_publickey, --file source, initialize (v0.7.0-v0.9.0)
- configure_ssh (0.7.0): marker-managed per-host ssh client block in
  ~/.ssh/config, idempotent, unmanaged-alias guard (exit 11)
- store_publickey (0.8.0): on-site bootstrap mirror of send_pubkey -
  run on the machine access is granted to, installs the key into the
  local authorized_keys (multi-key preserving, material dedup, 700/600,
  no possession check by design); shared --file PATH source (USB
  stick) for both store subcommands; identity block printed before
  acting (line, source, SHA-256 material digest)
- initialize (0.9.0): gnupg readiness check + install, no card
  expectations; --dry-run; initialize_yubikey step 1 shares the flow
- spec-first per SPEC 6.11/6.12: gpgtools spec.md items 2.6/2.7,
  4.1.5, 4.8, sections 10-12; 91 tests in test_gpgtools.py;
  README/registry/CHANGELOG/version pins through 0.9.0

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-11-19 08:57:30 +01:00
nvaldez 85e8342a74 docs: per-script local specs + spec-first change order (SPEC 6.11, 6.12)
Every script gets a complete spec.md sectionized like SPEC.md
(python/src/<name>/spec.md, <name>.spec.md for shell scripts).
Change order becomes spec -> tests -> code. Specs added for
gpgtools, hello, hello_bash; CHANGELOG under Unreleased.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-11-19 00:54:03 +01:00
nvaldez fef68a84c9 feat: gpgtools - YubiKey GPG/SSH helpers (v0.6.0)
initialize_yubikey (guide steps 1-4): gnupg install fallback
(apt-get/dnf/pacman), card check, public-key fetch from the
card's URL field, idempotent gpg-agent SSH config merge,
GNUPGHOME chmod 700; --dry-run, --gnupg-home.

send_pubkey (guide steps 5-6): resolve the SSH public key from
four sources (--yubikey via gpg-agent ssh socket, --url, --fingerprint via store chain local keyring -> keys.openpgp.org
-> keyserver.ubuntu.com with fingerprint checking, --pubkey
literal), prove possession of the private half with a random
challenge signature (ssh-keygen -Y sign -U / verify) before
anything is stored, then append idempotently to the target's
authorized_keys (dedup by key material, comments ignored).
--no-verify opts out explicitly; --dry-run resolves only.

51 tests (flow via injected runner: no hardware, network, or
interactive terminal); steps 1-6 of the wiki guide
(yubikey-ssh-guide.md) are now one command each.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-11-19 00:46:40 +01:00
hermes-pi ec9848b169 daedalus 0.4.0: bash script interface (help() dispatch) + hello_bash
- bash/daedalus_common.sh (new): the shared interface for bash scripts
  (SPEC item 6.10) - a script sources its sibling helper, defines help()
  (usage) and main(), and ends with daedalus_bash_dispatch "$@" which
  routes help/-h/--help to help() and everything else to main()
  unchanged (clear fallback errors when a script forgets either)
- completion for bash scripts (SPEC item 3.13.5.2): after a completed
  script name daedalus offers --help, -h, help, prefix-filtered, written
  itself on the fd-8 argcomplete protocol - no script runs on TAB;
  scripts without the interface get the shell default
- bash/hello_bash.sh (new, category test): sample script through the
  interface, the bash twin of hello, with tests; registry entry, README
  row, CHANGELOG bullet
- tests: bash/tests/test_bash_interface.py (helper behavior, bash -n,
  enforcement of the interface for every registered .sh),
  test_hello_bash.py (direct and daedalus runs, help routing, SPEC 3.1
  pass-through, completion probes including the user's
  daedalus hello_bash<TAB><TAB> case), completions units + e2e harness
- README/INSTALL/SPEC updated (6.10, 3.13.5.2, tree, boilerplate with
  shellcheck directive); autotest green (212 tests)

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-11-18 22:35:11 +01:00
30 changed files with 4918 additions and 39 deletions
+215
View File
@@ -10,6 +10,221 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and
- Nothing yet.
## [0.13.1] - 2026-11-19
### Fixed in 0.13.1
- The PyPI README's repo-relative links (`./INSTALL.md`,
`./SPEC.md`, `./CHANGELOG.md`) 404 on pypi.org - the package
metadata holds only the README itself. They now point at the
public Gitea repository
(`https://gitea.nolivaldeziii.com/nvaldez/daedalus/src/branch/main/...`)
with their anchors kept. 0.13.0's already-published page keeps
its broken links (PyPI metadata is immutable); the project page
shows the newest release's README. Found by the owner on the
0.13.0 page.
## [0.13.0] - 2026-11-19
### Changed in 0.13.0
- PyPI distribution renamed to **`daedalus-tools`** (from `daedalus`):
PyPI policy-blocks the plain name - the upload of 0.12.1 was rejected
with "The name 'daedalus' isn't allowed" (near the existing
`daedalus-cli` and `pydaedalus` projects). The `daedalus` command, the
`daedalus` import package, the registry, and the repository are
unchanged; only the value of `[project] name` (and hello's installed
version lookup) moved. `pipx install daedalus-tools` puts the same
`daedalus` CLI on PATH (SPEC item 9.1).
### Fixed in 0.13.0
- `publish`'s artifact names now use the PEP 625 normalized name
(`daedalus-tools` -> `daedalus_tools-0.13.0.tar.gz`), matching what
setuptools actually writes to `dist/`; with a hyphenated project name
the constructed names would have missed the files. PyPI's version
probe keeps using the project name as written (publish spec 3.2).
## [0.12.1] - 2026-11-19
### Fixed in 0.12.1
- `publish`'s tag guard rejected a correctly tagged release when
`latest` (or any other tag) shared the release commit: `git describe
--tags --exact-match` returns whichever name git picks, not the
version tag. The guard now checks that `v<version>` is among
`git tag --points-at HEAD` (membership check, publish spec item
3.3.2); moving tags on the same commit are fine. Found by the first
live run of `daedalus publish` on the v0.12.0 release.
## [0.12.0] - 2026-11-19
### Added in 0.12.0
- `daedalus publish`: a guarded one-command PyPI release. Checks the
working tree is clean, HEAD exactly tagged `v<version>`, the version
not yet on PyPI (immutable once published), and `build` + `twine`
present in the running interpreter — then runs the **chained**
`python -m build` (the sdist must rebuild the wheel) and
`twine check`. `--upload` hands exactly this version's sdist and
wheel to twine; credentials stay with twine (`~/.pypirc` or the
prompt, `__token__`). Spec `python/src/publish/spec.md` first, then
tests, then code (SPEC 6.12).
- Release tooling (`build`, `twine`) added to `requirements.txt`.
### Fixed in 0.12.0
- **Release-blocking sdist defect:** the sdist could not rebuild its
wheel (`package directory 'powershell' does not exist`) — the empty
`powershell/`/`batch/` folders were declared in packaging but never
shipped, so installing from an sdist of 0.11.0 failed. Empty script
folders now carry a `README.md` placeholder and `MANIFEST.in` ships
them (SPEC item 9.2.1). The chained build in `publish` keeps this
from recurring.
## [0.11.0] - 2026-11-19
### Added in 0.11.0
- `gpgtools ssh-config-summary`: a read-only view of the gpg-enabled ssh
logins. One row per marker-managed block in `~/.ssh/config` (or
`--config FILE`): alias, hostname, user, the key id - first 8 chars of the
identity's SHA256 fingerprint via `ssh-keygen -lf`, with the SHA-256
material digest as fallback when ssh-keygen is unavailable - and the
fallback identity's name. No managed blocks (or a missing config) prints
that fact with the `configure_ssh` hint. Exit code always 0. Spec item 2.8
and section 13 written first, then tests, then code (SPEC 6.12).
## [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
- `gpgtools initialize`: checks that gnupg is ready on this machine
(`gpg --version`) and installs what is missing — the gnupg-only
half of `initialize_yubikey`, with no card expectations. Missing gpg
triggers the same manager detection and sudo install; the check
re-runs once after a successful install. `--dry-run` prints
`already ready` or the install command and changes nothing. Intended
as the on-site companion to `store_publickey --fingerprint` on a
bare server. Spec section 12 written first, then tests, then code
(SPEC 6.12); `initialize_yubikey` step 1 now runs the same shared
flow instead of its own inline copy.
## [0.8.0] - 2026-11-19
### Added in 0.8.0
- `gpgtools store_publickey`: the on-site bootstrap mirror of
`send_pubkey`. Run on the machine that access is being granted
**to** (a server with ssh password authentication disabled, no key
there yet, you at its console), it resolves one SSH public key and
appends it to this machine's `authorized_keys` — so the machine
holding the YubiKey can ssh in afterwards. Same five sources as
`send_pubkey`; by design there is no proof-of-possession (the
private half is elsewhere). Existing entries preserved verbatim,
idempotent by key material, `~/.ssh`/file modes forced to 700/600,
`--authorized-keys` override, `--dry-run`. Spec section 11 written
first, then tests, then code (SPEC 6.12).
- New shared source `--file PATH` for both `send_pubkey` and
`store_publickey`: a file holding the SSH public key line,
typically `yubikey_auth.pub` carried on a USB stick — no network,
no gpg needed. Several keys in one file refuse rather than guess.
- Both resolve-and-store subcommands now print an identity block (key
line, source, and the key material's SHA-256 digest) before acting,
so what was resolved can be compared across machines.
## [0.7.0] - 2026-11-19
### Added in 0.7.0
- `gpgtools configure_ssh` (guide step 7): writes a marker-managed
`Host <alias>` block into the ssh client config — YubiKey identity
first, fallback identity only when it exists, `IdentitiesOnly yes`.
Idempotent (re-runs replace the block; everything outside the
markers is preserved), `--dry-run`, and a guard that refuses when an
unmanaged `Host` with the same alias would shadow the block. Spec
items 2.5 and 10 written first, then tests, then code (SPEC 6.12).
- Per-script local specs (SPEC items 6.11, 6.12): every script gets a
spec that completely describes it — `spec.md` in a Python script's
folder, `<name>.spec.md` beside bash/PowerShell/batch scripts — in
the sectionized format of SPEC.md. Script work is spec first, then
tests, then code. First specs added:
`gpgtools`, `hello`, `hello_bash`.
### Fixed in 0.7.0
- Test fixtures no longer carry private values: the real server IP,
host alias, card serial, and public key fingerprint were replaced
with documentation-range placeholders.
## [0.6.0] - 2026-11-18
### Added in 0.6.0
- `gpgtools send_pubkey` (guide steps 5-6): resolves an SSH public key
from one of four sources — `--yubikey` (gpg-agent ssh socket),
`--url` (armored OpenPGP key, converted with `gpg --export-ssh-key`
in a throwaway GNUPGHOME), `--fingerprint` (store chain: local
keyring, keys.openpgp.org VKS, keyserver.ubuntu.com, each
fingerprint-checked), or `--pubkey` (literal line, format-validated).
Before anything is stored, proof of possession: a random challenge is
signed by the private half through the agent (`ssh-keygen -Y sign
-U`; PIN prompts reach the user) and verified against the candidate
line (`ssh-keygen -Y verify`). Only then is the line appended to the
target's `authorized_keys` — idempotent (grep before append), perms
enforced. `--no-verify` skips the check explicitly; `--dry-run`
resolves and prints without side effects. 22 new tests.
## [0.5.0] - 2026-11-18
### Added in 0.5.0
- `gpgtools` (Python, category `gpg`): YubiKey GPG/SSH helpers.
`daedalus gpgtools initialize_yubikey` runs the fresh-machine flow
(steps 1-4 of the wiki guide): installs gnupg when missing (apt-get,
dnf, pacman), checks the card, fetches the public key from the card's
URL field with `gpg --fetch-keys`, and writes the gpg-agent SSH
config (`enable-ssh-support`, cache TTLs) with the GNUPGHOME
directory at mode 700. `--dry-run` prints the plan; steps 5-7
(derive and deploy the SSH key per host) are server-specific and
intentionally out of scope.
## [0.4.0] - 2026-11-18
### Added in 0.4.0
- `bash/daedalus_common.sh`: the shared interface for bash scripts (SPEC
item 6.10) — a script sources its sibling helper, defines `help()`
(usage) and `main()`, and ends with `daedalus_bash_dispatch "$@"`,
which routes `help` / `-h` / `--help` to `help()` and everything else
to `main()` unchanged.
- Bash script completion (SPEC item 3.13.5.2): `daedalus <name> <TAB>`
completes `--help`, `-h`, and `help` for scripts implementing the
interface; no script runs on TAB. Scripts without the interface get
the shell default.
- `bash/hello_bash.sh`: sample bash script (category `test`) through the
shared interface, the bash twin of `hello`, with tests.
- `bash/tests/`: the interface tests — helper behavior through a
sample script and enforcement of the interface for every registered
`.sh` script.
## [0.3.0] - 2026-11-18
### Added in 0.3.0
+11 -8
View File
@@ -17,23 +17,21 @@ Back to the [script list](./README.md#available-scripts). Repository rules:
### With pipx (recommended)
[pipx](https://pipx.pypa.io/) installs daedalus into its own environment
and puts the `daedalus` command on `PATH`.
[pipx](https://pipx.pypa.io/) installs the `daedalus-tools` distribution
(from PyPI or Git) into its own environment and puts the `daedalus`
command on `PATH` — the project name and the command differ on purpose
(plain `daedalus` is policy-blocked on PyPI; see SPEC item 9.1).
Linux (Debian 12): paste once; open a new shell if `pipx` was just
installed. Run the same block again to refresh from Git (`main`); do **not**
use `pipx upgrade daedalus` for Git installs — it does not pull the repo.
use `pipx upgrade daedalus-tools` for Git installs — it does not pull the repo.
```bash
daedalus_pipx_install() {
r="${1:-git+ssh://git@example.com/your-org/daedalus.git@main}"
command -v pipx >/dev/null || sudo apt install -y pipx
pipx ensurepath 2>/dev/null || pipx ensurepath --force
if pipx list --short 2>/dev/null | grep -qE '^daedalus '; then
pipx install --force "$r"
else
pipx install "$r"
fi
pipx install --force "$r"
daedalus --version
}; daedalus_pipx_install
```
@@ -157,6 +155,11 @@ Notes:
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.
- Bash scripts share `bash/daedalus_common.sh` (SPEC item 6.10): the
script sources it, defines `help()` and `main()`, and ends with
`daedalus_bash_dispatch "$@"`. After the script name, TAB offers
`--help`, `-h`, and `help`; running one of them prints the script's
`help()`.
- 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).
+5
View File
@@ -0,0 +1,5 @@
# Ship the declared script folders even while they hold only
# README placeholders, so every sdist can rebuild its wheel
# (SPEC item 9.2.1). File types are filtered per 9.2 on install.
recursive-include powershell *
recursive-include batch *
+198 -6
View File
@@ -9,20 +9,26 @@ daedalus <category> [category...] # list scripts in the categories (AND)
daedalus --list # list everything
```
**[Install, usage, and development](./INSTALL.md)** ·
[SPEC](./SPEC.md) (how the repo is maintained) ·
[CHANGELOG](./CHANGELOG.md)
**[Install, usage, and development](https://gitea.nolivaldeziii.com/nvaldez/daedalus/src/branch/main/INSTALL.md)** ·
[SPEC](https://gitea.nolivaldeziii.com/nvaldez/daedalus/src/branch/main/SPEC.md) (how the repo is maintained) ·
[CHANGELOG](https://gitea.nolivaldeziii.com/nvaldez/daedalus/src/branch/main/CHANGELOG.md)
## Available scripts
| Script | Type | Categories | What it does |
| --- | --- | --- | --- |
| `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 |
| `publish` | Python | release | Release daedalus to PyPI: guarded chained build (clean tree, exact `v<version>` tag, PyPI-free version, tooling), twine check, `--upload` (credentials stay with twine) |
Run the sample script:
```bash
daedalus hello # hello from daedalus 0.3.0
daedalus hello # hello from daedalus 0.4.0
daedalus hello_bash me # hello, me (from daedalus bash)
daedalus hello_bash -h # usage from hello_bash's help()
daedalus test hello # same, through the category prefix
daedalus test # list the scripts in the 'test' category
```
@@ -30,18 +36,204 @@ daedalus test # list the scripts in the 'test' category
`daedalus --list` prints the version, a `script` / `type` / `categories`
table, and each description wrapped under each row.
### gpgtools
`initialize` checks that gnupg is ready on this machine and installs
what is missing — the gnupg-only half of `initialize_yubikey`, with no
card expectations. Its use is on-site: on a bare server where you are
about to run `store_publickey --fingerprint`, this is the command that
makes the gpg-dependent sources work.
```bash
daedalus gpgtools initialize # check gnupg, install when missing
daedalus gpgtools initialize --dry-run # already ready, or the install command
```
| Argument | Default | Meaning |
| --- | --- | --- |
| `--dry-run` | off | Print what would happen (already ready or the install command); change nothing |
Exit codes: `0` gnupg ready (installed or already present), `2` package
install failed or gpg still unusable after it, `3` gpg missing and no
known package manager.
`initialize_yubikey` runs the fresh-machine flow for YubiKey-backed
GPG and SSH (steps 1-4 of the wiki guide): install gnupg when missing,
check the card, fetch the public key from the card's URL field, and
write the gpg-agent SSH config. Steps 5-7 are per-server and covered
by the subcommands below.
```bash
daedalus gpgtools # overview of the subcommands
daedalus gpgtools initialize_yubikey # prepare this machine
daedalus gpgtools initialize_yubikey --dry-run # print the plan only
```
| Argument | Default | Meaning |
| --- | --- | --- |
| `--dry-run` | off | Print the plan, write nothing |
| `--gnupg-home DIR` | `GNUPGHOME` or `~/.gnupg` | Which GnuPG home to configure |
Exit codes: `0` ready, `2` package install failed, `3` gpg missing and
no known package manager, `4` no card found, `5` public-key fetch did
not pair the keyring, `6` keyring unpaired and the card carries no URL.
`send_pubkey` covers guide steps 5-6 for one server: resolve the SSH
public key from one of five sources, prove possession of the private
half with a challenge signature (the YubiKey itself signs; PIN prompts
go to the user), then append the line to the target's
`authorized_keys` — idempotent, fingerprint-checked against stores,
and nothing is sent when verification fails.
```bash
daedalus gpgtools send_pubkey --yubikey you@server
daedalus gpgtools send_pubkey --fingerprint <FP> you@server
daedalus gpgtools send_pubkey --url https://keys.openpgp.org/vks/v1/by-fingerprint/<FP> you@server
daedalus gpgtools send_pubkey --pubkey "ssh-ed25519 AAAA... comment" you@server
daedalus gpgtools send_pubkey --file /media/usb/yubikey_auth.pub you@server
daedalus gpgtools send_pubkey --yubikey --dry-run you@server # resolve only
```
| Argument | Default | Meaning |
| --- | --- | --- |
| `--yubikey` | — | Key from the plugged YubiKey via gpg-agent (must be the only agent key) |
| `--url URL` | — | Armored OpenPGP public key at a URL ([A] subkey is exported) |
| `--fingerprint FP` | — | Searched: local keyring → keys.openpgp.org → keyserver.ubuntu.com |
| `--pubkey LINE` | — | The literal SSH public key line |
| `--file PATH` | — | File holding the key line, e.g. a `.pub` from a USB stick (no network, no gpg) |
| `--no-verify` | verification on | Skip the proof-of-possession signature (explicit risk acceptance) |
| `--dry-run` | off | Resolve and print the key; verify and send nothing |
Additional exit codes: `7` ssh to the target failed, `8` no source
resolved a key, `10` proof-of-possession verification failed (nothing
was sent).
`store_publickey` is the mirror for the on-site bootstrap: run it on
the machine that access is being granted *to* — a server with ssh
password authentication disabled that no key authorizes yet, where
you are logged in at the console. It resolves the same five sources
and appends the key into this machine's `authorized_keys`, so the
machine holding the YubiKey can ssh in afterwards. There is no
proof-of-possession (the private half is, by design, elsewhere);
instead both resolve-and-store subcommands print an identity block —
line, source, and the key material's SHA-256 — to compare across
machines. Existing entries are preserved, nothing is duplicated, and
directory/file modes are forced to 700/600.
```bash
daedalus gpgtools store_publickey --file /media/usb/yubikey_auth.pub
daedalus gpgtools store_publickey --fingerprint <FP>
daedalus gpgtools store_publickey --pubkey "ssh-ed25519 AAAA... comment"
daedalus gpgtools store_publickey --file /media/usb/yubikey_auth.pub --dry-run # print only
```
| Argument | Default | Meaning |
| --- | --- | --- |
| sources | — | Same five sources as `send_pubkey` (exactly one required) |
| `--authorized-keys FILE` | `~/.ssh/authorized_keys` | Where to install the key |
| `--dry-run` | off | Resolve and print the key; write nothing |
Additional exit codes: `8` no source resolved a key.
`configure_ssh` covers guide step 7 for one host: it writes a
marker-managed `Host <alias>` block into the ssh client config.
Outside the markers your config is preserved byte-for-byte; re-runs
replace the block (idempotent), and an unmanaged `Host` with the same
alias is refused rather than shadowed. It never connects anywhere.
```bash
daedalus gpgtools configure_ssh --alias vault1 --hostname 203.0.113.10 --user admin
daedalus gpgtools configure_ssh --alias vault1 --dry-run # print only
daedalus gpgtools configure_ssh --alias vault1 --no-fallback # YubiKey only
```
| Argument | Default | Meaning |
| --- | --- | --- |
| `--alias NAME` | required | The ssh Host alias to configure |
| `--hostname HOST` | the alias | HostName value |
| `--user USER` | ssh's default | User value |
| `--pubkey FILE` | `~/.ssh/yubikey_auth.pub` | Primary IdentityFile (must exist) |
| `--fallback FILE` | `~/.ssh/id_ed25519` | Fallback IdentityFile, included only when it exists |
| `--no-fallback` | off | Never add a fallback IdentityFile |
| `--config PATH` | `~/.ssh/config` | Which ssh client config to edit |
Additional exit code: `11` an unmanaged `Host` with the same alias exists in the
config (move it into the managed markers or rename the alias).
`ssh-config-summary` prints what is enabled where, read-only: one row per
managed block — alias, hostname, user, the key id (first 8 chars of the
identity's SHA256 fingerprint, material-digest fallback), and the fallback
identity. Same id on two rows means the same gpg key guards both hosts.
```bash
daedalus gpgtools ssh-config-summary
daedalus gpgtools ssh-config-summary --config FILE
```
| Argument | Default | Meaning |
| --- | --- | --- |
| `--config FILE` | `~/.ssh/config` | Which ssh client config to read |
## 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).
Run `daedalus init` once to register the hook in `~/.bashrc` (below); see
also [INSTALL](https://gitea.nolivaldeziii.com/nvaldez/daedalus/src/branch/main/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).
### publish
`publish` releases the package itself. Guards first — clean working
tree, HEAD exactly tagged `v<version>` (the version from
`pyproject.toml`), the version not yet on PyPI, and `build` + `twine`
available in the running interpreter — then a **chained** build
(the sdist must rebuild the wheel, SPEC item 9.2.1) and
`twine check`. Without `--upload` it stops there and prints the
artifacts; with `--upload` it uploads exactly this version's sdist
and wheel. Credentials never touch the script: twine prompts or
reads `~/.pypirc` (username `__token__`, your PyPI API token).
```bash
daedalus publish # build + check, print next step
daedalus publish --upload # ... and upload to PyPI
```
Exit codes: `2` not run from a checkout, `3` dirty tree, `4` not
exactly tagged `v<version>`, `5` build/twine missing, `6` version
already on PyPI (or PyPI unreachable), `7` build failed, `8` twine
check failed, `9` upload failed.
## Getting started
1. Clone or copy this template and name the Git remote for your team.
2. Add a script under `python/src/`, `bash/`, `powershell/`, or `batch/`
(see [SPEC layout](./SPEC.md#2-layout)).
(see [SPEC layout](https://gitea.nolivaldeziii.com/nvaldez/daedalus/src/branch/main/SPEC.md#2-layout)); bash scripts implement the
shared `help()` interface (SPEC item 6.10).
3. Register it in `daedalus/registry.py`, add a row to the table above,
write tests, bump `version` in `pyproject.toml`, and run
`python autotest.py`.
+83 -8
View File
@@ -77,12 +77,15 @@ daedalus/
│ ├── daedalus_logging/ # File + console logging (section 11)
│ └── tests/
├── python/
│ ├── src/<name>/ # Python scripts, one folder per script
│ ├── src/<name>/ # Python scripts, one folder per script,
│ │ # holding <name>.py and spec.md (SPEC item 6.11)
│ └── tests/ # pytest tests for python/src, .ps1, .bat
├── bash/ # *.sh scripts
├── bash/ # *.sh scripts (SPEC item 6.10 interface),
│ # each with a <name>.spec.md sibling
│ ├── daedalus_common.sh # shared helper: daedalus_bash_dispatch, help() routing
│ └── tests/ # pytest tests that run them
├── powershell/ # *.ps1 scripts
├── batch/ # *.bat scripts (CRLF)
├── powershell/ # *.ps1 scripts, each with <name>.spec.md
├── batch/ # *.bat scripts (CRLF), each with <name>.spec.md
├── ci/ # sanity.py, checks.py, with tests
├── autotest.py # Runs every check (local and CI)
├── pyproject.toml # Package, version, entry point, package data
@@ -298,8 +301,12 @@ help.
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.5.2** A `.sh` script that implements the interface (SPEC item
6.10) completes the help words `--help`, `-h`, and `help`, filtered
by the word being typed; daedalus writes them itself on the
completion channel — no script runs on TAB. A `.sh` script without
the interface, and `.ps1` / `.bat` scripts, get no candidates: the
shell default (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
@@ -466,6 +473,63 @@ SCRIPTS: dict[str, Script] = {
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).
- **6.10** Bash script interface. Every `*.sh` script registered in
`SCRIPTS` implements the shared interface through
`bash/daedalus_common.sh`:
- **6.10.1** Near the top, the script sources the sibling helper
exactly once:
```bash
# shellcheck source=/dev/null
. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/daedalus_common.sh"
```
- **6.10.2** The script defines `help()`, which prints its usage and
option list: the words `daedalus <name> <TAB>` completes (SPEC item
3.13.5.2) route to it.
- **6.10.3** The script defines `main()` with the body; `main "$@"`
receives the script arguments unchanged.
- **6.10.4** The last statement is `daedalus_bash_dispatch "$@"`: the
helper routes `help`, `-h`, and `--help` to `help()` (exit status of
`help`), every other invocation to `main() "$@"` (exit status of
`main`). The help words are reserved for the dispatch in every
bash script.
- **6.10.5** `bash/tests/` enforces the interface for every
registered `.sh` script (source line, `help()`, `main()`, the
dispatch call) and tests the helper behavior directly.
- **6.11** Every script has a local spec that completely
describes it.
- **6.11.1** A Python script's spec is `spec.md` inside its
own folder: `python/src/<name>/spec.md`.
- **6.11.2** A bash, PowerShell, or batch script's spec is a
sibling file named `<name>.spec.md`:
`bash/<name>.spec.md`, `powershell/<name>.spec.md`,
`batch/<name>.spec.md`.
- **6.11.3** The local spec follows the sectionized format of
this file: every heading and list item has a stable numbered
id (`- **N.M**`), sub-items continue the numbering
(`N.M.K`), and items are cited as
`<name> spec item N.M`.
- **6.11.4** The local spec is complete enough to rebuild the
script from it alone: purpose, commands and arguments,
observable behavior (steps, validation, output), exit
codes, files written, error handling, and testing approach.
- **6.11.5** The local spec does not repeat this file; where it
relies on a repository rule it cites the SPEC item instead.
- **6.12** The change order for script work is spec first, then
tests, then code.
- **6.12.1** Create or modify the script's local spec (SPEC
item 6.11) until it describes the intended behavior - a
change that contradicts an existing spec item updates that
item in the same change.
- **6.12.2** Add or change tests that fail without the
behavior.
- **6.12.3** Make the smallest change that makes the tests
pass, then refactor with them green.
- **6.12.4** Spec, tests, code, README, and CHANGELOG land in
the same change; the version bump follows SPEC item 9.8.
## 7. Quality gates
@@ -552,8 +616,11 @@ autotest results
## 9. Packaging
- **9.1** `pyproject.toml` builds one wheel (setuptools 68 or newer) named
`daedalus` that holds the CLI and every script. It requires Python
- **9.1** The PyPI distribution is named `daedalus-tools` (plain
`daedalus` is policy-blocked on PyPI - near the existing
`daedalus-cli`/`pydaedalus` projects; command and import names
stay `daedalus`). `pyproject.toml` builds one wheel (setuptools 68
or newer) that holds the CLI and every script. It requires Python
3.11 or newer.
| Command | Use |
@@ -573,6 +640,14 @@ autotest results
| `powershell/` | `daedalus/_library/powershell/` | `*.ps1` |
| `batch/` | `daedalus/_library/batch/` | `*.bat` |
- **9.2.1** The source tree must be able to rebuild its wheel from
the sdist: every folder the packaging declares (including empty
`powershell/` and `batch/`) carries at least a `README.md`
placeholder, and `MANIFEST.in` ships both folders in the sdist.
A missing declared package directory is a release-blocking
defect: `python -m build` builds sdist and wheel chained, so a
broken sdist fails the release before it ships.
- **9.3** `LIBRARY_ROOT` is `PACKAGE_DIR/_library` when that folder exists
(a normal install), otherwise `REPO_ROOT` (a checkout or an editable
install).
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env bash
# Shared interface for daedalus bash scripts (SPEC.md item 6.10).
#
# A registered bash script sources this sibling file once and ends with:
# daedalus_bash_dispatch "$@"
# The script defines help() (its usage text) and main() (its body).
# daedalus completes the help words for the script (SPEC item 3.13.5.2);
# this helper runs them: help, -h, and --help print help(), everything
# else goes to main() with the arguments unchanged.
help() {
echo "bash script error: help() is not defined (SPEC item 6.10.2)" >&2
return 2
}
main() {
echo "bash script error: main() is not defined (SPEC item 6.10.3)" >&2
return 2
}
daedalus_is_help_request() {
case "${1-}" in
help|-h|--help) return 0 ;;
*) return 1 ;;
esac
}
daedalus_bash_dispatch() {
if daedalus_is_help_request "${1:-}"; then
help
local status=$?
exit "$status"
fi
main "$@"
}
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env bash
# hello_bash: sample bash script for the shared interface (SPEC item 6.10).
#
# Run via daedalus: daedalus hello_bash [name...]
# It exists to exercise help() routing, main() dispatch, and the
# completion of the help words (SPEC item 3.13.5.2) end to end.
# shellcheck source=/dev/null
. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/daedalus_common.sh"
help() {
cat <<'EOF'
usage: hello_bash [name...]
Prints a hello line, once per name, default "world".
EOF
}
main() {
local names=("$@")
((${#names[@]})) || names=("world")
local name
for name in "${names[@]}"; do
echo "hello, ${name} (from daedalus bash)"
done
}
daedalus_bash_dispatch "$@"
+31
View File
@@ -0,0 +1,31 @@
# hello_bash specification
Complete description of `bash/hello_bash.sh`. The sample bash
script of the template: it exercises the SPEC item 6.10 shared
interface end to end. Items are cited as `hello_bash spec item
N.M`.
## 1. Purpose
- **1.1** Print one hello line per name argument, defaulting to
`world` when no argument is given, and exit via the interface:
`hello, <name> (from daedalus bash)`.
## 2. Behavior
- **2.1** The script sources `daedalus_common.sh` once, defines
`help()` (usage text) and `main()` (the printing), and ends
with `daedalus_bash_dispatch "$@"` (SPEC item 6.10).
- **2.2** `daedalus hello_bash me` prints `hello, me (from
daedalus bash)`; `daedalus hello_bash a b` prints one line
per name; no arguments prints the line for `world`.
- **2.3** `help`, `-h`, and `--help` route to `help()` and exit
0; every other invocation routes to `main` unchanged.
- **2.4** Nothing is read or written; the script takes names only.
## 3. Testing approach
- **3.1** `bash/tests/test_hello_bash.py` runs the script through
`runners.find_bash()` (skip when bash is missing) and covers
the default name, multiple names, the help routing, and the
completion words.
+82
View File
@@ -0,0 +1,82 @@
"""Tests for the daedalus bash script interface (SPEC item 6.10).
`bash/daedalus_common.sh` routes the help words to the script's help()
and everything else to its main(); every registered .sh script must
implement the interface.
"""
import re
import subprocess
import pytest
from daedalus import REPO_ROOT
from daedalus import registry
COMMON = REPO_ROOT / "bash" / "daedalus_common.sh"
SCRIPT_TEMPLATE = """#!/usr/bin/env bash
. "{common}"
help() {{
echo "usage: sample [args...] (help from help)"
}}
main() {{
echo "main $*"
echo "count $#"
return 3
}}
daedalus_bash_dispatch "$@"
"""
@pytest.fixture
def sample(tmp_path):
"""A minimal script that implements the interface (SPEC items 6.10.1-6.10.4)."""
path = tmp_path / "sample.sh"
path.write_text(SCRIPT_TEMPLATE.format(common=COMMON))
path.chmod(0o755)
return path
def run(script, *args):
"""Run a script with bash and capture everything."""
return subprocess.run(["bash", str(script), *args], capture_output=True,
text=True, check=False)
@pytest.mark.parametrize("word", ["help", "-h", "--help"])
def test_help_words_route_to_help(sample, word):
"""help, -h, and --help print help() and exit with its status (SPEC item 6.10.4)."""
result = run(sample, word)
assert result.returncode == 0
assert result.stdout == "usage: sample [args...] (help from help)\n"
@pytest.mark.parametrize("args, count", [(("build", "--x", "y z"), 3), ((), 0)])
def test_main_receives_the_arguments(sample, args, count):
"""Everything except the help words goes to main() unchanged (SPEC item 6.10.4)."""
result = run(sample, *args)
assert result.returncode == 3
assert result.stdout.splitlines() == [f"main {' '.join(args)}", f"count {count}"]
def test_common_script_parses():
"""bash -n accepts the shared helper itself."""
assert subprocess.run(["bash", "-n", str(COMMON)], check=False).returncode == 0
def test_every_registered_bash_script_implements_the_interface():
"""Every .sh entry in SCRIPTS: source line, help(), main(), dispatch."""
for name, script in sorted(registry.SCRIPTS.items()):
path = script.absolute_path
if path.suffix != ".sh":
continue
assert path.is_file(), f"{name}: {path} does not exist"
text = path.read_text(encoding="utf-8")
assert "daedalus_common.sh" in text, \
f"{name} must source the shared helper (SPEC item 6.10.1)"
assert re.search(r"^help\s*\(\s*\)", text, re.MULTILINE), \
f"{name} must define help() (SPEC item 6.10.2)"
assert re.search(r"^main\s*\(\s*\)", text, re.MULTILINE), \
f"{name} must define main() (SPEC item 6.10.3)"
assert 'daedalus_bash_dispatch "$@"' in text, \
f"{name} must end with the dispatch call (SPEC item 6.10.4)"
+102
View File
@@ -0,0 +1,102 @@
"""Tests for hello_bash: the shared bash interface end to end (SPEC item 6.10).
Direct runs, daedalus runs, help routing, and the completion of the help
words after the script name (SPEC item 3.13.5.2).
"""
import os
import shlex
import subprocess
import sys
import pytest
from daedalus import REPO_ROOT
from daedalus import registry
SCRIPT = registry.SCRIPTS["hello_bash"].absolute_path
def run_script(*args):
"""Run the script directly with bash."""
return subprocess.run(["bash", str(SCRIPT), *args], capture_output=True,
text=True, check=False)
def run_daedalus(*args):
"""Run python -m daedalus from the checkout, like the installed CLI."""
env = {**os.environ, "PYTHONPATH": str(REPO_ROOT)}
return subprocess.run([sys.executable, "-m", "daedalus", *args],
capture_output=True, text=True, check=False,
cwd=REPO_ROOT.parent, env=env)
def test_main_defaults_to_world():
"""No arguments: one hello line for the default name."""
result = run_script()
assert result.returncode == 0
assert result.stdout == "hello, world (from daedalus bash)\n"
def test_main_prints_one_line_per_name():
"""Every name gets its hello line, arguments unchanged."""
result = run_script("me", "you too")
assert result.returncode == 0
assert result.stdout == ("hello, me (from daedalus bash)\n"
"hello, you too (from daedalus bash)\n")
@pytest.mark.parametrize("word", ["help", "-h", "--help"])
def test_help_words_print_the_usage(word):
"""The help words route to hello_bash's help() (SPEC item 6.10.4)."""
result = run_script(word)
assert result.returncode == 0
assert result.stdout.startswith("usage: hello_bash [name...]")
assert "Prints a hello line" in result.stdout
def test_daedalus_runs_it():
"""daedalus hello_bash runs through the bash runner (SPEC item 5.3)."""
result = run_daedalus("hello_bash", "pi")
assert result.returncode == 0, result.stderr
assert result.stdout == "hello, pi (from daedalus bash)\n"
def test_daedalus_category_prefix_runs_it():
"""daedalus test hello_bash runs it through the category prefix."""
result = run_daedalus("test", "hello_bash")
assert result.returncode == 0, result.stderr
assert result.stdout == "hello, world (from daedalus bash)\n"
def test_daedalus_help_word_passes_through():
"""daedalus hello_bash --help shows the script's help, not daedalus's (SPEC item 3.1)."""
result = run_daedalus("hello_bash", "--help")
assert result.returncode == 0, result.stderr
assert result.stdout.startswith("usage: hello_bash [name...]")
def _probe(comp_line):
"""Replay the argcomplete hook and return the candidates (fd 8)."""
env = {**os.environ, "_ARGCOMPLETE": "1", "COMP_LINE": comp_line,
"COMP_POINT": str(len(comp_line)), "_ARGCOMPLETE_IFS": "\n",
"_ARGCOMPLETE_SHELL": "bash", "PYTHONPATH": str(REPO_ROOT),
"NO_COLOR": "1"}
command = (f"exec 8>&1; exec 1>/dev/null; exec 2>/dev/null; "
f"{shlex.quote(sys.executable)} -m daedalus")
result = subprocess.run(["bash", "-c", command], env=env, cwd=REPO_ROOT,
capture_output=True, text=True, check=False)
return [line.strip() for line in result.stdout.splitlines() if line.strip()]
@pytest.mark.skipif(os.name == "nt", reason="bash completion harness")
def test_completion_offers_the_script_name():
"""daedalus hello_ba<TAB> completes hello_bash."""
assert _probe("daedalus hello_ba") == ["hello_bash"]
@pytest.mark.skipif(os.name == "nt", reason="bash completion harness")
def test_completion_offers_the_help_words():
"""After the script name: only the help words (SPEC item 3.13.5.2)."""
assert _probe("daedalus hello_bash ") == ["--help", "-h", "help"]
assert _probe("daedalus hello_bash --") == ["--help"]
assert _probe("daedalus test hello_bash ") == ["--help", "-h", "help"]
+6
View File
@@ -0,0 +1,6 @@
# Batch scripts live here
`daedalus` runs every `*.bat` in this folder (SPEC.md section 9.2);
registered scripts are installed under `daedalus/_library/batch/`.
This README keeps the folder in git and in the sdist so the
sdist can rebuild its wheel (SPEC item 9.2.1).
+34 -5
View File
@@ -92,20 +92,49 @@ def _exec_delegate(command: str, argv: list[str], env: dict[str, str]) -> None:
os.execve(command, argv, env)
def handles_script_args(execute=_exec_delegate) -> bool:
BASH_HELP_WORDS = ("--help", "-h", "help")
def implements_bash_interface(path) -> bool:
"""True when the .sh sources daedalus_common.sh (SPEC items 6.10.1, 3.13.5.2)."""
try:
return "daedalus_common.sh" in path.read_text(encoding="utf-8")
except OSError:
return False
def _emit_candidates(candidates: list[str]) -> None:
"""Write candidates on the completion channel (fd 8), argcomplete protocol."""
ifs = os.environ.get("_ARGCOMPLETE_IFS", "\013")
try:
with os.fdopen(8, "w") as stream:
stream.write(ifs.join(candidates))
except OSError:
pass
def handles_script_args(execute=_exec_delegate, emit=None) -> 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).
environment rewritten to start at the script name (SPEC item 3.13.5.1).
A .sh script with the interface completes the help words itself, written
on the completion channel without running the script (SPEC item 3.13.5.2);
other suffixes get no candidates at all.
"""
plan = script_args_delegation()
if plan is None:
return False
script, comp_line, tail = plan
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)))
env = dict(os.environ, COMP_LINE=_comp_line, COMP_POINT=str(len(_comp_line)))
execute(command[0], [*command, *tail], env)
elif path.suffix.lower() == ".sh" and implements_bash_interface(path):
partial = tail[-1] if tail else ""
candidates = [word for word in BASH_HELP_WORDS if word.startswith(partial)]
if emit is None:
emit = _emit_candidates
emit(candidates)
return True
+20
View File
@@ -54,11 +54,31 @@ class Script:
SCRIPTS: dict[str, Script] = {
"gpgtools": Script(
path="python/src/gpgtools/gpgtools.py",
description="YubiKey GPG/SSH helpers: initialize (gnupg readiness check + install), initialize_yukikey (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), ssh-config-summary (per-host table of gpg-enabled logins)",
categories="gpg",
),
"hello": Script(
path="python/src/hello/hello.py",
description="Print a hello line and the daedalus version",
categories="test",
),
"hello_bash": Script(
path="bash/hello_bash.sh",
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",
),
"publish": Script(
path="python/src/publish/publish.py",
description="Release daedalus to PyPI: guarded chained build (clean tree, exact v<version> tag, PyPI-free version, tooling), twine check, optional --upload (credentials stay with twine)",
categories="release",
),
}
"""Every script daedalus can run (SPEC.md section 4)."""
+1 -1
View File
@@ -150,7 +150,7 @@ def test_path_with_extra_words_is_a_usage_error(fake_registry, plain, capsys):
assert "usage: daedalus --path <name>" in capsys.readouterr().err
@pytest.mark.parametrize("installed, expected", [(True, "daedalus 1.2.3"), (False, "daedalus 0.3.0")])
@pytest.mark.parametrize("installed, expected", [(True, "daedalus 1.2.3"), (False, "daedalus 0.13.1")])
def test_version(monkeypatch, capsys, installed, expected):
"""--version uses metadata or pyproject.toml in a checkout."""
def fake_version(_name):
+83 -7
View File
@@ -183,12 +183,62 @@ def test_handles_false_without_script_word(fake_registry, monkeypatch):
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)
monkeypatch.setattr(completions, "handles_script_args", lambda execute=None, emit=None: True)
assert cli.main(["hello", "-x"]) == 0
assert capsys.readouterr().out == ""
def _probe(comp_line: str) -> str:
@pytest.fixture
def bash_interface_script(tmp_path, monkeypatch):
"""An .sh script in a tmp dir that implements the interface (SPEC item 6.10)."""
path = tmp_path / "iface.sh"
path.write_text('#!/usr/bin/env bash\n'
'. "$(dirname "${BASH_SOURCE[0]}")/daedalus_common.sh"\n')
monkeypatch.setitem(registry.SCRIPTS, "iface",
registry.Script(str(path), "Bash script", categories="test"))
plain = registry.Script(str(tmp_path / "plain.sh"), "Plain", categories="test")
monkeypatch.setitem(registry.SCRIPTS, "plain_sh", plain)
return path
def test_bash_help_words_narrow_by_prefix(bash_interface_script, monkeypatch):
"""The help words filter by the word being typed (SPEC item 3.13.5.2)."""
set_comp_line(monkeypatch, "daedalus iface ")
emitted = []
assert completions.handles_script_args(execute=emitted.append,
emit=emitted.append) is True
assert emitted == [["--help", "-h", "help"]]
set_comp_line(monkeypatch, "daedalus iface -")
emitted.clear()
assert completions.handles_script_args(execute=emitted.append,
emit=emitted.append) is True
assert emitted == [["--help", "-h"]]
set_comp_line(monkeypatch, "daedalus iface he")
emitted.clear()
assert completions.handles_script_args(execute=emitted.append,
emit=emitted.append) is True
assert emitted == [["help"]]
def test_bash_without_interface_is_silent(bash_interface_script, monkeypatch):
"""A .sh script that does not source the helper gets no candidates."""
set_comp_line(monkeypatch, "daedalus plain_sh ")
emitted = []
assert completions.handles_script_args(execute=emitted.append,
emit=emitted.append) is True
assert emitted == []
def test_implements_bash_interface(bash_interface_script, tmp_path):
"""Interface detection reads the script source for the helper (SPEC item 6.10.1)."""
assert completions.implements_bash_interface(bash_interface_script) is True
plain = tmp_path / "plain.sh"
assert completions.implements_bash_interface(plain) is False
missing = tmp_path / "missing.sh"
assert completions.implements_bash_interface(missing) is False
def _probe(comp_line: str, code: str = "") -> str:
"""Replay the argcomplete hook for comp_line and return the candidates."""
env = dict(
os.environ,
@@ -199,35 +249,57 @@ def _probe(comp_line: str) -> str:
_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"
program = (f"{shlex.quote(sys.executable)} -c {shlex.quote(code)}"
if code else f"{shlex.quote(sys.executable)} -m daedalus")
command = f"exec 8>&1; exec 1>/dev/null; exec 2>/dev/null; {program}"
result = subprocess.run(["bash", "-c", command], env=env, cwd=str(REPO_ROOT),
capture_output=True, text=True, check=False)
return result.stdout
requires_bash = pytest.mark.skipif(os.name == "nt", reason="bash completion harness")
requires_argcomplete = pytest.mark.skipif(
importlib.util.find_spec("argcomplete") is None,
reason="end-to-end completion needs argcomplete",
)
@requires_bash
@requires_argcomplete
def test_end_to_end_bash_script_help_words(tmp_path):
"""A registered interface .sh completes its help words through the hook."""
script = tmp_path / "probe.sh"
script.write_text('#!/usr/bin/env bash\n'
'. "$(dirname "${BASH_SOURCE[0]}")/daedalus_common.sh"\n')
code = ("import sys\nfrom daedalus import cli, registry\n"
f"registry.SCRIPTS['probe'] = registry.Script({str(script)!r}, 'Probe',"
" categories='test')\n"
"sys.exit(cli.main())\n")
lines = [line.strip() for line in _probe("daedalus probe ", code).splitlines()
if line.strip()]
assert lines == ["--help", "-h", "help"]
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_bash
@requires_argcomplete
def test_end_to_end_first_word():
"""daedalus h<TAB> completes hello through the argcomplete protocol."""
assert _candidates("daedalus h") == ["hello"]
"""daedalus hel<TAB><TAB> lists hello and hello_bash (same prefix)."""
assert _candidates("daedalus hel") == ["hello", "hello_bash"]
@requires_bash
@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"]
"""daedalus test hel<TAB><TAB> lists both scripts in the category."""
assert _candidates("daedalus test hel") == ["hello", "hello_bash"]
@requires_bash
@requires_argcomplete
def test_end_to_end_empty_word_lists_only_candidates():
"""On an empty word, only daedalus offers: options plus scripts and labels."""
@@ -236,6 +308,7 @@ def test_end_to_end_empty_word_lists_only_candidates():
assert ".md" not in " ".join(candidates)
@requires_bash
@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)."""
@@ -245,12 +318,14 @@ def test_end_to_end_options_for_dash_prefix():
assert "hello" not in candidates
@requires_bash
@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_bash
@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)."""
@@ -261,6 +336,7 @@ def test_end_to_end_script_options_come_from_the_script():
assert "--path" not in candidates
@requires_bash
@requires_argcomplete
def test_end_to_end_delegation_through_category():
"""daedalus test hello --<TAB> completes hello's --help through the prefix."""
+6
View File
@@ -0,0 +1,6 @@
# Powershell scripts live here
`daedalus` runs every `*.ps1` in this folder (SPEC.md section 9.2);
registered scripts are installed under `daedalus/_library/powershell/`.
This README keeps the folder in git and in the sdist so the
sdist can rebuild its wheel (SPEC item 9.2.1).
+8 -2
View File
@@ -3,8 +3,8 @@ requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "daedalus"
version = "0.3.0"
name = "daedalus-tools"
version = "0.13.1"
description = "Template for daedalus: loose scripts in one repo, run with: daedalus <name> [args...]"
readme = "README.md"
requires-python = ">=3.11"
@@ -19,7 +19,10 @@ daedalus = "daedalus.cli:main"
packages = [
"daedalus",
"daedalus.daedalus_logging",
"daedalus.gpgtools",
"daedalus.hello",
"daedalus.init",
"daedalus.publish",
"daedalus._library.python.src",
"daedalus._library.bash",
"daedalus._library.powershell",
@@ -27,7 +30,10 @@ packages = [
]
[tool.setuptools.package-dir]
"daedalus.gpgtools" = "python/src/gpgtools"
"daedalus.hello" = "python/src/hello"
"daedalus.init" = "python/src/init"
"daedalus.publish" = "python/src/publish"
"daedalus._library.python.src" = "python/src"
"daedalus._library.bash" = "bash"
"daedalus._library.powershell" = "powershell"
File diff suppressed because it is too large Load Diff
+375
View File
@@ -0,0 +1,375 @@
# gpgtools specification
Complete description of `python/src/gpgtools/gpgtools.py`. Change
this file first, then tests, then code (SPEC items 6.11 and 6.12).
Items are cited as `gpgtools spec item N.M`.
<!-- toc-start: headings 2..6 -->
- [1. Purpose](#1-purpose)
- [2. Commands](#2-commands)
- [3. initialize_yubikey behavior](#3-initialize_yubikey-behavior)
- [4. send_pubkey behavior](#4-send_pubkey-behavior)
- [5. Exit codes](#5-exit-codes)
- [6. Runner contract and injectability](#6-runner-contract-and-injectability)
- [7. Files written](#7-files-written)
- [8. Testing approach](#8-testing-approach)
- [9. References](#9-references)
- [10. configure_ssh behavior](#10-configure_ssh-behavior)
- [11. store_publickey behavior](#11-store_publickey-behavior)
- [12. initialize behavior](#12-initialize-behavior)
- [13. ssh-config-summary behavior](#13-ssh-config-summary-behavior)
<!-- toc-end -->
## 1. Purpose
- **1.1** gpgtools automates the YubiKey SSH flow documented in the
owner's wiki guide
(`~/repositories/vibe-wiki/wiki/queries/yubikey-ssh-guide.md`):
`initialize_yubikey` covers guide steps 1-4 (fresh machine ready
for GPG), `send_pubkey` covers steps 5-6 (key to a server).
`store_publickey` covers the on-site bootstrap case (section 11):
installing the key from the machine that access is being
granted to. Guide step 7 (per-host `~/.ssh/config`) is out of
scope.
- **1.2** Hard constraint: the YubiKey's OpenPGP applet is never
written - no `gpg --card-edit`, no `keytocard`, no applet reset.
Only public card data is read; the card PIN is typed by its
owner into pinentry, never passed through this script.
- **1.3** The user's real GNUPGHOME is written only where section
7 says so; remote public-key imports go to a throwaway home
(item 4.5).
- **1.4** Standard library only; Python 3.11+ (SPEC item 9.6).
## 2. Commands
- **2.1** `daedalus gpgtools` with no subcommand prints the
overview of the subcommands and exits 0.
- **2.2** `daedalus gpgtools initialize_yubikey [--dry-run]
[--gnupg-home DIR]` - prepares this machine (section 3).
- **2.3** `daedalus gpgtools send_pubkey
(--yubikey | --url URL | --fingerprint FP | --pubkey LINE | --file PATH)
[--no-verify] [--dry-run] you@server` - resolves one SSH
public key, proves possession of the private half, appends it
to the target (section 4). The five source flags are mutually
exclusive and exactly one is required; `you@server` is
required.
- **2.4** `--dry-run` on either subcommand prints what would
happen and writes nothing; on `send_pubkey` it resolves and
prints the key but never verifies and never connects.
- **2.5** `daedalus gpgtools configure_ssh --alias NAME
[--hostname HOST] [--user USER] [--pubkey FILE]
[--fallback FILE | --no-fallback] [--config PATH] [--dry-run]`
- writes the per-host ssh client block (guide step 7);
behavior in section 10.
- **2.6** `daedalus gpgtools store_publickey
(--yubikey | --url URL | --fingerprint FP | --pubkey LINE | --file PATH)
[--authorized-keys FILE] [--dry-run]` - resolves one SSH
public key and installs it into *this* machine's
authorized_keys (section 11). The source flags are the
send_pubkey set (items 4.1.1-4.1.5), mutually exclusive,
exactly one required.
- **2.7** `daedalus gpgtools initialize [--dry-run]` - checks
that gnupg is ready on this machine and installs what is
missing; the gnupg-only half of initialize_yubikey
(section 12).
- **2.8** `daedalus gpgtools ssh-config-summary
[--config PATH]` - prints the table of gpg-enabled ssh logins
found in the config (section 13); read-only.
## 3. initialize_yubikey behavior
- **3.1** Step 1 - gnupg: the section 12 flow (item 12.1). When
`gpg --version` fails, the package manager is detected
(`shutil.which` over apt-get, dnf, pacman) and gnupg installed
via `sudo`; no known manager is exit 3. A failed install is
exit 2.
- **3.2** Step 2 - card: `gpg --card-status` parsed for the
`Application type`/`OpenPGP` markers; absent card (including
gpg error text) is exit 4 with the pcscd hint
`systemctl enable --now pcscd`.
- **3.3** Card fields: serial (`Serial number`), authentication
subkey presence (`Authentication key` with a non-`[none]`
value), key URL (`URL of public key`, `[not set]` is None),
keyring pairing (`General key info` non-`[none]`).
- **3.4** Step 3 - public key: when unpaired and a URL exists,
`gpg --fetch-keys <url>`, then re-parse the card; still
unpaired is exit 5. Unpaired without a URL is exit 6 with the
manual-import hint.
- **3.5** A missing `[A]` subkey logs a warning (SSH via
gpg-agent will not work; GPG signing/decryption will) but is
not an error.
- **3.6** Step 4 - agent: the homedir is created at mode 700;
`gpg-agent.conf` gains `enable-ssh-support` and, only when its
key is absent, `default-cache-ttl 600` and `max-cache-ttl
7200`; existing lines, including user TTLs, are kept verbatim
and never duplicated. `gpgconf --kill gpg-agent` restarts the
agent. Exit 0.
## 4. send_pubkey behavior
- **4.1** Sources (exactly one per run):
- **4.1.1** `--yubikey`: the gpg ssh socket from
`gpgconf --list-dirs agent-ssh-socket` (bare path or prefixed
form), `SSH_AUTH_SOCK` set to it, `ssh-add -L`. No socket is
exit 8 with the `initialize_yubikey` hint; no keys is exit 8
with "is the YubiKey plugged in?"; several keys refuses with
the list and the `--pubkey` hint rather than guessing.
- **4.1.2** `--url`: fetch the armored OpenPGP public key,
convert via item 4.5.
- **4.1.3** `--fingerprint`: normalize (strip spaces and `0x`,
case-insensitive, exactly 40 hex chars, else exit 8); resolve
through the store chain, first hit wins: local keyring (`gpg
--export-ssh-key 0x<FP>`), then keys.openpgp.org VKS
(`.../vks/v1/by-fingerprint/<FP>`), then keyserver.ubuntu.com
(`.../pks/lookup?op=get&search=0x<FP>`). Every store result is
fingerprint-checked before use; a mismatch skips the store.
All exhausted is exit 8 naming the stores.
- **4.1.4** `--pubkey`: the literal line, validated by item 4.2;
exit 8 when invalid.
- **4.1.5** `--file PATH`: a file holding the SSH public key
line - typically `yubikey_auth.pub` carried on a USB stick
(zero network, zero gpg). Every line is validated per item
4.2: no valid line is exit 8; several valid lines refuse
listing them with the `--pubkey` hint (item 4.1.1
precedent) rather than guessing; an unreadable or missing
file is exit 8.
- **4.2** Key line validation: `ssh-(ed25519|rsa|dss|ecdsa-sha2-*)
<base64> [comment]`, full line; anything else is rejected.
- **4.3** Key material (type + base64, comment ignored) is the
key's identity for deduplication and reporting.
- **4.4** Proof of possession (default, skipped only with
`--no-verify`): a random hex challenge is signed via
`ssh-keygen -Y sign -U` (the private half - card, PIN prompt
included - must sign) and verified via `ssh-keygen -Y verify`
against the candidate line with an allowed_signers file. Any
failure prints that nothing was sent and exits 10; the ssh
target is never contacted.
- **4.5** Remote conversion: armored keys are imported into a
throwaway `--homedir` via `gpg --import`, fingerprints listed
with `--list-keys --with-colons`, and the ssh line exported with
`gpg --export-ssh-key 0x<FP>`. The real keyring is not touched;
the throwaway home is removed afterwards.
- **4.6** Send: `ssh you@server "cat ~/.ssh/authorized_keys
2>/dev/null"` to read, then - only when the key material is
absent - append the line via stdin with perms forced
(`mkdir -p`, `chmod 700 ~/.ssh`, `chmod 600 authorized_keys`).
Present is reported, not re-appended. Any ssh failure is exit 7;
nothing is appended on failure.
- **4.7** Both ssh calls run without an interactive terminal: the
target must be reachable with existing non-interactive
credentials (agent, passphrase-less key, or ControlMaster
socket). First contact to a brand-new server by password is out
of scope - gain access once manually, then send the key.
- **4.8** Output (identical in section 11): both resolve-and-store
subcommands print the resolved key line, its source, and the
SHA-256 hex digest of the key material (item 4.3) before
acting, so the resolved value can be compared with the machine
the key came from (or read over a phone).
## 5. Exit codes
| Code | Meaning |
| --- | --- |
| 0 | success (initialize ready; send appended or already present) |
| 2 | package install failed (initialize, initialize_yubikey) |
| 3 | gpg missing and no known package manager (initialize, initialize_yubikey) |
| 4 | no OpenPGP card found (initialize) |
| 5 | public-key fetch did not pair the keyring (initialize) |
| 6 | keyring unpaired and the card carries no URL (initialize) |
| 7 | ssh to the target failed; nothing stored (send) |
| 8 | no source resolved a usable key (send, store); pubkey file missing (configure) |
| 10 | proof-of-possession verification failed; nothing sent (send) |
| 11 | an unmanaged `Host <alias>` exists in the config (configure) |
## 6. Runner contract and injectability
- **6.1** Everything external goes through
`run_command(cmd, input_text="", env=None) -> (code,
stdout+stderr)`: env variables are merged over `os.environ`,
`input_text` is piped to stdin, a missing binary returns
`(127, "<cmd>: not found")`.
- **6.2** `initialize_yukikey(home, run_cmd)`,
`verify_possession(line, workdir, run_cmd)`,
`send_key(line, target, run_cmd)`, and the `source_*`
functions accept the runner; `source_url`,
`source_fingerprint`, and `cmd_send_pubkey` also accept a
`fetch(url) -> bytes | None`. Tests inject fakes; defaults are
`run_command` and `fetch_bytes` (urllib, 30 s timeout, None on
any fetch error).
- **6.3** ssh-keygen signature namespaces and identity are the
constants `daedalus-gpgtools` and `daedalus@verify`.
## 7. Files written
- **7.1** initialize: `<gnupg-home>/gpg-agent.conf` (merge per
item 3.6); the homedir permissions set to 700. Nothing else.
- **7.2** send: scratch dirs (throwaway GNUPGHOME, challenge
workspace) are created under the system temp dir and removed in
`finally`. The only persistent write is the target's
`authorized_keys` append via ssh (item 4.6).
- **7.3** store: the local `authorized_keys` (item 11.5) is the
only persistent write; its parent gets mode 700, the file 600.
Scratch rules of item 7.2 apply when remote sources resolve
(item 4.5).
## 8. Testing approach
- **8.1** Tests live in `python/tests/test_gpgtools.py` and never
need hardware, a network, or an interactive terminal (SPEC item
6.6): all flows take an injected runner; fetchers and runners
are fakes scripted per test by command prefix.
- **8.2** Covered groups: card-status parsing (present/absent,
no URL, no auth subkey, unpaired), config merge (empty,
preserving, complete), manager mapping and detection,
GNUPGHOME resolution, the initialize flow's success, failure,
warning, and persistence branches and the standalone
readiness/install/re-check branches (section 12), the five
sources including the store chain and fingerprint mismatch,
challenge sign/verify success and refusal, send idempotence by
material, store: file sources, append, preservation,
idempotence, perms, dry run, summary: block parsing (each
field), key-id resolution and both id fallbacks, the empty
and missing-config paths, and the CLI wiring, guards, and
dry runs.
- **8.3** The change order is spec item 6.12: this spec first,
then failing tests, then the smallest implementation.
## 9. References
- **9.1** The wiki guide behind items 1.1:
`~/repositories/vibe-wiki/wiki/queries/yubikey-ssh-guide.md`
(steps 1-13; automation notes in section 13).
- **9.2** Repository rules: SPEC items 6.6 (tests), 6.9
(argcomplete opt-in after the parser), 9.8 (version bump).
- **9.3** History: `CHANGELOG.md` entries 0.5.0, 0.6.0
(initialize/send), 0.7.0 (configure_ssh), 0.8.0
(--file source, store_publickey), 0.9.0 (initialize), 0.10.0
(init script), 0.11.0 (ssh-config-summary).
## 10. configure_ssh behavior
- **10.1** The block is written into `--config` (default
`~/.ssh/config`) between managed markers, one block per alias:
```text
# BEGIN daedalus gpgtools: <alias>
Host <alias>
HostName <hostname>
User <user> (omitted without --user)
IdentityFile <pubkey>
IdentityFile <fallback> (omitted per item 10.4)
IdentitiesOnly yes
# END daedalus gpgtools: <alias>
```
- **10.2** Defaults: `--hostname` defaults to the alias itself;
`--pubkey` defaults to `~/.ssh/yubikey_auth.pub`;
`--fallback` defaults to `~/.ssh/id_ed25519`.
- **10.3** Idempotence: a run that finds the alias's markers
replaces the whole marked block with the newly built one;
everything outside the markers is preserved byte-for-byte.
Running twice with the same arguments changes nothing.
- **10.4** The fallback `IdentityFile` is included only when its
file exists and `--no-fallback` was not given; a missing
explicit `--fallback FILE` logs a warning.
- **10.5** Guards: a `--pubkey` file that does not exist is exit
8 with the derive hint; a `Host` line naming the same alias
anywhere outside the managed markers is exit 11 (ssh would let
the first match shadow the managed block).
- **10.6** File hygiene: `~/.ssh` is created at mode 700 when
missing; the config file is created at mode 600 when missing.
- **10.7** `--dry-run` prints the block plus
`creating`/`replacing`, and writes nothing.
## 11. store_publickey behavior
- **11.1** Installs one SSH public key into the *current user's*
`~/.ssh/authorized_keys` (`--authorized-keys FILE` overrides)
on this machine - the machine the key will later grant access
to. Use case: a server with ssh password authentication
disabled that no key authorizes yet; you are logged in at its
console and install the key from inside, so the machine
holding the YubiKey can ssh in afterwards. It is the mirror of
section 4: send pushes the key from where it is, store pulls
it from where the access is.
- **11.2** Sources: identical to items 4.1.1-4.1.5, one per run.
On a bare server the realistic ones are `--pubkey` (typed at
the console), `--file` (USB stick; needs no network and no
gpg), and `--fingerprint` (store chain, needs gpg and
network); `--yubikey` works when the card is plugged into
this machine. An unresolvable source is exit 8 (item 5).
- **11.3** There is no proof-of-possession step (item 4.4) and
no `--no-verify` flag: the private half is, by design,
elsewhere - this machine is the one being granted access, so
nothing here could sign the challenge. Hardening instead: line
validation (item 4.2), fingerprint-checked stores (item
4.1.3), and the identity block (item 11.4).
- **11.4** Identity block: the resolved key line, its source,
and the SHA-256 hex digest of the key material (item 4.3) are
printed before writing (shared rule, item 4.8), so the value
can be compared with the machine the key came from.
- **11.5** Storage: the parent directory is created at mode 700
when missing and the authorized_keys file forced to mode 600,
on every write. Existing entries are preserved verbatim -
authorized_keys is a multi-key file; there is no mismatch
guard on the rest, only the new key's absence is checked.
- **11.6** Idempotence follows item 4.3: the line is appended
only when its material is absent (comments ignored); already
present is reported and exits 0. A missing trailing newline
in an existing file is repaired, never glued into a key line.
- **11.7** `--dry-run` prints the identity block plus
`already present`/`creating` and writes nothing.
- **11.8** No ssh is run and the only persistent write is item
11.5; remote sources keep item 4.5's throwaway-home rule
(item 7.3). Exit codes: 0 stored or already present, 8 no
source resolved a usable key.
## 12. initialize behavior
- **12.1** `initialize` covers the gnupg half of item 3.1
only - no card, keyring, or agent expectations. `gpg
--version` decides readiness: present prints the version
line and exits 0. Missing runs manager detection and the
`sudo` install (item 3.1's manager map); no known manager is
exit 3, a failed install is exit 2. After a successful
install the check re-runs once - still unusable is exit 2.
- **12.2** `--dry-run` performs only the read-only
`gpg --version`, prints what would happen (`already ready`
with the version line, the install command it would run, or
the install-manually message), installs nothing, and exits 0
in every dry-run case.
- **12.3** `initialize_yubikey` runs this flow as its step 1
(item 3.1); a `-2`/`-3` return stops it before anything else.
- **12.4** Intended use: the on-site companion to
store_publickey (item 11) - on a machine without the
YubiKey, run `initialize` first when a gpg-dependent source
(`--fingerprint`, `--url`, `--yubikey`) is wanted.
## 13. ssh-config-summary behavior
- **13.1** Scope: every marker-managed block (item 10.1) in
`--config` (default `~/.ssh/config`) is one gpg-enabled
login. The command never writes and never contacts any
host; it reads only the config and the IdentityFiles the
blocks name (`~` expanded).
- **13.2** Output is one row per block with the columns
`alias`, `hostname`, `user`, `key id`, `fallback`:
hostname defaults to the alias when the block omits
HostName; user prints `-` when absent (ssh's own default);
fallback prints `-` when the block has no second
IdentityFile. Columns are padded and separated by two
spaces, like the daedalus script listing.
- **13.3** Key id: taken from the block's *first* IdentityFile.
`ssh-keygen -lf <file>` yields the SHA256 fingerprint; the
row shows its first 8 chars after the `SHA256:` prefix
(shorter values print in full). When ssh-keygen fails or is
missing but the file is readable and holds a valid key line
(item 4.2), the id falls back to the first 8 chars of the
material digest (item 4.8) - both are stable per key. A
missing or unreadable IdentityFile prints `-` for the id.
- **13.4** No managed blocks - a missing config file counts -
prints that fact with the `configure_ssh` hint and exits 0.
- **13.5** Exit code is always 0; the command is read-only and
has no failure modes that would leave anything half-done.
+1 -1
View File
@@ -23,7 +23,7 @@ UNKNOWN = "unknown"
def app_version() -> str:
"""Installed daedalus version, else the checkout pyproject, else 'unknown'."""
try:
return importlib.metadata.version("daedalus") # plain and editable installs
return importlib.metadata.version("daedalus-tools") # plain and editable installs
except importlib.metadata.PackageNotFoundError:
pass
# A checkout that is not installed: python/src/hello/hello.py -> pyproject.toml
+33
View File
@@ -0,0 +1,33 @@
# hello specification
Complete description of `python/src/hello/hello.py`. The sample
Python script of the template: it exercises the registry, the
`test` category, and the run_python_script entry end to end.
Items are cited as `hello spec item N.M`.
## 1. Purpose
- **1.1** Print one line, `hello from daedalus <version>`, and
exit 0. It takes no arguments of its own.
- **1.2** `<version>` comes from `app_version()`: the installed
daedalus metadata (`importlib.metadata.version("daedalus")`),
else the `version` field of the checkout's `pyproject.toml`
(resolved relative to the script file), else the literal
`unknown`.
## 2. Behavior
- **2.1** `daedalus hello` prints the line and exits 0;
`daedalus test hello` does the same through the category
prefix.
- **2.2** The parser opts in to argcomplete (SPEC item 6.9) with
a guarded import; without argcomplete nothing changes.
- **2.3** No files are read besides `pyproject.toml` in the
fallback; nothing is written.
## 3. Testing approach
- **3.1** `python/tests/test_hello.py` covers both version
resolutions (metadata and pyproject fallback, monkeypatched),
the printed line, `--help`, and end-to-end runs through the
CLI.
+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.
+208
View File
@@ -0,0 +1,208 @@
"""Release daedalus to PyPI: guarded build, check, upload (publish spec).
`daedalus publish` turns the checkout into a versioned sdist + wheel
pair and (with ``--upload``) hands them to PyPI via twine, only after
the guards pass (publish spec section 3): a clean tree, HEAD exactly
tagged ``v<version>``, the version not yet on PyPI, and the build and
twine tooling present in the running interpreter. Credentials are
never handled by this script - twine prompts or reads ``~/.pypirc``.
Run from the daedalus checkout: ``daedalus publish`` (spec item 1.4).
"""
from __future__ import annotations
import argparse
import logging
import pathlib
import re
import subprocess
import sys
import tomllib
import urllib.error
import urllib.request
try: # SPEC item 6.9: complete publish'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_REPO = 2
EXIT_DIRTY = 3
EXIT_TAG = 4
EXIT_TOOLING = 5
EXIT_PYPI = 6
EXIT_BUILD = 7
EXIT_CHECK = 8
EXIT_UPLOAD = 9
PY = sys.executable
PYPI_VERSION_URL = "https://pypi.org/pypi/{name}/{version}/json"
def find_repo_root() -> pathlib.Path | None:
"""The checkout root above the script (item 3.1), or None."""
root = pathlib.Path(__file__).resolve().parents[3]
return root if (root / "pyproject.toml").is_file() else None
def read_project(pyproject: pathlib.Path) -> tuple[str, str]:
"""Read [project] name and version from pyproject.toml (3.2)."""
project = tomllib.loads(
pyproject.read_text(encoding="utf-8"))["project"]
return project["name"], project["version"]
def run_in_cwd(cmd: list[str],
cwd: pathlib.Path | None = None) -> tuple[int, str]:
"""Run a command (in cwd when given); return (code, output)."""
try:
result = subprocess.run(
cmd, capture_output=True, text=True, check=False,
cwd=str(cwd) if cwd else None)
except FileNotFoundError:
return 127, f"{' '.join(cmd)}: not found"
return result.returncode, (result.stdout or "") + (result.stderr or "")
def pypi_status(url: str) -> int | None:
"""HTTP status of a PyPI JSON URL, or None when unreachable."""
try:
with urllib.request.urlopen(url, timeout=30) as response:
return response.status
except urllib.error.HTTPError as err:
return err.code
except (urllib.error.URLError, ValueError):
return None
def artifact_names(name: str, version: str) -> tuple[str, str]:
"""The version's sdist and wheel file names (items 3.4-3.7).
File names use the PEP 625 normalized name (lowercase, runs
of `-._` collapsed to one underscore - what setuptools
writes to dist/); the PyPI JSON probe uses `name` as written.
The wheel is a pure-Python wheel (SPEC item 9.1), so its name
follows ``<normalized>-<version>-py3-none-any.whl``.
"""
safe = re.sub(r"[-_.]+", "_", name).lower()
return (f"{safe}-{version}.tar.gz",
f"{safe}-{version}-py3-none-any.whl")
def cmd_publish(args: argparse.Namespace, run_cmd=None,
fetch_status=None) -> int:
"""publish subcommand: guards, build, check, upload.
Args:
args: parsed arguments (upload).
run_cmd: ``(cmd, cwd) -> (code, output)`` runner;
defaults to run_in_cwd.
fetch_status: ``(url) -> HTTP status | None``;
defaults to pypi_status.
Returns:
Exit code per publish spec section 4.
"""
if run_cmd is None:
run_cmd = run_in_cwd
if fetch_status is None:
fetch_status = pypi_status
root = find_repo_root()
if root is None:
LOGGER.error("not a daedalus checkout: no pyproject.toml "
"above %s (item 3.1)", __file__)
return EXIT_NO_REPO
name, version = read_project(root / "pyproject.toml")
code, output = run_cmd(["git", "status", "--porcelain"], cwd=root)
if code != 0 or output.strip():
LOGGER.error("working tree is dirty (or git failed); commit "
"or stash first - what ships must be committed "
"(item 3.3.1)")
return EXIT_DIRTY
code, output = run_cmd(["git", "tag", "--points-at", "HEAD"], cwd=root)
tags = [line.strip() for line in output.splitlines() if line.strip()]
if code != 0 or f"v{version}" not in tags:
LOGGER.error("v%s is not among the tags pointing at HEAD "
"(found: %s); tag the release first: git tag -a "
"v%s -m \"...\" (item 3.3.2)",
version, tags or "none", version)
return EXIT_TAG
for module in ("build", "twine"):
code, _output = run_cmd([PY, "-m", module, "--version"], cwd=root)
if code != 0:
LOGGER.error("python -m %s is unavailable in this "
"interpreter; pipx inject daedalus build twine, "
"or pip install -r requirements.txt (item 3.3.3)",
module)
return EXIT_TOOLING
status = fetch_status(
PYPI_VERSION_URL.format(name=name, version=version))
if status == 200:
LOGGER.error("%s %s is already on PyPI; a published version is "
"immutable - bump the version (item 3.3.4)",
name, version)
return EXIT_PYPI
if status != 404:
LOGGER.error("could not check PyPI (status %s); never publish "
"blind (item 3.3.4)", status)
return EXIT_PYPI
sdist, wheel = artifact_names(name, version)
print(f"release : {name} {version} "
"(tree clean, tag exact, PyPI free)")
print("build : python -m build (sdist -> wheel, chained)")
code, output = run_cmd([PY, "-m", "build"], cwd=root)
if code != 0:
LOGGER.error("build failed; fastest repro: %s -m build --wheel"
"\n%s", PY, output.strip())
return EXIT_BUILD
code, output = run_cmd([PY, "-m", "twine", "check",
f"dist/{sdist}", f"dist/{wheel}"], cwd=root)
if code != 0:
LOGGER.error("twine check failed:\n%s", output.strip())
return EXIT_CHECK
print(f"artifacts : dist/{sdist}, dist/{wheel}")
if not args.upload:
print("checked; upload this exact version with: "
"daedalus publish --upload")
return EXIT_OK
print("upload : twine (credentials from ~/.pypirc or the "
"prompt; username __token__ with your PyPI API token)")
code, output = run_cmd([PY, "-m", "twine", "upload",
f"dist/{sdist}", f"dist/{wheel}"], cwd=root)
if code != 0:
LOGGER.error("twine upload failed:\n%s", output.strip())
return EXIT_UPLOAD
print(f"uploaded : {name} {version} -> "
f"https://pypi.org/project/{name}/{version}/")
return EXIT_OK
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse publish command-line arguments."""
parser = argparse.ArgumentParser(
prog="publish",
description="Release daedalus to PyPI: guarded build, twine "
"check, optional upload",
)
parser.add_argument("--upload", action="store_true",
help="upload this exact version to PyPI after "
"the checks pass (default: build and "
"check only)")
if autocomplete is not None: # SPEC item 6.9
autocomplete(parser)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
"""CLI entry point; return the exit code."""
logging.basicConfig(level=logging.INFO,
format="%(levelname)-5s %(message)s")
return cmd_publish(parse_args(argv), run_in_cwd, pypi_status)
if __name__ == "__main__":
sys.exit(main())
+119
View File
@@ -0,0 +1,119 @@
# publish specification
Complete description of `python/src/publish/publish.py`. Change this
file first, then tests, then code (SPEC items 6.11 and 6.12). Items
are cited as `publish spec item N.M`.
## 1. Purpose
- **1.1** `daedalus publish` releases the daedalus package itself:
it turns the checkout into a versioned, quality-checked
sdist + wheel pair in `dist/` and (with `--upload`) hands them
to PyPI via twine.
- **1.2** It exists so a release is one command with the
guards done for you: clean tree, exact tag, version not yet
on PyPI, tooling present in the running interpreter.
- **1.3** Credentials are never handled by this script: twine
reads `~/.pypirc` or prompts; nothing is recorded, forwarded,
or stored.
- **1.4** Runs from the daedalus checkout (editable pipx install
or the repository itself); there is no release from an
installed wheel copy - the tree is the source of truth.
## 2. Command
- **2.1** `daedalus publish [--upload]` - build and check the
release artifacts; `--upload` additionally uploads exactly this
version's artifacts to PyPI (section 3).
## 3. Behavior
- **3.1** Repo root: `pyproject.toml` found at three levels above
the script file (the `python/src/publish/` layout); missing is
exit 2.
- **3.2** Version: read from `[project] version` in that
`pyproject.toml` (tomllib); project name for PyPI checks from
`[project] name`. Artifact *file names* use the PEP 625
normalized name (lowercase, runs of `-._` collapsed to one
`_`, e.g. `daedalus-tools` -> `daedalus_tools-<version>.tar.gz`);
the PyPI JSON probe uses the project name as written.
- **3.3** Guards, in order, each stopping before anything is
built:
- **3.3.1** Dirty working tree (`git status --porcelain` in the
repo root, any output) is exit 3 - what ships must be what is
committed, and the tag must cover the exact tree.
- **3.3.2** `v<version>` not among the tags that point at HEAD
(`git tag --points-at HEAD`) is exit 4 - tag the release
first: `git tag -a v<version> -m ...`. Other tags on the
same commit (`latest`, `stable`) are fine; the guard checks
membership, not the name git happens to pick.
- **3.3.3** The interpreter must provide `python -m build` and
`python -m twine` (`--version` probe each); a failure is exit 5
with the inject hint (`pipx inject daedalus build twine`, or
the dev venv's `requirements.txt`).
- **3.3.4** `<name>` `<version>` already on PyPI
(`https://pypi.org/pypi/<name>/<version>/json` answering 200)
is exit 6 - a version, once published, is immutable; bump the
version. The probe runs through an injectable fetch; an
unreachable PyPI also stops with exit 6 (never publish blind).
- **3.4** Build: `python -m build` (sdist and wheel chained - the
sdist must be able to rebuild the wheel, SPEC item 9.2.1);
a failure is exit 7 with the troubleshooting pointer
(`python -m build --wheel` shows the error fastest).
- **3.5** Check: `python -m twine check dist/<name>-<version>*`;
anything twine dislikes is exit 8 - a README that will not
render blocks the release.
- **3.6** Without `--upload`, the run ends here: it prints the two
artifacts, the tag and version guard summary, and the `--upload`
command that would publish them. Exit 0.
- **3.7** With `--upload`: `python -m twine upload` over exactly
this version's sdist and wheel (never `dist/*` - stale artifacts
of other versions stay untouched and un-uploaded). Credentials:
twine prompts or reads `~/.pypirc` (API token as the username
`__token__`). Failure is exit 9; success prints the PyPI URL.
## 4. Exit codes
| Code | Meaning |
| --- | --- |
| 0 | checked (no `--upload`), or checked and uploaded |
| 2 | not run from a daedalus checkout (no pyproject.toml above) |
| 3 | dirty working tree |
| 4 | HEAD is not exactly tagged `v<version>` |
| 5 | build/twine tooling missing in this interpreter |
| 6 | version already on PyPI, or PyPI unreachable |
| 7 | build failed |
| 8 | twine check failed |
| 9 | twine upload failed |
## 5. Files written
- **5.1** `dist/` in the repo root: the version's sdist and wheel
(plus `build/` and egg-info that `python -m build` leaves
behind); nothing else. The script never touches `~/.pypirc`,
keychains, or tokens.
## 6. Testing approach
- **6.1** Tests live in `python/tests/test_publish.py`; no
network, no git state, no real build (daedalus agent rule 5.6):
every guard and step runs through an injected runner
`(cmd, cwd) -> (code, output)` and an injectable PyPI fetch;
the default runner shells out with cwd and the default fetch
reads the PyPI JSON URL with urllib (30 s timeout).
- **6.2** Covered groups: pyproject discovery and the version
read, each guard branch in order (dirty tree, tag mismatch,
tooling missing, already published, PyPI unreachable), the
chained build command, the twine check command, the upload
gate (`--upload` absent/present) and its exact artifact
selection, and the CLI wiring.
## 7. References
- **7.1** Packaging truth: SPEC items 9.1-9.5, 9.2.1.
- **7.2** Repository rules: SPEC items 6.6 (tests), 9.8 (version
bump).
- **7.3** History: `CHANGELOG.md` entries 0.12.0 (script),
0.12.1 (tag-guard fix, found by the first live run), 0.13.0
(PEP 625 artifact names; distribution renamed daedalus-tools
after PyPI refused the name daedalus).
File diff suppressed because it is too large Load Diff
+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.3.0"
assert hello.app_version() == "0.13.1"
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
+271
View File
@@ -0,0 +1,271 @@
"""Tests for the publish script: guarded PyPI release (publish spec).
No network, no git state, no real build: every guard and step runs
through an injected runner and an injectable PyPI status fetch
(daedalus agent rule 5.6, publish spec item 6.1).
"""
import re
from daedalus.publish import publish
def make_runner(script, calls=None):
"""Build an injectable run_cmd(cmd, cwd) from {prefix: (code, out)}."""
def run_cmd(cmd, cwd=None):
if calls is not None:
calls.append((list(cmd), cwd))
for prefix, reply in script.items():
if list(cmd)[:len(prefix)] == list(prefix):
return reply
raise AssertionError(f"unexpected command: {cmd}")
return run_cmd
def clean_runner(version, calls=None):
"""A runner with all guards green for `version`."""
py = publish.PY
return make_runner({
("git", "status"): (0, ""),
("git", "tag", "--points-at"): (0, f"v{version}\n"),
(py, "-m", "build", "--version"): (0, "build 1.6.1\n"),
(py, "-m", "twine", "--version"): (0, "twine 7.0.0\n"),
(py, "-m", "build"): (0, "Successfully built\n"),
(py, "-m", "twine", "check"): (0, "PASSED\n"),
(py, "-m", "twine", "upload"): (0, "Uploaded\n"),
}, calls)
# --- pyproject discovery (publish spec items 3.1-3.2)
def test_read_project_from_this_repo():
"""The script's own repo resolves: name daedalus, semver version."""
root = publish.find_repo_root()
assert root is not None
name, version = publish.read_project(root / "pyproject.toml")
assert name == "daedalus"
assert re.fullmatch(r"\d+\.\d+\.\d+", version)
# --- guards (publish spec item 3.3)
def test_dirty_tree_stops_before_building():
"""A dirty tree is exit 3; no build runs."""
name, version = publish.read_project(
publish.find_repo_root() / "pyproject.toml")
calls = []
runner = make_runner({("git", "status"): (0, " M file\n")}, calls)
args = publish.parse_args([])
assert publish.cmd_publish(args, runner,
lambda _u: 404) == 3
assert not any(cmd[:2] == ["git", "tag"]
or cmd[1:3] == ["-m", "build"]
for cmd, _cwd in calls)
def test_tag_mismatch_stops():
"""HEAD tagged with another version is exit 4."""
calls = []
runner = make_runner({
("git", "status"): (0, ""),
("git", "tag", "--points-at"): (0, "v0.0.1\n"),
}, calls)
args = publish.parse_args([])
assert publish.cmd_publish(args, runner,
lambda _u: 404) == 4
def test_tag_probe_failure_stops():
"""An untagged HEAD (no tag points at it) is exit 4."""
runner = make_runner({
("git", "status"): (0, ""),
("git", "tag", "--points-at"): (1, ""),
})
assert publish.cmd_publish(publish.parse_args([]), runner,
lambda _u: 404) == 4
def test_moving_tags_on_the_same_commit_do_not_confuse_the_guard():
"""`latest` sharing the release commit is fine (item 3.3.2).
git's own name picking is not the contract; v<version>
among the tags that point at HEAD is. Live case: git
prints `latest` for a commit tagged both latest and
v<version>.
"""
calls = []
runner = make_runner({
("git", "status"): (0, ""),
("git", "tag", "--points-at"):
(0, f"latest\nv{repo_version()}\n"),
(publish.PY, "-m", "build", "--version"): (0, "build\n"),
(publish.PY, "-m", "twine", "--version"): (0, "twine\n"),
(publish.PY, "-m", "build"): (0, "ok\n"),
(publish.PY, "-m", "twine", "check"): (0, "PASSED\n"),
}, calls)
assert publish.cmd_publish(publish.parse_args([]), runner,
lambda _u: 404) == 0
tag_calls = [cmd for cmd, _ in calls
if cmd[:2] == ["git", "tag"]]
assert tag_calls == [["git", "tag", "--points-at", "HEAD"]]
def repo_version():
"""The version the checkout's pyproject carries."""
_name, version = publish.read_project(
publish.find_repo_root() / "pyproject.toml")
return version
def test_tooling_missing_stops():
"""No build/twine in the interpreter is exit 5."""
runner = make_runner({
("git", "status"): (0, ""),
("git", "tag", "--points-at"): (0, f"v{repo_version()}\n"),
(publish.PY, "-m", "build", "--version"): (127, "no module"),
(publish.PY, "-m", "twine", "--version"): (0, "twine\n"),
})
assert publish.cmd_publish(publish.parse_args([]), runner,
lambda _u: 404) == 5
def test_already_on_pypi_stops():
"""A published version is exit 6 before any artifact is built."""
calls = []
runner = make_runner({
("git", "status"): (0, ""),
("git", "tag", "--points-at"): (0, f"v{repo_version()}\n"),
(publish.PY, "-m", "build", "--version"): (0, "build\n"),
(publish.PY, "-m", "twine", "--version"): (0, "twine\n"),
}, calls)
assert publish.cmd_publish(publish.parse_args([]), runner,
lambda _u: 200) == 6
assert not any(cmd[1:3] == ["-m", "build"] and len(cmd) == 3
for cmd, _ in calls)
def test_pypi_unreachable_stops():
"""A blind publish is refused: unreachable PyPI is exit 6."""
runner = make_runner({
("git", "status"): (0, ""),
("git", "tag", "--points-at"): (0, f"v{repo_version()}\n"),
(publish.PY, "-m", "build", "--version"): (0, "build\n"),
(publish.PY, "-m", "twine", "--version"): (0, "twine\n"),
})
assert publish.cmd_publish(publish.parse_args([]), runner,
lambda _u: None) == 6
# --- build, check, upload (publish spec items 3.4-3.7)
def test_check_only_flow_builds_and_stops(tmp_path, capsys):
"""Without --upload: chained build, twine check, exit 0."""
name, version = publish.read_project(
publish.find_repo_root() / "pyproject.toml")
sdist, wheel = publish.artifact_names(name, version)
calls = []
assert publish.cmd_publish(publish.parse_args([]),
clean_runner(version, calls),
lambda _u: 404) == 0
build = [cmd for cmd, _ in calls
if cmd[1:3] == ["-m", "build"] and len(cmd) == 3]
assert len(build) == 1 # chained, not two runs
assert not any(cmd[3:4] == ["upload"] for cmd, _ in calls)
out = capsys.readouterr().out
assert f"{sdist}" in out
assert "--upload" in out # the next-step hint
def test_upload_sends_exactly_this_version():
"""--upload passes only this version's sdist and wheel."""
name, version = publish.read_project(
publish.find_repo_root() / "pyproject.toml")
sdist, wheel = publish.artifact_names(name, version)
calls = []
assert publish.cmd_publish(publish.parse_args(["--upload"]),
clean_runner(version, calls),
lambda _u: 404) == 0
upload = [cmd for cmd, _ in calls if cmd[3:4] == ["upload"]][0]
assert upload[-2] == f"dist/{sdist}"
assert upload[-1] == f"dist/{wheel}"
def test_artifact_names_normalize_pep625():
"""Filenames use the normalized name, not the project name."""
sdist, wheel = publish.artifact_names("daedalus-tools", "0.13.0")
assert sdist == "daedalus_tools-0.13.0.tar.gz"
assert wheel == "daedalus_tools-0.13.0-py3-none-any.whl"
assert publish.artifact_names("daedalus", "1.0") == \
("daedalus-1.0.tar.gz", "daedalus-1.0-py3-none-any.whl")
def test_build_failure_is_7():
"""A failed chained build is exit 7."""
name, version = publish.read_project(
publish.find_repo_root() / "pyproject.toml")
py = publish.PY
runner = make_runner({
("git", "status"): (0, ""),
("git", "tag", "--points-at"): (0, f"v{version}\n"),
(py, "-m", "build", "--version"): (0, "build\n"),
(py, "-m", "twine", "--version"): (0, "twine\n"),
(py, "-m", "build"): (1, "error\n"),
})
assert publish.cmd_publish(publish.parse_args([]), runner,
lambda _u: 404) == 7
def test_check_failure_is_8():
"""twine check rejecting the artifacts is exit 8."""
name, version = publish.read_project(
publish.find_repo_root() / "pyproject.toml")
py = publish.PY
runner = make_runner({
("git", "status"): (0, ""),
("git", "tag", "--points-at"): (0, f"v{version}\n"),
(py, "-m", "build", "--version"): (0, "build\n"),
(py, "-m", "twine", "--version"): (0, "twine\n"),
(py, "-m", "build"): (0, "ok\n"),
(py, "-m", "twine", "check"): (1, "Failed\n"),
})
assert publish.cmd_publish(publish.parse_args([]), runner,
lambda _u: 404) == 8
def test_upload_failure_is_9():
"""twine upload failing is exit 9."""
name, version = publish.read_project(
publish.find_repo_root() / "pyproject.toml")
py = publish.PY
runner = make_runner({
("git", "status"): (0, ""),
("git", "tag", "--points-at"): (0, f"v{version}\n"),
(py, "-m", "build", "--version"): (0, "build\n"),
(py, "-m", "twine", "--version"): (0, "twine\n"),
(py, "-m", "build"): (0, "ok\n"),
(py, "-m", "twine", "check"): (0, "PASSED\n"),
(py, "-m", "twine", "upload"): (1, "403\n"),
})
assert publish.cmd_publish(publish.parse_args(["--upload"]), runner,
lambda _u: 404) == 9
def test_cli_wires_flow(monkeypatch):
"""The CLI hands cmd_publish the real runner and fetch."""
seen = {}
def fake_publish(args, run_cmd, fetch_status):
seen["args"] = args
seen["run_cmd"] = run_cmd
seen["fetch"] = fetch_status
return 0
monkeypatch.setattr(publish, "cmd_publish", fake_publish)
assert publish.main(["--upload"]) == 0
assert seen["args"].upload is True
assert seen["run_cmd"] is publish.run_in_cwd
assert seen["fetch"] is publish.pypi_status
+2
View File
@@ -6,3 +6,5 @@ pyyaml>=6.0
shellcheck-py>=0.10
setuptools>=68
argcomplete>=3.3
build>=1.6
twine>=6.0