daedalus 0.1.0: scriptman spec update ported - categories, new listing format with colors, run_python_script child entry, daedalus_logging, daedalus.<folder> namespace imports; SPEC rewritten with stable item numbers

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
nvaldez
2026-11-18 21:13:57 +01:00
parent 792beca2c5
commit b71a513c36
19 changed files with 1606 additions and 202 deletions
+31 -9
View File
@@ -1,9 +1,9 @@
--- ---
name: daedalus-agent-rules name: daedalus-agent-rules
version: 1.0.0 version: 1.1.0
type: summary type: summary
created: 2026-11-11 created: 2026-11-11
updated: 2026-11-11 updated: 2026-11-18
tags: [agents, rules, scripts, cli] tags: [agents, rules, scripts, cli]
--- ---
@@ -116,7 +116,8 @@ pip install -e . # daedalus command runs the checkout
```text ```text
daedalus/ daedalus/
├── bin/ # Launchers: daedalus (bash), daedalus.bat ├── bin/ # Launchers: daedalus (bash), daedalus.bat
├── daedalus/ # CLI package: cli.py, registry.py, runners.py, tests/ ├── daedalus/ # CLI package: cli.py, registry.py, runners.py,
│ # run_python_script.py, daedalus_logging/, tests/
├── python/ ├── python/
│ ├── src/<name>/ # One folder per Python script │ ├── src/<name>/ # One folder per Python script
│ └── tests/ # pytest tests for python/src (and .ps1/.bat scripts) │ └── tests/ # pytest tests for python/src (and .ps1/.bat scripts)
@@ -148,6 +149,9 @@ Before writing anything, know:
- The type: Python, bash, PowerShell, or batch. Prefer Python when the - The type: Python, bash, PowerShell, or batch. Prefer Python when the
script must run on both Windows and Linux. script must run on both Windows and Linux.
- A one-line description for `daedalus --list`. - A one-line description for `daedalus --list`.
- The categories the script belongs to. The default is `general`; pick
labels that say where the script fits (`media`, `linux`, ...). A label
may never equal a script name.
Ask the user only when the name or the type cannot be inferred. Track the Ask the user only when the name or the type cannot be inferred. Track the
work with this checklist: work with this checklist:
@@ -157,6 +161,7 @@ work with this checklist:
- [ ] Entry added to SCRIPTS in daedalus/registry.py - [ ] Entry added to SCRIPTS in daedalus/registry.py
- [ ] README row and usage section - [ ] README row and usage section
- [ ] Tests written and passing - [ ] Tests written and passing
- [ ] daedalus.<folder> entry in pyproject.toml (Python scripts)
- [ ] version bumped in pyproject.toml - [ ] version bumped in pyproject.toml
- [ ] python autotest.py passes - [ ] python autotest.py passes
- [ ] daedalus <name> --help works - [ ] daedalus <name> --help works
@@ -175,6 +180,7 @@ marked "test".
| Name matches `^[a-z][a-z0-9_-]*$` | Registry test | | Name matches `^[a-z][a-z0-9_-]*$` | Registry test |
| `path` is repo-relative with forward slashes | Registry test | | `path` is repo-relative with forward slashes | Registry test |
| `description` is one non-empty line | Registry test | | `description` is one non-empty line | Registry test |
| `categories` are non-empty labels, none equal to a script name | Registry test |
| File suffix has a runner (`.py`, `.sh`, `.ps1`, `.bat`) | Registry test | | File suffix has a runner (`.py`, `.sh`, `.ps1`, `.bat`) | Registry test |
| A row for the name in the README "Available scripts" table | Registry test | | A row for the name in the README "Available scripts" table | Registry test |
| Own tests for the script's logic | Review, coverage | | Own tests for the script's logic | Review, coverage |
@@ -185,7 +191,7 @@ marked "test".
| Type | Location | Runner | | Type | Location | Runner |
| --- | --- | --- | | --- | --- | --- |
| Python | `python/src/<name>/<name>.py` | Current Python, `python/src` on `PYTHONPATH` | | Python | `python/src/<name>/<name>.py` | `DAEDALUS_PYTHON` or current Python, via `run_python_script.py` |
| bash | `bash/<name>.sh` | `DAEDALUS_BASH`, Git Bash, then `bash` | | bash | `bash/<name>.sh` | `DAEDALUS_BASH`, Git Bash, then `bash` |
| PowerShell | `powershell/<name>.ps1` | `pwsh`, then `powershell` | | PowerShell | `powershell/<name>.ps1` | `pwsh`, then `powershell` |
| Batch | `batch/<name>.bat` | `cmd /c`, Windows only | | Batch | `batch/<name>.bat` | `cmd /c`, Windows only |
@@ -242,7 +248,13 @@ if __name__ == "__main__":
- `prog="<name>"` makes `--help` show the daedalus command name. - `prog="<name>"` makes `--help` show the daedalus command name.
- Shared helpers go in their own package under `python/src/`; scripts - Shared helpers go in their own package under `python/src/`; scripts
import them directly because `python/src` is on `PYTHONPATH`. import them as `daedalus.<folder>` (SPEC section 10). The child gets
`REPO_ROOT` on `PYTHONPATH`, so the import works in a checkout and an
install alike.
- Python scripts run through `run_python_script.py` and get the
`daedalus_logging` setup (file `~/.daedalus/debug.log` + stderr,
`DAEDALUS_LOGLEVEL`, `DAEDALUS_NO_LOGGING`) unless they configure
logging themselves.
- Standard library only. Lazy `%` logging. Type hints in every docstring. - Standard library only. Lazy `%` logging. Type hints in every docstring.
bash template: bash template:
@@ -290,16 +302,23 @@ sorted:
"<name>": Script( "<name>": Script(
path="python/src/<name>/<name>.py", path="python/src/<name>/<name>.py",
description="<one line, same as README>", description="<one line, same as README>",
categories="<label>", # or a tuple; default is "general"
), ),
``` ```
Do not edit `cli.py` or `runners.py`. The suffix picks the runner. Do not edit `cli.py` or `runners.py`. The suffix picks the runner.
For a Python script, also add the folder to `pyproject.toml` as an
installed package (SPEC section 9): entries `"daedalus.<folder>"` in
`[tool.setuptools].packages` and
`"daedalus.<folder>" = "python/src/<folder>"` in
`[tool.setuptools.package-dir]`.
In `README.md`: In `README.md`:
- Add a row to the "Available scripts" table, sorted by name: - Add a row to the "Available scripts" table, sorted by name:
`` | `<name>` | Python | <description> | ``. The registry test looks `` | `<name>` | Python | <categories> | <description> | ``. The
for the exact text `` | `<name>` | ``. registry test looks for the exact text `` | `<name>` | ``.
- When the script takes arguments, add a `### <name>` section after the - When the script takes arguments, add a `### <name>` section after the
table: what it does, example `daedalus <name> ...` calls in a `bash` table: what it does, example `daedalus <name> ...` calls in a `bash`
block, and an argument table. Follow the existing sections, if any. block, and an argument table. Follow the existing sections, if any.
@@ -308,7 +327,7 @@ In `README.md`:
| Type | Test file | How | | Type | Test file | How |
| --- | --- | --- | | --- | --- | --- |
| Python | `python/tests/test_<name>.py` | `from <name> import <name>`, call functions and `main([...])` | | Python | `python/tests/test_<name>.py` | `from daedalus.<name> import <name>`, call functions and `main([...])` |
| bash | `bash/tests/test_<name>.py` | `subprocess.run` with `runners.find_bash()`; skip when bash is missing | | bash | `bash/tests/test_<name>.py` | `subprocess.run` with `runners.find_bash()`; skip when bash is missing |
| PowerShell, batch | `python/tests/test_<name>.py` | `subprocess.run` via `runners.build_command`; skip when the interpreter or Windows is missing | | PowerShell, batch | `python/tests/test_<name>.py` | `subprocess.run` via `runners.build_command`; skip when the interpreter or Windows is missing |
@@ -323,7 +342,7 @@ Python test skeleton:
<what the tests cover>. <what the tests cover>.
""" """
from <name> import <name> from daedalus.<name> import <name>
def test_main_returns_zero(): def test_main_returns_zero():
@@ -428,6 +447,9 @@ disable a check to make a run pass.
- A script outside `python/src/`, `bash/`, `powershell/`, or `batch/`. - A script outside `python/src/`, `bash/`, `powershell/`, or `batch/`.
- Registry `path` with backslashes or an absolute path. - Registry `path` with backslashes or an absolute path.
- A runner chosen by anything other than the file suffix. - A runner chosen by anything other than the file suffix.
- A top-level import from `python/src` (use `daedalus.<folder>`;
SPEC section 10).
- A category label that equals a script name.
- A script that only works through daedalus (imports from `daedalus`, - A script that only works through daedalus (imports from `daedalus`,
reads `LIBRARY_ROOT`). reads `LIBRARY_ROOT`).
- Tests that need another machine, the network, or an interactive terminal without a - Tests that need another machine, the network, or an interactive terminal without a
+27
View File
@@ -10,6 +10,33 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and
- Nothing yet. - Nothing yet.
## [0.1.0] - 2026-11-18
### Added in 0.1.0
- Categories: `Script.categories` (default `general`),
`daedalus <category>` listing (AND when several) and
`daedalus <category>… <name>` runs; script names and category labels
never collide.
- New listing format: `Daedalus Version:` line, `script` / `type` /
`categories` table, descriptions wrapped to the terminal width and
indented, colors via `NO_COLOR` / `FORCE_COLOR`.
- `daedalus/run_python_script.py`: `.py` scripts run through a child
entry that sets up `sys.path`, logging, `sys.argv`, and exit codes.
- `daedalus.daedalus_logging`: file logging to `~/.daedalus/debug.log`
plus a colored stderr console handler (`DAEDALUS_LOGLEVEL`,
`DAEDALUS_NO_LOGGING`).
- Library imports: shared code imports as `daedalus.<folder>`; the
checkout registers `python/src/<folder>` as packages on import and the
child gets `REPO_ROOT` on `PYTHONPATH`.
- Exact error messages for every usage failure, with close matches after
a category prefix.
### Changed in 0.1.0
- `SPEC.md` rewritten with stable item numbers (`SPEC item 3.7.1`), in
lockstep with the upstream scriptman specification.
## [0.0.0] - 2026-11-11 ## [0.0.0] - 2026-11-11
### Added in 0.0.0 ### Added in 0.0.0
+32 -7
View File
@@ -88,16 +88,36 @@ pipx uninstall daedalus
## Usage ## Usage
```bash ```bash
daedalus --help # usage daedalus --help # usage
daedalus --list # list the available scripts daedalus [--list] # list the available scripts
daedalus NAME [args...] # run a script; every argument after NAME goes to it daedalus <name> [args...] # run a script; every argument after the name goes to it
daedalus --path NAME # print where the script file is daedalus <category> [category...] # list scripts that have every category
daedalus --version # print the installed version daedalus <category> <name> [args...] # run when the script has every category
daedalus --path <name> # print where the script file is
daedalus --version # print the installed version
``` ```
- `daedalus NAME --help` shows the help of the script, not of daedalus. - `daedalus NAME --help` shows the help of the script, not of daedalus.
- The exit code is the script's exit code. daedalus's own errors, such as - The exit code is the script's exit code. daedalus's own errors, such as
an unknown name, exit with 2 and suggest close matches. an unknown name, exit with 2 and suggest close matches.
- Listings print `Daedalus Version:`, a table of `script`, `type`, and
`categories`, and the wrapped description under each row. Colors follow
`NO_COLOR` / `FORCE_COLOR` and the terminal.
Environment variables:
| Variable | Effect |
| --- | --- |
| `DAEDALUS_PYTHON` | Interpreter for `.py` scripts (default: the interpreter running daedalus) |
| `DAEDALUS_BASH` | Override the bash used for `.sh` scripts |
| `DAEDALUS_LOGLEVEL` | Console log level for Python scripts (default `INFO`) |
| `DAEDALUS_NO_LOGGING` | Non-empty: Python scripts start without the daedalus logging setup |
| `NO_COLOR` / `FORCE_COLOR` | Colors on listings and console logs |
Python scripts run through `daedalus/run_python_script.py`: they get
`REPO_ROOT` on `PYTHONPATH` (so `import daedalus.<folder>` works for
shared code), file and console logging to `~/.daedalus/debug.log`, and
their `sys.argv` and exit code passed through unchanged.
## Add a script ## Add a script
@@ -108,11 +128,16 @@ an unknown name, exit with 2 and suggest close matches.
| bash | `bash/<name>.sh` | | bash | `bash/<name>.sh` |
| PowerShell | `powershell/<name>.ps1` | | PowerShell | `powershell/<name>.ps1` |
| Batch | `batch/<name>.bat` (CRLF line endings, Windows only) | | Batch | `batch/<name>.bat` (CRLF line endings, Windows only) |
- Register it in `SCRIPTS` in `daedalus/registry.py`. - Register it in `SCRIPTS` in `daedalus/registry.py` (set `categories`
when it belongs to a group such as `media` or `linux`; the default is
`general`).
- Add a row to the [Available scripts](./README.md#available-scripts) - Add a row to the [Available scripts](./README.md#available-scripts)
table in `README.md`. A test fails when a registered script is missing table in `README.md`. A test fails when a registered script is missing
from that table. from that table.
- Add tests under `python/tests/` or `bash/tests/`. - Add tests under `python/tests/` or `bash/tests/`. Python tests import
the script with `from daedalus.<name> import <name>`; a new
`python/src/<folder>/` also needs a matching `daedalus.<folder>`
entry in `pyproject.toml` (SPEC section 9).
- Bump `version` in `pyproject.toml`, then run `daedalus_pipx_install` - Bump `version` in `pyproject.toml`, then run `daedalus_pipx_install`
(or `pipx install --force` from the Git URL) so pipx picks up the change. (or `pipx install --force` from the Git URL) so pipx picks up the change.
- Run `python autotest.py`. - Run `python autotest.py`.
+8 -6
View File
@@ -4,7 +4,9 @@ Starter repository for daedalus:
one CLI, many small scripts, each with tests. one CLI, many small scripts, each with tests.
```bash ```bash
daedalus <name> [args...] daedalus <name> [args...] # run a script
daedalus <category> [category...] # list scripts in the categories (AND)
daedalus --list # list everything
``` ```
**[Install, usage, and development](./INSTALL.md)** · **[Install, usage, and development](./INSTALL.md)** ·
@@ -13,12 +15,12 @@ daedalus <name> [args...]
## Available scripts ## Available scripts
| Script | Type | What it does | | Script | Type | Categories | What it does |
| --- | --- | --- | | --- | --- | --- | --- |
| *(none yet)* | — | Add scripts per [AGENTS section 5](./AGENTS.md#5-integrating-a-script) or [SPEC section 6](./SPEC.md#6-adding-a-script). | | *(none yet)* | — | — | Add scripts per [AGENTS section 5](./AGENTS.md#5-integrating-a-script) or [SPEC section 6](./SPEC.md#6-adding-a-script). |
`daedalus --list` prints every registered name for the version you have `daedalus --list` prints the version, a `script` / `type` / `categories`
installed. table, and each description wrapped under its row.
## Getting started ## Getting started
+481 -119
View File
@@ -1,8 +1,15 @@
# daedalus specification # daedalus specification
How this repository is laid out, how scripts are registered and run, and How this repository is laid out, how scripts are registered and run, and
the rules for maintaining it. Change this file first when the behavior the rules for maintaining it. This file alone is enough to rebuild the
changes, then change the code and tests to match. tool: it states every observable behavior (arguments, output, exit codes,
environment variables, files written, packaging, checks). Change this file
first when the behavior changes, then change the code and tests to match.
This checkout is an **empty template**: the CLI and quality gates are
ready; add scripts per section 6.
<!-- toc-start: headings 2..6 -->
- [1. Purpose](#1-purpose) - [1. Purpose](#1-purpose)
- [2. Layout](#2-layout) - [2. Layout](#2-layout)
@@ -13,201 +20,552 @@ changes, then change the code and tests to match.
- [7. Quality gates](#7-quality-gates) - [7. Quality gates](#7-quality-gates)
- [8. Conventions](#8-conventions) - [8. Conventions](#8-conventions)
- [9. Packaging](#9-packaging) - [9. Packaging](#9-packaging)
- [10. Implementation plan](#10-implementation-plan) - [10. Library imports](#10-library-imports)
- [11. Logging for Python scripts](#11-logging-for-python-scripts)
- [12. Implementation plan](#12-implementation-plan)
<!-- toc-end -->
## 1. Purpose ## 1. Purpose
This repository is an **empty template**: the CLI and quality gates are - **1.1** Every heading and list item has a stable id. Cite an item as
ready; add scripts per section 6. A filled checkout keeps loose scripts in `SPEC item 3.7.1`. New items get the next free number; numbers of
one repository, each with tests, and runs any of them through one command: removed items are not reused.
- **1.2** daedalus keeps loose personal scripts in one repository, each
with tests, and runs any of them through one command:
```text ```text
daedalus <name> [args...] daedalus <name> [args...]
daedalus <category> [category...] list scripts (AND when multiple)
daedalus <category>… <name> [args...] run when the script has every category
``` ```
The same checkout is used on a Windows workstation and on a Linux host. In this template checkout, `SCRIPTS` is empty until the first script is
added (section 6).
- **1.3** The same tool runs on a Windows workstation and on a Linux
host, either installed with pipx (section 9) or run from a checkout
(SPEC item 3.7.2).
- **1.4** Scripts are written in Python, bash, PowerShell, or batch. The
CLI picks the interpreter from the file suffix and passes arguments,
terminal, and exit code straight through.
- **1.5** The CLI itself uses only the Python standard library. Python
3.11 or newer.
## 2. Layout ## 2. Layout
- **2.1** Repository tree:
```text ```text
daedalus/ daedalus/
├── bin/ ├── bin/
│ ├── daedalus # Linux launcher (bash), no install needed │ ├── daedalus # Linux launcher (bash), no install needed
│ └── daedalus.bat # Windows launcher (cmd / PowerShell) │ └── daedalus.bat # Windows launcher (cmd / PowerShell)
├── daedalus/ # The CLI package ├── daedalus/ # The CLI package
│ ├── __main__.py # python -m daedalus │ ├── __init__.py # PACKAGE_DIR, REPO_ROOT, LIBRARY_ROOT, checkout imports
│ ├── cli.py # Argument handling, list, path, dispatch │ ├── __main__.py # python -m daedalus
│ ├── registry.py # SCRIPTS: name -> Script │ ├── cli.py # Argument handling, list, path, dispatch
│ ├── runners.py # Suffix -> interpreter command │ ├── registry.py # Script, SCRIPTS, category helpers
│ ├── runners.py # Suffix -> interpreter command, run
│ ├── run_python_script.py # Child entry for .py scripts (logging, argv)
│ ├── daedalus_logging/ # File + console logging (section 11)
│ └── tests/ │ └── tests/
├── python/ ├── python/
│ ├── src/<name>/ # Python scripts, one folder per script │ ├── src/<name>/ # Python scripts, one folder per script
│ └── tests/ # pytest tests for python/src │ └── tests/ # pytest tests for python/src, .ps1, .bat
├── bash/ # *.sh scripts ├── bash/ # *.sh scripts
│ └── tests/ # pytest tests that run them │ └── tests/ # pytest tests that run them
├── powershell/ # *.ps1 scripts ├── powershell/ # *.ps1 scripts
├── batch/ # *.bat scripts ├── batch/ # *.bat scripts (CRLF)
├── ci/ # Sanity, syntax, and lint checks, with tests ├── ci/ # sanity.py, checks.py, with tests
├── autotest.py # Runs every check (local and CI) ├── autotest.py # Runs every check (local and CI)
├── README.md # Script catalog (user-facing) ├── pyproject.toml # Package, version, entry point, package data
├── INSTALL.md # Install, usage, development ├── requirements.txt # Test and lint tools
└── SPEC.md # This file ├── .gitea/workflows/ci.yml # CI job that runs autotest.py
├── .gitattributes # LF everywhere, CRLF for *.bat
├── .editorconfig # UTF-8, LF, final newline, 4 spaces (2 for yml/json/md)
├── CHANGELOG.md # Release notes, newest first
├── README.md # Script catalog (user-facing)
├── INSTALL.md # Install, usage, development
├── AGENTS.md # Rules for AI agents
└── SPEC.md # This file
``` ```
- **2.2** Three paths are computed in `daedalus/__init__.py`:
- **2.2.1** `PACKAGE_DIR`: the resolved folder of the `daedalus`
package.
- **2.2.2** `REPO_ROOT`: the parent of `PACKAGE_DIR` (the checkout root,
or `site-packages` in an install).
- **2.2.3** `LIBRARY_ROOT`: see SPEC item 9.3.
## 3. Command line ## 3. Command line
| Call | Result | Exit code | | Call | Result | Exit code |
| --- | --- | --- | | --- | --- | --- |
| `daedalus <name> [args...]` | Runs the registered script with `args` passed through unchanged | The script's exit code | | `daedalus <name> [args...]` | Runs the registered script with `args` passed through unchanged | The script's exit code |
| `daedalus`, `daedalus -l`, `daedalus --list` | Prints every registered name, its type, and description | 0 | | `daedalus <category> [category...]` | Prints the version line, then scripts that have **every** listed category | 0 |
| `daedalus -h`, `daedalus --help` | Prints usage | 0 | | `daedalus <category>… <name> [args...]` | Runs `<name>` when it has every category prefix; same pass-through as the flat form | The script's exit code |
| `daedalus`, `daedalus -l`, `daedalus --list` | Prints the version line, then every script (SPEC item 3.3) | 0 |
| `daedalus -h`, `daedalus --help` | Prints usage (SPEC item 3.8) | 0 |
| `daedalus --path <name>` | Prints the absolute path of the script | 0 | | `daedalus --path <name>` | Prints the absolute path of the script | 0 |
| `daedalus --version` | Prints the installed version, or `project.version` from `pyproject.toml` in a checkout | 0 | | `daedalus --version` | Prints `daedalus <version>` (SPEC item 3.9) | 0 |
| Unknown name | Prints an error and close matches to stderr | 2 | | Unknown option, category, or script; script not in category | Prints an error and close matches to stderr | 2 |
| Script file missing, or no interpreter found | Prints the reason to stderr | 2 | | Script file missing, unsupported suffix, or no interpreter found | Prints the reason to stderr | 2 |
- Everything after `<name>` belongs to the script, including `--help`: - **3.1** Everything after the script name belongs to the script,
`daedalus my_tool --help` shows the help of `my_tool`. including `--help`; these forms show the script help:
- The script runs in the caller's current directory, with the caller's - **3.1.1** `daedalus sample_script --help`
stdin, stdout, and stderr, so interactive scripts work. - **3.1.2** `daedalus general sample_script --help`
- Ctrl+C reaches the script. daedalus waits for it to exit and returns its - **3.1.3** `daedalus media convert_video --help`
exit code. - **3.2** The flat form `daedalus <name>` stays valid; categories are
optional grouping.
- **3.3** Listing format (full list and category-filtered list):
- **3.3.1** First line `Daedalus Version: <version>`. When at least one
script is listed, a blank line and the table follow; otherwise nothing
follows.
- **3.3.2** The table has a header row `script`, `type`, `categories`,
then a rule row of `-` per column. Columns are left-aligned, padded to
the widest cell (header included) and separated by two spaces. The
`type` column is at least 4 wide.
- **3.3.3** One row per script, sorted by name. `type` is the file
suffix without the dot (`py`, `sh`, `ps1`, `bat`). `categories` is the
labels joined with a comma and a space (`media, linux`).
- **3.3.4** Under each row, the description is wrapped to the terminal
width (at least 40 columns; 80 when the width cannot be read), every
line indented by 8 spaces. Long words and hyphenated words are not
split.
- **3.3.5** Color: when enabled, the padded name cell is green
(`ESC[32m`), the type cell yellow (`ESC[33m`), the categories cell
bright blue (`ESC[94m`), each followed by `ESC[0m`.
- **3.3.6** Color is enabled when `NO_COLOR` is empty or unset and
either `FORCE_COLOR` is non-empty or stdout is a terminal. A non-empty
`NO_COLOR` always wins.
Ways to run the CLI: ```text
Daedalus Version: 0.1.0
- Install it with pip (section 9). `daedalus` is then on `PATH` script type categories
everywhere, with every registered script bundled. -------------------- ---- ------------------
- `bin/daedalus` (Linux) or `bin\daedalus.bat` (Windows). Add `bin/` to sample_script_name py general, linux
`PATH` to call plain `daedalus`. Needs no install. sample script description
- `python -m daedalus` from the repository root. ```
- **3.4** A token is treated as a **category** only when it matches a
category in use and is **not** also a registered script name (names and
category labels must not collide, SPEC item 4.3).
- **3.5** The script runs in the caller's current directory, with the
caller's stdin, stdout, and stderr, so interactive scripts work.
- **3.6** Ctrl+C reaches the script. daedalus waits for it to exit and
returns its exit code.
- **3.7** Ways to run the CLI:
- **3.7.1** Install it with pipx or pip (section 9). `daedalus` is then
on `PATH` everywhere, with every registered script bundled.
- **3.7.2** `bin/daedalus` (Linux) or `bin\daedalus.bat` (Windows). Add
`bin/` to `PATH` to call plain `daedalus`. Needs no install.
- **3.7.2.1** `bin/daedalus` resolves its own real path (following
symlinks), prepends the checkout root to `PYTHONPATH`, and `exec`s
`python3 -m daedalus "$@"`.
- **3.7.2.2** `bin\daedalus.bat` prepends `<bin>\..` to `PYTHONPATH`,
runs `python -m daedalus %*`, and exits with its `ERRORLEVEL`.
- **3.7.3** `python -m daedalus` from the repository root.
- **3.7.4** The installed command is the entry point
`daedalus = daedalus.cli:main`.
- **3.8** `--help` prints this text:
```text
usage: daedalus <name> [args...] run a script; args go to the script
daedalus <category> [category...] list scripts (AND when multiple)
daedalus <category>… <name> [args...] run when script has every category
daedalus [-l | --list] list all registered scripts
daedalus --path <name> print the path of a script
daedalus --version print the installed version
daedalus -h | --help show this help
```
- **3.9** The version is resolved in this order:
- **3.9.1** The installed distribution metadata for `daedalus`.
- **3.9.2** `project.version` from `REPO_ROOT/pyproject.toml` (a
checkout that is not installed).
- **3.9.3** The string `unknown`.
- **3.10** Argument resolution. Options are recognized only as the first
token:
```text
dispatch(argv):
if argv is empty or argv[0] in ("-l", "--list"): list(all scripts); return 0
if argv[0] in ("-h", "--help"): print usage; return 0
if argv[0] == "--version": print "daedalus " + version; return 0
if argv[0] == "--path":
require exactly one more token, else usage error
print absolute path of lookup(argv[1]) # file need not exist
return 0
if argv[0] starts with "-": usage error "unknown option"
prefix = leading tokens while is_category_label(token)
rest = remaining tokens
if prefix and rest is empty:
scripts = scripts having every label in prefix
if none: usage error "no scripts for categories"
list(scripts); return 0
if prefix: script = lookup_in(prefix, rest[0]); return run(script, rest[1:])
return run(lookup(argv[0]), argv[1:])
main(argv = sys.argv[1:]):
try dispatch(argv)
on usage or runner error: print "daedalus: <message>" to stderr; return 2
```
- **3.11** Error messages (each printed as `daedalus: <message>`):
| Case | Message |
| --- | --- |
| `--path` without exactly one name | `usage: daedalus --path <name>` |
| Unknown option | `unknown option '<opt>'; run 'daedalus --help'` |
| Unknown script, close matches exist | `unknown script '<name>'; did you mean: <m1>, <m2>` |
| Unknown script, no close match | `unknown script '<name>'; run 'daedalus --list'` |
| Categories match no script | `no scripts for categories: <a>, <b>` |
| Unknown script after a category prefix | `unknown script '<name>' for '<a b>'; did you mean: …` or `…; run 'daedalus <a b>'` |
| Script lacks a prefix category | `script '<name>' has categories '<x, y>', not [<missing>]; run 'daedalus <name>' or pick another prefix` |
- **3.12** Close matches are up to 3 names with similarity ratio at least
0.6 (Python `difflib.get_close_matches` defaults). After a category
prefix, only scripts in those categories are candidates.
## 4. Registry ## 4. Registry
`daedalus/registry.py` holds one dictionary: `daedalus/registry.py` holds one dictionary. In this template checkout it
is empty until the first script is added:
```python ```python
SCRIPTS: dict[str, Script] = { SCRIPTS: dict[str, Script] = {
"my_tool": Script( "<name>": Script(
path="python/src/my_tool/my_tool.py", path="python/src/<name>/<name>.py",
description="One-line summary for daedalus --list", description="One-line summary",
categories="general",
),
"<other_name>": Script(
path="bash/<other_name>.sh",
description="One-line summary",
categories=("category_a", "category_b"),
), ),
} }
``` ```
In this template checkout, `SCRIPTS` is empty until you add the first - **4.1** `Script` is a frozen (immutable) record:
script. - **4.1.1** `path` is relative to `LIBRARY_ROOT`, with forward slashes.
- **4.1.2** `description` is one line.
- `Script` is a frozen dataclass with `path` (repo-relative, forward - **4.1.3** `categories` is one or more labels, default `general`. A
slashes) and `description` (one line). string becomes a one-item tuple, a list becomes a tuple, and an empty
- The key is the command name: lowercase letters, digits, `_`, and `-`, list or tuple is rejected with `ValueError`.
starting with a letter. - **4.1.4** `absolute_path` is `LIBRARY_ROOT / path`.
- Names that start with `-` are reserved for daedalus options. - **4.1.5** `categories_display` is the labels joined with a comma and
- The runner is chosen from the suffix of `path`. No other field selects it. a space.
- Tests enforce, for every entry: the name is valid, the file exists, the - **4.2** The key is the command name and matches `^[a-z][a-z0-9_-]*$`.
suffix has a runner, and the description is not empty. - **4.3** Each category label uses the same pattern as script names. No
script name may equal any label in `used_categories()` (so
`daedalus media` is unambiguous).
- **4.4** Helpers:
- **4.4.1** `used_categories()`: the set of every label of every script.
- **4.4.2** `is_category_label(token)`: false when `token` is a script
name; otherwise true when it is in `used_categories()`.
- **4.4.3** `scripts_matching_categories(labels)`: scripts that have
every label (AND), sorted by name; all scripts when `labels` is empty.
- **4.5** Leading argv tokens that are category labels form a prefix; the
script must include **every** prefix label in `categories`.
- **4.6** Names that start with `-` are reserved for daedalus options.
- **4.7** The runner is chosen from the suffix of `path`. No other field
selects it.
- **4.8** Tests enforce, for every entry:
- **4.8.1** The name matches the pattern.
- **4.8.2** The file exists, and `path` has no backslash, does not start
with `/`, and resolves inside `LIBRARY_ROOT`.
- **4.8.3** The suffix has a runner.
- **4.8.4** The description is non-empty and has no newline.
- **4.8.5** Categories are non-empty and every label matches the
pattern; no script name equals a label.
- **4.8.6** `README.md` contains ``| `<name>` |``.
## 5. Runners ## 5. Runners
| Suffix | Command | Platforms | | Suffix | Command | Platforms |
| --- | --- | --- | | --- | --- | --- |
| `.py` | `<python> <path> args...` (`DAEDALUS_PYTHON` or daedalus's interpreter) | All | | `.py` | `<python> <PACKAGE_DIR>/run_python_script.py <path> args...` | All |
| `.sh` | `<bash> <path> args...` | All with bash | | `.sh` | `<bash> <path> args...` | All with bash |
| `.ps1` | `<pwsh or powershell> -NoProfile -ExecutionPolicy Bypass -File <path> args...` | All with PowerShell | | `.ps1` | `<pwsh or powershell> -NoProfile -ExecutionPolicy Bypass -File <path> args...` | All with PowerShell |
| `.bat` | `cmd /c <path> args...` | Windows only | | `.bat` | `<COMSPEC or cmd.exe> /c <path> args...` | Windows only |
- Python scripts get `python/src` prepended to `PYTHONPATH`, so they can - **5.1** Building the command, in order:
import shared modules from there. - **5.1.1** Look up the runner by the lowercased suffix. None found:
- Set `DAEDALUS_PYTHON` to a virtual-environment interpreter when a error `unsupported script type '<suffix>': <path>`.
script needs packages that are not in the pipx venv. - **5.1.2** The file must exist: else error `script not found: <path>`.
- bash lookup order: `DAEDALUS_BASH`, then Git Bash next to `git` on - **5.1.3** Find the interpreter (SPEC items 5.3 to 5.6), then append
Windows (`<git root>/bin/bash.exe`), then `bash` on `PATH`. On Windows, the script arguments unchanged.
`bash` on `PATH` is often the WSL launcher, which cannot open Windows - **5.2** `<python>` is `DAEDALUS_PYTHON` when set and non-empty, else
paths, so Git Bash comes first. the interpreter running daedalus. Set it to a virtual-environment
- PowerShell lookup order: `pwsh`, then `powershell`. interpreter when a script needs packages that are not in the pipx
- A missing interpreter or a `.bat` on a non-Windows host is an error with a environment daedalus was installed into.
clear message (exit code 2), never a silent skip. - **5.3** bash lookup order:
- **5.3.1** `DAEDALUS_BASH` when set and non-empty.
- **5.3.2** On Windows only: resolve `git` on `PATH`, then use
`<git root>/bin/bash.exe` when that file exists (`git` lives in
`<git root>/cmd/`).
- **5.3.3** `bash` on `PATH`. On Windows, `bash` on `PATH` is often the
WSL launcher, which cannot open Windows paths, so Git Bash comes first.
- **5.3.4** None: error `bash not found; install it or set DAEDALUS_BASH`.
- **5.4** PowerShell lookup order: `pwsh`, then `powershell` on `PATH`.
None: error `PowerShell not found; install pwsh`.
- **5.5** `.bat` on a non-Windows host: error
`<file name>: .bat scripts run on Windows only`.
- **5.6** Every error above exits daedalus with code 2 (SPEC item 3.10),
never a silent skip.
- **5.7** Running:
- **5.7.1** The child gets the caller's environment, with `REPO_ROOT`
(the folder that contains the `daedalus` package) prepended to
`PYTHONPATH` using the platform path separator. This applies to every
script type, so Python code started from a shell script can also
import `daedalus.*` (section 10).
- **5.7.2** The child inherits the current directory and the terminal
(stdin, stdout, stderr are not redirected).
- **5.7.3** daedalus waits for the child and returns its exit code.
When Ctrl+C interrupts the wait, it waits again and returns the
child's exit code.
- **5.8** `run_python_script.py <script.py> [args...]` runs in the child
process:
- **5.8.1** No arguments: print
`usage: run_python_script.py <script.py> [args...]` to stderr, exit 2.
- **5.8.2** Script path (resolved) is not a file: print
`script not found: <path>` to stderr, exit 2.
- **5.8.3** Put the parent of its own folder and its own folder at the
front of `sys.path` (when missing), so `import daedalus` works.
- **5.8.4** Unless `DAEDALUS_NO_LOGGING` is non-empty, configure
logging (section 11) with the console level from `DAEDALUS_LOGLEVEL`
(default `INFO`).
- **5.8.5** Set `sys.argv` to `[<script path>, *args]`, execute the file
as `__main__`, and restore `sys.argv` afterwards.
- **5.8.6** Exit code: 0 when the script returns normally or calls
`sys.exit()` / `sys.exit(None)`; the integer for `sys.exit(<int>)`;
1 for any other exit value. An uncaught exception prints a traceback
and exits 1.
## 6. Adding a script ## 6. Adding a script
- Put the file in the folder for its type (section 2). A Python script gets - **6.1** Put the file in the folder for its type (section 2). A Python
its own folder: `python/src/<name>/<name>.py`. script gets its own folder: `python/src/<name>/<name>.py`. The command
- The script must run on its own (`python python/src/<name>/<name>.py`) name, file stem, and (for Python) folder name are the same string.
without daedalus. Python scripts expose `main(argv: list[str] | None)` - **6.2** The script must run without daedalus.
and end with `if __name__ == "__main__": sys.exit(main())`. - **6.2.1** Python scripts expose `main(argv: list[str] | None)`.
- Add one entry to `SCRIPTS` in `daedalus/registry.py`. - **6.2.2** They end with
- Add a row to the "Available scripts" table in `README.md`, and a short `if __name__ == "__main__": sys.exit(main())`.
section with usage when the script takes arguments. A test fails when a - **6.2.3** Shared Python code is imported as `daedalus.<folder>`
registered name has no row. (section 10). A script that does so runs on its own when daedalus is
- Add tests: installed or the checkout root is on `PYTHONPATH`.
- Python: `python/tests/test_<name>.py`, importing with - **6.2.4** The script never imports the CLI modules (`cli`, `registry`,
`from <name> import <name>`. `runners`) and never reads `LIBRARY_ROOT`.
- bash: `bash/tests/test_<name>.py`, running the script with - **6.3** Add one entry to `SCRIPTS` in `daedalus/registry.py` (set
`categories` when the script belongs to media, linux, or other
groups).
- **6.4** Add a row to the "Available scripts" table in `README.md`
(columns Script, Type, Categories, What it does), and a short section
with usage when the script takes arguments.
- **6.4.1** A test fails when a registered name has no row.
- **6.5** A new `python/src/<folder>/` is added to `packages` and
`package-dir` in `pyproject.toml` as `daedalus.<folder>` (SPEC item
9.4), so installed code can import it.
- **6.6** Add tests:
- **6.6.1** Python: `python/tests/test_<name>.py`, importing with
`from daedalus.<name> import <name>`.
- **6.6.2** bash: `bash/tests/test_<name>.py`, running the script with
`subprocess` and skipping when bash is missing. `subprocess` and skipping when bash is missing.
- PowerShell and batch: a test under `python/tests/` that runs the - **6.6.3** PowerShell and batch: a test under `python/tests/` that runs
script, skipped when the interpreter or Windows is missing. the script, skipped when the interpreter or Windows is missing.
- Run `python autotest.py`. It must pass before pushing. - **6.7** Bump `version` in `pyproject.toml` and add a `CHANGELOG.md`
entry.
- **6.8** Run `python autotest.py`. It must pass before pushing.
## 7. Quality gates ## 7. Quality gates
`python autotest.py` runs every check; CI runs the same command. - **7.1** `python autotest.py [CHECK...]` runs the named checks (default:
all). An unknown name is an argument error (exit 2) listing the unknown
names.
- **7.2** Selected checks run concurrently in threads. Each returns an
error count; 0 is a pass. Failures are logged as
`ERROR [FAIL] <check detail>` while the checks run.
- **7.3** After all finish, autotest prints a summary and exits 1 when any
check failed, else 0:
```text
########################################
autotest results
########################################
[ PASS ] 0.42s sanity
[ FAIL ] 12.07s pytest
```
- **7.4** Run it before every commit; do not commit unless every check
passes ([AGENTS.md](./AGENTS.md) section 2.3).
- **7.5** File discovery walks the repository, skipping folders named
`.git`, `.venv`, `venv`, `.cache`, `.pytest_cache`, `.ruff_cache`,
`__pycache__`, `htmlcov`, `node_modules`, `build`, `dist`. Suffixes
match exactly.
| Check | Rule | | Check | Rule |
| --- | --- | | --- | --- |
| `sanity` | Changed files: line endings (section 8), no private keys, under 2 MB | | `sanity` | Changed files (SPEC item 7.6): line endings (section 8), no private key, at most 2,000,000 bytes |
| `python_syntax` | Every `*.py` parses | | `python_syntax` | Every `*.py` parses |
| `pycodestyle` | PEP 8 with the repository's ignore list (`PYCODESTYLE_IGNORE` in `ci/checks.py`) | | `pycodestyle` | PEP 8, ignoring `E501 E121 E123 E126 E226 E24 E704 W503 W504`; error count is the violation count |
| `shellcheck` | Every `*.sh`, `*.bash`, and suffixless file with a shell shebang | | `shellcheck` | `shellcheck --external-sources` on every `*.sh`, `*.bash`, and suffixless file whose first line matches `^#!.*\b(ba\|da\|k\|z)?sh\b`; a missing `shellcheck` fails each file |
| `json`, `yaml` | Every file loads | | `json` | Every `*.json` parses as UTF-8 JSON |
| `markdown` | markdownlint, MD013 and MD033 disabled | | `yaml` | Every document in every `*.yaml` / `*.yml` loads (safe loader) |
| `pytest` | All tests pass; coverage of `ci`, `daedalus`, and `python/src` at least `MIN_COVERAGE_PERCENT` | | `markdown` | PyMarkdown with the front-matter extension on every `*.md`; MD013 and MD033 ignored |
| `pytest` | `python -m pytest --cov=ci --cov=daedalus --cov=python/src --cov-report=term-missing:skip-covered --cov-fail-under=<MIN_COVERAGE_PERCENT>` in a subprocess |
- **7.6** Changed files for `sanity`:
- **7.6.1** Base ref: the first that resolves to a commit of
`SANITY_DIFF_BASE`, `origin/<target branch>`, `origin/main`,
`origin/master`.
- **7.6.2** With a base: files added, copied, modified, or renamed
against it (`git diff --name-only --diff-filter=ACMR <ref>`), plus
untracked files not ignored.
- **7.6.3** Without a base: every tracked and untracked, not ignored
file.
- **7.6.4** Deleted paths are skipped.
- **7.7** Sanity rules per file:
- **7.7.1** A file containing a NUL byte is binary and skips the line
ending rule.
- **7.7.2** `*.bat` fails when any `\n` is not preceded by `\r`. Any
other file fails when it contains `\r`.
- **7.7.3** A file fails when it contains
`-----BEGIN <uppercase words> PRIVATE KEY-----`.
- **7.8** `MIN_COVERAGE_PERCENT` in `autotest.py` is 75 and only goes up.
- **7.9** pytest configuration in `pyproject.toml`: test paths
`ci/tests`, `daedalus/tests`, `python/tests`, `bash/tests`; `.` on the
Python path; coverage omits `*/tests/*` and `*/__main__.py`.
- **7.10** CI (`.gitea/workflows/ci.yml`) runs one job on pull request
pipelines and on the default branch: a Python 3.11 image with git and
shellcheck, full git history (for SPEC item 7.6),
`pip install -r requirements.txt`, then `python autotest.py`. The
sanity diff base is passed as `SANITY_DIFF_BASE`.
- **7.11** `requirements.txt` holds the tools: `pytest`, `pytest-cov`,
`pycodestyle`, `pymarkdownlnt`, `pyyaml`, `shellcheck-py`, `setuptools`.
## 8. Conventions ## 8. Conventions
- Line endings are LF everywhere except `*.bat`, which must be CRLF: - **8.1** Line endings are LF everywhere except `*.bat`, which must be
cmd.exe mishandles labels and `goto` in LF-only batch files. CRLF.
`.gitattributes` enforces both on checkout. - **8.1.1** cmd.exe mishandles labels and `goto` in LF-only batch files.
- Python targets 3.11. Standard library imports use `import module`. - **8.1.2** `.gitattributes` enforces both on checkout.
Logging uses lazy `%` formatting. - **8.2** Python targets 3.11. Standard library imports use `import module`.
- Markdown lists use dashes. - **8.3** Logging uses lazy `%` formatting.
- `bin/daedalus` and every `*.sh` are committed executable: - **8.6** Markdown lists use dashes.
- **8.7** `bin/daedalus` and every `*.sh` are committed executable:
`git add --chmod=+x <file>`. `git add --chmod=+x <file>`.
- `MIN_COVERAGE_PERCENT` in `autotest.py` only goes up. Raise it when - **8.8** `MIN_COVERAGE_PERCENT` in `autotest.py` only goes up. Raise it
tests are added. when tests are added.
- **8.9** `CHANGELOG.md` follows Keep a Changelog, newest release first,
with release numbers equal to `version` in `pyproject.toml`.
## 9. Packaging ## 9. Packaging
`pyproject.toml` builds one wheel that holds the CLI and every script. - **9.1** `pyproject.toml` builds one wheel (setuptools 68 or newer) named
`daedalus` that holds the CLI and every script. It requires Python
3.11 or newer.
| Command | Use | | Command | Use |
| --- | --- | | --- | --- |
| `pipx install git+ssh://git@example.com/your-org/daedalus.git` | Own isolated environment, `daedalus` on `PATH` (recommended; works on Debian 12, where plain `pip install` is blocked) | | `pipx install git+https://example.com/your-org/daedalus.git` | Own isolated environment, `daedalus` on `PATH` (recommended; works on Debian 12, where plain `pip install` is blocked) |
| `pip install --user .` | From a checkout, into the user site | | `pip install --user .` | From a checkout, into the user site |
| `pip install -e .` | Development: the installed command runs the scripts in the checkout | | `pip install -e .` | Development: the installed command runs the scripts in the checkout |
| `pipx upgrade daedalus` / `pip install --upgrade .` | Pick up new scripts | | `pipx upgrade daedalus` / `pip install --upgrade .` | Pick up new scripts |
The script folders are copied into the wheel under - **9.2** The script folders are copied into the wheel under
`daedalus/_library/`, with the same relative paths as in the repository: `daedalus/_library/`, with the same relative paths as in the repository:
| Repository folder | Installed folder | Files | | Repository folder | Installed folder | Files |
| --- | --- | --- | | --- | --- | --- |
| `python/src/` | `daedalus/_library/python/src/` | Everything except `__pycache__` and `*.pyc` | | `python/src/` | `daedalus/_library/python/src/` | Everything except `__pycache__`, `*.pyc`, `.gitkeep` |
| `bash/` | `daedalus/_library/bash/` | `*.sh` | | `bash/` | `daedalus/_library/bash/` | `*.sh` |
| `powershell/` | `daedalus/_library/powershell/` | `*.ps1` | | `powershell/` | `daedalus/_library/powershell/` | `*.ps1` |
| `batch/` | `daedalus/_library/batch/` | `*.bat` | | `batch/` | `daedalus/_library/batch/` | `*.bat` |
- `LIBRARY_ROOT` in `daedalus/__init__.py` is `daedalus/_library` when - **9.3** `LIBRARY_ROOT` is `PACKAGE_DIR/_library` when that folder exists
that folder exists (a normal install), otherwise the repository root (a (a normal install), otherwise `REPO_ROOT` (a checkout or an editable
checkout or an editable install). Registry paths resolve against it, so install).
`SCRIPTS` entries are the same in both cases. - **9.3.1** Registry paths resolve against it, so `SCRIPTS` entries are
- Tests under `*/tests/` are not packaged. the same in both cases.
- The CLI has no runtime dependencies. Test and lint tools stay in - **9.4** Each `python/src/<folder>/` is also installed as the package
`requirements.txt`. `daedalus.<folder>` (an explicit `packages` and `package-dir` entry per
- A test builds the wheel and fails when any registered script is missing folder). `daedalus` and `daedalus.daedalus_logging` are packages too.
from it. The wheel therefore holds each Python script twice: the `_library` copy
- Bump `version` in `pyproject.toml` when scripts or the CLI change, so is what the CLI runs, the `daedalus.<folder>` copy is what imports
`pipx upgrade` picks them up. resolve to (section 10).
- **9.5** Tests under `*/tests/`, bytecode, and `.gitkeep` are not
packaged.
- **9.6** Runtime dependencies: none; the CLI uses only the standard
library. A script that needs third-party packages says so in its own
help text and fails with a clear message when they are missing;
`DAEDALUS_PYTHON` (SPEC item 5.2) points it at their environment.
Test and lint tools stay in `requirements.txt`.
- **9.7** Tests build the wheel from a copy of the checkout and check:
- **9.7.1** Every registered script is at `daedalus/_library/<path>`.
- **9.7.2** No `/tests/`, `*.pyc`, or `.gitkeep` entry is present.
- **9.7.3** The entry point `daedalus = daedalus.cli:main` is declared.
- **9.7.4** Unpacked on `PYTHONPATH`, `daedalus --path <name>` points
into `_library` for every registered `<name>`, `--list` lists it,
`<name> --help` runs, and every registered `daedalus.<folder>`
import resolves.
- **9.8** Bump `version` in `pyproject.toml` when scripts or the CLI
change, so `pipx upgrade` picks them up.
## 10. Implementation plan ## 10. Library imports
- **10.1** Library Python code imports shared modules under the
`daedalus` namespace, never as top-level names:
`from daedalus.<folder> import <module>`.
- **10.2** In an install, `daedalus.<folder>` is a real installed package
(SPEC item 9.4).
- **10.3** In a checkout, `import daedalus` registers every direct
subfolder of `REPO_ROOT/python/src` (except `__pycache__`) as a module
`daedalus.<folder>` whose package search path is that folder, unless a
module of that name is already loaded. Files are not copied.
```text
on import daedalus:
if REPO_ROOT/python/src is a folder:
for each subfolder F, sorted by name:
if "daedalus.F" not already loaded:
create empty package "daedalus.F" with search path [F]
```
- **10.4** `REPO_ROOT` on `PYTHONPATH` (SPEC item 5.7.1) and the
`sys.path` setup of `run_python_script.py` (SPEC item 5.8.3) make
`import daedalus` succeed in the child, under `DAEDALUS_PYTHON` too.
## 11. Logging for Python scripts
- **11.1** `daedalus.daedalus_logging.configure_logging()` is called by
`run_python_script.py` before the script starts (SPEC item 5.8.4).
Library scripts may call it too. It replaces any existing root handlers.
- **11.2** Root logger level is `DEBUG`, with two handlers:
- **11.2.1** File handler, appending UTF-8 to `~/.daedalus/debug.log`
(parent folders created), all levels, format
`%(asctime)s|%(levelname)-5.5s|%(module)s.%(funcName)s:%(lineno)d:%(message)s`,
date format `%Y-%m-%d %H:%M:%S`.
- **11.2.2** Console handler on stderr, level from
`DAEDALUS_LOGLEVEL` (a level name such as `DEBUG`, `INFO`,
`WARNING`), format `%(levelname)-5.5s|%(message)s`.
- **11.4** Console color is on when `NO_COLOR` is empty or unset and
either `FORCE_COLOR` is non-empty or stderr is a terminal.
- **11.5** With color on:
- **11.5.1** `WARNING` lines are yellow (`ESC[33m`), `ERROR` bold red
(`ESC[1;31m`), `CRITICAL` bold bright red (`ESC[1;91m`); the whole
line is colored and reset at the end. `DEBUG` and `INFO` are plain.
- **11.5.2** An IPv4 address in square brackets, `[10.0.0.1]` or a
range `[10.0.0.1 - 10.0.0.9]`, has its first address in bold blue
(`ESC[1;34m`); the line's level color resumes after it.
- **11.6** `configure_logging` accepts overrides for the log file path,
console level, file level, and color, and returns the resolved log
file path.
## 12. Implementation plan
| Step | Work | Status | | Step | Work | Status |
| --- | --- | --- | | --- | --- | --- |
@@ -225,3 +583,7 @@ The script folders are copied into the wheel under
| 12 | `daedalus --version` | Done | | 12 | `daedalus --version` | Done |
| 13 | Tests: `LIBRARY_ROOT` selection, wheel contains every registered script, installed CLI | Done | | 13 | Tests: `LIBRARY_ROOT` selection, wheel contains every registered script, installed CLI | Done |
| 14 | README: install with pipx or pip | Done | | 14 | README: install with pipx or pip | Done |
| 15 | Categories in `Script`, CLI `daedalus <category>` and `daedalus <category> <name>` | Done |
| 16 | `run_python_script.py` and `daedalus_logging` (section 11) | Done |
| 17 | `daedalus.<folder>` imports in checkouts and installs (section 10) | Done |
| 18 | Listing table with version line, wrapped descriptions, and color (SPEC item 3.3) | Done |
+36 -1
View File
@@ -1,8 +1,15 @@
"""daedalus: run any registered script with ``daedalus <name> [args...]``. """daedalus: run any registered script with ``daedalus <name> [args...]``.
CLI package; see SPEC.md. CLI package; see SPEC.md. On import this module also registers every
``python/src/<folder>`` as a ``daedalus.<folder>`` package so library
scripts can import shared code in checkout and install alike
(SPEC.md section 10).
""" """
from __future__ import annotations
import pathlib import pathlib
import sys
import types
PACKAGE_DIR = pathlib.Path(__file__).resolve().parent PACKAGE_DIR = pathlib.Path(__file__).resolve().parent
REPO_ROOT = PACKAGE_DIR.parent REPO_ROOT = PACKAGE_DIR.parent
@@ -15,3 +22,31 @@ def library_root(package_dir: pathlib.Path = PACKAGE_DIR) -> pathlib.Path:
LIBRARY_ROOT = library_root() LIBRARY_ROOT = library_root()
def register_source_folders(repo_root: pathlib.Path = REPO_ROOT) -> list[str]:
"""Register python/src subfolders as daedalus.<folder> packages (SPEC item 10.3).
Each subfolder becomes an empty package whose search path is that
folder, unless a module of that name is already loaded. Returns the
names registered, in order.
"""
source = repo_root / "python" / "src"
if not source.is_dir():
return []
registered: list[str] = []
for folder in sorted(source.iterdir()):
if not folder.is_dir() or folder.name.startswith((".", "_")):
continue # not a library script package (e.g. __pycache__)
name = f"daedalus.{folder.name}"
if name in sys.modules:
continue
module = types.ModuleType(name)
module.__path__ = [str(folder)]
module.__package__ = name
sys.modules[name] = module
registered.append(name)
return registered
register_source_folders(REPO_ROOT)
+115 -17
View File
@@ -6,35 +6,96 @@ from __future__ import annotations
import difflib import difflib
import importlib.metadata import importlib.metadata
import os
import shutil
import sys import sys
import textwrap
import tomllib import tomllib
from daedalus import REPO_ROOT from daedalus import REPO_ROOT
from daedalus import registry from daedalus import registry
from daedalus import runners from daedalus import runners
USAGE = """usage: daedalus <name> [args...] run a script; args go to the script USAGE = """usage: daedalus <name> [args...] run a script; args go to the script
daedalus [-l | --list] list registered scripts daedalus <category> [category...] list scripts (AND when multiple)
daedalus --path <name> print the path of a script daedalus <category>… <name> [args...] run when script has every category
daedalus --version print the installed version daedalus [-l | --list] list all registered scripts
daedalus -h | --help show this help""" daedalus --path <name> print the path of a script
daedalus --version print the installed version
daedalus -h | --help show this help"""
TYPE_COLUMN_MIN_WIDTH = 4
DESCRIPTION_INDENT = " " * 8
MIN_WRAP_WIDTH = 40
NAME_COLOR = "\033[32m"
TYPE_COLOR = "\033[33m"
CATEGORIES_COLOR = "\033[94m"
RESET = "\033[0m"
class UsageError(Exception): class UsageError(Exception):
"""Bad daedalus arguments or an unknown script name.""" """Bad daedalus arguments or an unknown script name."""
def colors_enabled(stream=None) -> bool:
"""NO_COLOR unset/empty and (FORCE_COLOR or a terminal): SPEC item 3.3.6."""
stream = sys.stdout if stream is None else stream
if os.environ.get("NO_COLOR"):
return False
if os.environ.get("FORCE_COLOR"):
return True
return stream.isatty()
def _cell(text: str, width: int, color: str) -> str:
"""One left-aligned table cell: text, color, reset (SPEC item 3.3.2, 3.3.5)."""
padded = f"{text:<{width}}"
return f"{color}{padded}{RESET}" if colors_enabled() else padded
def _column(items: list[str], minimum: int = 1) -> int:
"""Widest cell with the header included, floor at minimum (SPEC item 3.3.2)."""
return max([minimum, *(len(item) for item in items)])
def _wrapped_description(description: str, width: int) -> list[str]:
"""Description wrapped to the terminal width, indented 8 (SPEC item 3.3.4)."""
wrapper = textwrap.TextWrapper(width=width, break_long_words=False,
break_on_hyphens=False,
initial_indent=DESCRIPTION_INDENT,
subsequent_indent=DESCRIPTION_INDENT)
return wrapper.wrap(description)
def format_list(scripts: dict[str, registry.Script]) -> str: def format_list(scripts: dict[str, registry.Script]) -> str:
"""One aligned line per script: name, type, description.""" """Version line, then the script table with wrapped descriptions (SPEC item 3.3)."""
width = max((len(name) for name in scripts), default=0) lines = [f"Daedalus Version: {version()}"]
return "\n".join( if not scripts:
f"{name:<{width}} {script.absolute_path.suffix.lstrip('.'):<3} {script.description}" return lines[0]
for name, script in sorted(scripts.items()) lines.append("")
) entries = sorted(scripts.items())
name_width = _column(["script", *[name for name, _ in entries]])
type_width = _column(["type", *[script.absolute_path.suffix.lstrip(".") for _, script in entries]],
TYPE_COLUMN_MIN_WIDTH)
categories_width = _column(["categories", *[script.categories_display for _, script in entries]])
lines.append(f"{'script':<{name_width}} {'type':<{type_width}}"
f" {'categories':<{categories_width}}")
lines.append(f"{'-' * name_width} {'-' * type_width} {'-' * categories_width}")
for name, script in entries:
suffix = script.absolute_path.suffix.lstrip(".")
lines.append(" ".join([
_cell(name, name_width, NAME_COLOR),
_cell(suffix, type_width, TYPE_COLOR),
_cell(script.categories_display, categories_width, CATEGORIES_COLOR),
]))
wrap_width = max(MIN_WRAP_WIDTH, shutil.get_terminal_size().columns)
lines.extend(_wrapped_description(script.description, wrap_width))
return "\n".join(lines)
def version() -> str: def version() -> str:
"""Installed metadata, else version from checkout pyproject.toml.""" """Installed metadata, else version from checkout pyproject.toml (SPEC item 3.9)."""
try: try:
return importlib.metadata.version("daedalus") return importlib.metadata.version("daedalus")
except importlib.metadata.PackageNotFoundError: except importlib.metadata.PackageNotFoundError:
@@ -47,18 +108,43 @@ def version() -> str:
return "unknown" return "unknown"
def _close_matches(name: str, candidates: list[str]) -> list[str]:
"""Up to 3 names with similarity at least 0.6 (SPEC item 3.12)."""
return difflib.get_close_matches(name, candidates, n=3)
def lookup(name: str) -> registry.Script: def lookup(name: str) -> registry.Script:
"""Registered script by name; UsageError with close matches otherwise.""" """Registered script by name; UsageError with close matches otherwise (SPEC item 3.11)."""
script = registry.SCRIPTS.get(name) script = registry.SCRIPTS.get(name)
if script is not None: if script is not None:
return script return script
matches = difflib.get_close_matches(name, registry.SCRIPTS, n=3) matches = _close_matches(name, list(registry.SCRIPTS))
hint = f"did you mean: {', '.join(matches)}" if matches else "run 'daedalus --list'" hint = f"did you mean: {', '.join(matches)}" if matches else "run 'daedalus --list'"
raise UsageError(f"unknown script {name!r}; {hint}") raise UsageError(f"unknown script {name!r}; {hint}")
def lookup_in(prefix: list[str], name: str) -> registry.Script:
"""A script inside the prefix categories; UsageError otherwise (SPEC item 3.11)."""
matching = registry.scripts_matching_categories(prefix)
script = matching.get(name)
if script is not None:
return script
joined = " ".join(prefix)
if name in registry.SCRIPTS:
script = registry.SCRIPTS[name]
missing = [label for label in prefix if label not in script.categories]
raise UsageError(f"script '{name}' has categories '{script.categories_display}', "
f"not [{', '.join(missing)}]; run 'daedalus {name}' "
"or pick another prefix")
matches = _close_matches(name, list(matching))
if matches:
raise UsageError(f"unknown script '{name}' for '{joined}'; "
f"did you mean: {', '.join(matches)}")
raise UsageError(f"unknown script '{name}' for '{joined}'; run 'daedalus {joined}'")
def dispatch(argv: list[str]) -> int: def dispatch(argv: list[str]) -> int:
"""Handle daedalus options, or run the named script with the rest of argv.""" """Handle daedalus options, categories, or run a script (SPEC item 3.10)."""
if not argv or argv[0] in ("-l", "--list"): if not argv or argv[0] in ("-l", "--list"):
print(format_list(registry.SCRIPTS)) print(format_list(registry.SCRIPTS))
return 0 return 0
@@ -75,11 +161,23 @@ def dispatch(argv: list[str]) -> int:
return 0 return 0
if argv[0].startswith("-"): if argv[0].startswith("-"):
raise UsageError(f"unknown option {argv[0]!r}; run 'daedalus --help'") raise UsageError(f"unknown option {argv[0]!r}; run 'daedalus --help'")
return runners.run(lookup(argv[0]).absolute_path, argv[1:]) prefix: list[str] = []
rest = list(argv)
while rest and registry.is_category_label(rest[0]):
prefix.append(rest.pop(0))
if prefix and not rest:
scripts = registry.scripts_matching_categories(prefix)
if not scripts:
raise UsageError(f"no scripts for categories: {', '.join(prefix)}")
print(format_list(scripts))
return 0
if prefix:
return runners.run(lookup_in(prefix, rest[0]).absolute_path, rest[1:])
return runners.run(lookup(rest[0]).absolute_path, rest[1:])
def main(argv: list[str] | None = None) -> int: def main(argv: list[str] | None = None) -> int:
"""CLI entry point; daedalus errors exit with 2.""" """CLI entry point; daedalus errors exit with 2 (SPEC item 3.10)."""
try: try:
return dispatch(sys.argv[1:] if argv is None else argv) return dispatch(sys.argv[1:] if argv is None else argv)
except (UsageError, runners.RunnerError) as error: except (UsageError, runners.RunnerError) as error:
+91
View File
@@ -0,0 +1,91 @@
"""File and console logging for daedalus Python scripts.
``configure_logging()`` is called by run_python_script.py before a script
starts (SPEC.md item 5.8.4); library scripts may call it too. Layout,
levels, formats, and colors follow SPEC.md section 11.
"""
from __future__ import annotations
import logging
import os
import pathlib
import re
import sys
DEFAULT_LOG_FILE = pathlib.Path.home() / ".daedalus" / "debug.log"
FILE_FORMAT = "%(asctime)s|%(levelname)-5.5s|%(module)s.%(funcName)s:%(lineno)d:%(message)s"
FILE_DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
CONSOLE_FORMAT = "%(levelname)-5.5s|%(message)s"
DEFAULT_CONSOLE_LEVEL = "INFO"
WARNING_COLOR = "\033[33m"
ERROR_COLOR = "\033[1;31m"
CRITICAL_COLOR = "\033[1;91m"
ADDRESS_COLOR = "\033[1;34m"
RESET = "\033[0m"
LEVEL_COLORS = {"WARNING": WARNING_COLOR, "ERROR": ERROR_COLOR, "CRITICAL": CRITICAL_COLOR}
BRACKETED_IPV4 = re.compile(r"\[(\d{1,3}(?:\.\d{1,3}){3})")
def colors_enabled(stream=None) -> bool:
"""NO_COLOR unset/empty and (FORCE_COLOR or a terminal): SPEC item 11.4."""
stream = sys.stderr if stream is None else stream
if os.environ.get("NO_COLOR"):
return False
if os.environ.get("FORCE_COLOR"):
return True
return stream.isatty()
def resolve_console_level(override: str | int | None = None) -> int:
"""Console level from an override, else DAEDALUS_LOGLEVEL, else INFO."""
if isinstance(override, int):
return override
text = override or os.environ.get("DAEDALUS_LOGLEVEL") or DEFAULT_CONSOLE_LEVEL
level = logging.getLevelName(text.upper())
return level if isinstance(level, int) else logging.INFO
class ColorFormatter(logging.Formatter):
"""Colors the whole line for WARNING and above; highlights IPv4 in brackets."""
def __init__(self, fmt: str, color: bool | None = None) -> None:
"""Remember whether color is forced regardless of the terminal."""
super().__init__(fmt)
self.color = color
def format(self, record: logging.LogRecord) -> str:
"""Plain for DEBUG and INFO; colored line with an address highlight."""
line = super().format(record)
color = self.color if self.color is not None else colors_enabled()
level_color = LEVEL_COLORS.get(record.levelname)
if not color or level_color is None:
return line
line = BRACKETED_IPV4.sub(
lambda match: f"[{ADDRESS_COLOR}{match.group(1)}{RESET}{level_color}", line)
return f"{level_color}{line}{RESET}"
def configure_logging(log_file: str | os.PathLike | None = None,
console_level: str | int | None = None,
file_level: str | int | None = None,
color: bool | None = None) -> pathlib.Path:
"""Replace the root handlers with a file and a console handler (SPEC item 11.1).
Returns the resolved log file path.
"""
resolved = pathlib.Path(log_file) if log_file is not None else DEFAULT_LOG_FILE
resolved.parent.mkdir(parents=True, exist_ok=True)
logging.root.setLevel(logging.DEBUG)
logging.root.handlers.clear()
file_handler = logging.FileHandler(resolved, mode="a", encoding="utf-8")
file_handler.setFormatter(logging.Formatter(FILE_FORMAT, datefmt=FILE_DATE_FORMAT))
if file_level is not None:
file_handler.setLevel(file_level)
logging.root.addHandler(file_handler)
console_handler = logging.StreamHandler(sys.stderr)
console_handler.setLevel(resolve_console_level(console_level))
console_handler.setFormatter(ColorFormatter(CONSOLE_FORMAT, color))
logging.root.addHandler(console_handler)
return resolved
+49 -4
View File
@@ -1,9 +1,8 @@
"""Registry of the scripts daedalus can run. """Registry of the scripts daedalus can run.
Empty template registry; add entries when integrating scripts (SPEC.md section 4).
Add a script by adding one entry to SCRIPTS. The suffix of ``path`` picks Add a script by adding one entry to SCRIPTS. The suffix of ``path`` picks
the runner (daedalus/runners.py). the runner (daedalus/runners.py); ``categories`` powers the
``daedalus <category>`` listing forms (SPEC.md sections 3 and 4).
""" """
from __future__ import annotations from __future__ import annotations
@@ -15,18 +14,64 @@ from daedalus import LIBRARY_ROOT
NAME_PATTERN = re.compile(r"^[a-z][a-z0-9_-]*$") NAME_PATTERN = re.compile(r"^[a-z][a-z0-9_-]*$")
DEFAULT_CATEGORY = "general"
def _normalize_categories(value: str | list[str] | tuple[str, ...]) -> tuple[str, ...]:
"""One label or an iterable of labels -> tuple; empty is rejected (SPEC item 4.1.3)."""
if isinstance(value, str):
labels: tuple[str, ...] = (value,)
elif isinstance(value, (list, tuple)):
labels = tuple(value)
else:
raise ValueError(f"categories must be a string or a sequence, not {type(value).__name__}")
if not labels or any(not label for label in labels):
raise ValueError("categories must not be empty")
return labels
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
class Script: class Script:
"""One registered script: repo-relative path and a one-line description.""" """One registered script: repo-relative path, one-line description, categories."""
path: str path: str
description: str description: str
categories: str | list[str] | tuple[str, ...] = DEFAULT_CATEGORY
def __post_init__(self) -> None:
"""Store the labels normalized to a tuple (SPEC item 4.1.3)."""
object.__setattr__(self, "categories", _normalize_categories(self.categories))
@property @property
def absolute_path(self) -> pathlib.Path: def absolute_path(self) -> pathlib.Path:
"""Absolute path in the checkout or the installed _library.""" """Absolute path in the checkout or the installed _library."""
return LIBRARY_ROOT / self.path return LIBRARY_ROOT / self.path
@property
def categories_display(self) -> str:
"""Labels joined with a comma and a space (SPEC item 4.1.5)."""
return ", ".join(self.categories)
SCRIPTS: dict[str, Script] = {} SCRIPTS: dict[str, Script] = {}
"""Every script daedalus can run; empty in this template (SPEC.md section 6)."""
def used_categories() -> set[str]:
"""The set of every label of every script (SPEC item 4.4.1)."""
labels: set[str] = set()
for script in SCRIPTS.values():
labels.update(script.categories)
return labels
def is_category_label(token: str) -> bool:
"""True when token is an in-use category and not a script name (SPEC item 4.4.2)."""
return token not in SCRIPTS and token in used_categories()
def scripts_matching_categories(labels: list[str] | tuple[str, ...]) -> dict[str, Script]:
"""Scripts that have every label (AND), sorted by name (SPEC item 4.4.3)."""
wanted = set(labels)
return {name: script for name, script in sorted(SCRIPTS.items())
if wanted <= set(script.categories)}
+62
View File
@@ -0,0 +1,62 @@
"""Child entry for .py scripts: sys.path, logging, argv, and exit codes.
Called as ``<python> run_python_script.py <script.py> [args...]`` by the
daedalus runner (daedalus/runners.py); see SPEC.md item 5.8.
"""
from __future__ import annotations
import os
import pathlib
import runpy
import sys
USAGE = "usage: run_python_script.py <script.py> [args...]"
def _prepend_missing(path: str) -> None:
"""Keep sys.path[0] and the package parent importable (SPEC item 5.8.3)."""
if path not in sys.path:
sys.path.insert(0, path)
def _configure_logging() -> None:
"""Set up file + console logging unless DAEDALUS_NO_LOGGING (SPEC item 5.8.4)."""
if os.environ.get("DAEDALUS_NO_LOGGING"):
return
from daedalus import daedalus_logging
daedalus_logging.configure_logging()
def main(argv: list[str] | None = None) -> int:
"""Run the script file as __main__ and map its exit value (SPEC item 5.8.6)."""
argv = list(sys.argv[1:] if argv is None else argv)
if not argv:
print(USAGE, file=sys.stderr)
return 2
here = pathlib.Path(__file__).resolve().parent
_prepend_missing(str(here.parent))
_prepend_missing(str(here))
script = pathlib.Path(argv[0]).resolve()
args = argv[1:]
if not script.is_file():
print(f"script not found: {script}", file=sys.stderr)
return 2
_configure_logging()
previous_argv = sys.argv
sys.argv = [str(script), *args]
try:
runpy.run_path(str(script), run_name="__main__")
return 0
except SystemExit as error:
if error.code is None:
return 0
if isinstance(error.code, int):
return error.code
print(error.code, file=sys.stderr)
return 1
finally:
sys.argv = previous_argv
if __name__ == "__main__":
sys.exit(main())
+7 -5
View File
@@ -11,8 +11,10 @@ import subprocess
import sys import sys
from daedalus import LIBRARY_ROOT from daedalus import LIBRARY_ROOT
from daedalus import PACKAGE_DIR
from daedalus import REPO_ROOT
PYTHON_SRC = LIBRARY_ROOT / "python" / "src" PYTHON_CHILD = PACKAGE_DIR / "run_python_script.py"
class RunnerError(RuntimeError): class RunnerError(RuntimeError):
@@ -63,8 +65,8 @@ def python_executable() -> str:
def python_command(path: pathlib.Path) -> list[str]: def python_command(path: pathlib.Path) -> list[str]:
"""Run a .py file with python_executable().""" """Run a .py file through run_python_script.py (SPEC item 5, first row)."""
return [python_executable(), str(path)] return [python_executable(), str(PYTHON_CHILD), str(path)]
def bash_command(path: pathlib.Path) -> list[str]: def bash_command(path: pathlib.Path) -> list[str]:
@@ -103,9 +105,9 @@ def build_command(path: pathlib.Path, args: list[str]) -> list[str]:
def script_env() -> dict[str, str]: def script_env() -> dict[str, str]:
"""Caller environment with python/src prepended to PYTHONPATH.""" """Caller environment with REPO_ROOT prepended to PYTHONPATH (SPEC item 5.7.1)."""
env = dict(os.environ) env = dict(os.environ)
env["PYTHONPATH"] = os.pathsep.join(filter(None, [str(PYTHON_SRC), env.get("PYTHONPATH")])) env["PYTHONPATH"] = os.pathsep.join(filter(None, [str(REPO_ROOT), env.get("PYTHONPATH")]))
return env return env
+183 -19
View File
@@ -1,6 +1,7 @@
"""Tests for daedalus.cli and the launchers. """Tests for daedalus.cli and the launchers.
Options, errors, dispatch, and end-to-end runs (SPEC.md section 3). Options, listing format, categories, errors, dispatch, and end-to-end runs
(SPEC.md section 3).
""" """
import os import os
import subprocess import subprocess
@@ -16,31 +17,121 @@ from daedalus import runners
FAKE_SCRIPTS = { FAKE_SCRIPTS = {
"alpha": registry.Script("python/src/alpha/alpha.py", "First tool"), "alpha": registry.Script("python/src/alpha/alpha.py", "First tool"),
"beta_tool": registry.Script("bash/beta_tool.sh", "Second tool"), "beta_tool": registry.Script("bash/beta_tool.sh", "Second tool",
categories=("media", "linux")),
"gamma": registry.Script("powershell/gamma.ps1", "Third tool", categories="media"),
} }
@pytest.fixture @pytest.fixture
def fake_registry(monkeypatch): def fake_registry(monkeypatch):
"""Replace SCRIPTS with a fixed two-entry registry.""" """Replace SCRIPTS and pin the version so list output is stable."""
monkeypatch.setattr(registry, "SCRIPTS", FAKE_SCRIPTS) monkeypatch.setattr(registry, "SCRIPTS", dict(FAKE_SCRIPTS))
monkeypatch.setattr(cli, "version", lambda: "1.2.3")
@pytest.fixture
def plain(monkeypatch):
"""Force colors off and a wide, deterministic terminal."""
monkeypatch.setenv("NO_COLOR", "1")
monkeypatch.delenv("FORCE_COLOR", raising=False)
monkeypatch.setenv("COLUMNS", "200")
def row(name: str, script_type: str, categories: str) -> str:
"""One table row: name 9 wide, type 4 wide, categories 12 wide (SPEC item 3.3.2)."""
return f"{name:<9} {script_type:<4} {categories:<12}"
@pytest.mark.parametrize("argv", [[], ["-l"], ["--list"]]) @pytest.mark.parametrize("argv", [[], ["-l"], ["--list"]])
def test_list(fake_registry, capsys, argv): def test_list(fake_registry, plain, capsys, argv):
"""No arguments or --list prints name, type, and description.""" """Listing prints the version line, a table, wrapped descriptions (SPEC item 3.3)."""
assert cli.main(argv) == 0 assert cli.main(argv) == 0
assert capsys.readouterr().out.splitlines() == [ assert capsys.readouterr().out.splitlines() == [
"alpha py First tool", "Daedalus Version: 1.2.3",
"beta_tool sh Second tool", "",
row("script", "type", "categories"),
"--------- ---- ------------",
row("alpha", "py", "general"),
" First tool",
row("beta_tool", "sh", "media, linux"),
" Second tool",
row("gamma", "ps1", "media"),
" Third tool",
] ]
def test_list_when_empty(monkeypatch, plain, capsys):
"""With no scripts, only the version line is printed (SPEC item 3.3.1)."""
monkeypatch.setattr(registry, "SCRIPTS", {})
monkeypatch.setattr(cli, "version", lambda: "1.2.3")
assert cli.main([]) == 0
assert capsys.readouterr().out == "Daedalus Version: 1.2.3\n"
def test_list_wraps_descriptions(fake_registry, plain, monkeypatch, capsys):
"""Descriptions wrap to the terminal width and indent by 8 (SPEC item 3.3.4)."""
monkeypatch.setenv("COLUMNS", "60")
long_text = "The quick brown fox jumps over the lazy dog again and again " * 3
monkeypatch.setitem(registry.SCRIPTS, "alpha",
registry.Script("python/src/alpha/alpha.py", long_text.rstrip()))
assert cli.main(["--list"]) == 0
lines = capsys.readouterr().out.splitlines()
wrapped = [line for line in lines if line.startswith(" ")]
assert len(wrapped) > 1, "a 170-char description must wrap at 60 columns"
assert all(len(line) <= 8 + 60 for line in wrapped), lines
def test_list_min_width_is_40(fake_registry, plain, monkeypatch, capsys):
"""Narrow terminals still wrap to at least 40 columns (SPEC item 3.3.4)."""
monkeypatch.setenv("COLUMNS", "20")
assert cli.main(["--list"]) == 0
lines = capsys.readouterr().out.splitlines()
wrapped = [line for line in lines if line.startswith(" ")]
assert all(8 + 40 >= len(line) for line in wrapped), lines
def test_list_no_word_splitting(fake_registry, plain, monkeypatch, capsys):
"""Long and hyphenated words are never split (SPEC item 3.3.4)."""
monkeypatch.setenv("COLUMNS", "50")
text = "short filler words to fill the line " + "supercalifragilistic-expialidocious word"
monkeypatch.setitem(registry.SCRIPTS, "alpha",
registry.Script("python/src/alpha/alpha.py", text))
assert cli.main(["--list"]) == 0
lines = capsys.readouterr().out.splitlines()
assert any("supercalifragilistic-expialidocious" in line for line in lines), lines
fragments = [line for line in lines if "expialidoc" in line
and "supercalifragilistic" not in line]
assert fragments == [], lines
def test_list_colors(fake_registry, monkeypatch, capsys):
"""FORCE_COLOR colors the padded name, type, and categories cells (SPEC item 3.3.5)."""
monkeypatch.delenv("NO_COLOR", raising=False)
monkeypatch.setenv("FORCE_COLOR", "1")
assert cli.main(["--list"]) == 0
alpha_row = next(line for line in capsys.readouterr().out.splitlines()
if "alpha" in line and "py" in line)
assert alpha_row.startswith("\033[32malpha")
assert "\033[33mpy" in alpha_row
assert "\033[94mgeneral" in alpha_row
def test_list_no_color_wins(fake_registry, monkeypatch, capsys):
"""A non-empty NO_COLOR beats FORCE_COLOR (SPEC item 3.3.6)."""
monkeypatch.setenv("NO_COLOR", "1")
monkeypatch.setenv("FORCE_COLOR", "1")
assert cli.main(["--list"]) == 0
assert "\033[" not in capsys.readouterr().out
@pytest.mark.parametrize("argv", [["-h"], ["--help"]]) @pytest.mark.parametrize("argv", [["-h"], ["--help"]])
def test_help(capsys, argv): def test_help(fake_registry, plain, capsys, argv):
"""--help prints usage.""" """--help prints the full usage with category forms (SPEC item 3.8)."""
assert cli.main(argv) == 0 assert cli.main(argv) == 0
assert capsys.readouterr().out.startswith("usage: daedalus <name>") out = capsys.readouterr().out
assert "daedalus <name> [args...]" in out
assert "daedalus <category> [category...]" in out
def test_path(fake_registry, capsys): def test_path(fake_registry, capsys):
@@ -49,7 +140,7 @@ def test_path(fake_registry, capsys):
assert capsys.readouterr().out.strip() == str(LIBRARY_ROOT / "python/src/alpha/alpha.py") assert capsys.readouterr().out.strip() == str(LIBRARY_ROOT / "python/src/alpha/alpha.py")
@pytest.mark.parametrize("installed, expected", [(True, "daedalus 1.2.3"), (False, "daedalus 0.0.0")]) @pytest.mark.parametrize("installed, expected", [(True, "daedalus 1.2.3"), (False, "daedalus 0.1.0")])
def test_version(monkeypatch, capsys, installed, expected): def test_version(monkeypatch, capsys, installed, expected):
"""--version uses metadata or pyproject.toml in a checkout.""" """--version uses metadata or pyproject.toml in a checkout."""
def fake_version(_name): def fake_version(_name):
@@ -64,17 +155,17 @@ def test_version(monkeypatch, capsys, installed, expected):
@pytest.mark.parametrize("argv, message", [ @pytest.mark.parametrize("argv, message", [
(["--path"], "usage: daedalus --path"), (["--path"], "usage: daedalus --path"),
(["--bogus"], "unknown option '--bogus'"), (["--bogus"], "unknown option '--bogus'; run 'daedalus --help'"),
(["alpah"], "unknown script 'alpah'; did you mean: alpha"), (["alpah"], "unknown script 'alpah'; did you mean: alpha"),
(["zzz"], "unknown script 'zzz'; run 'daedalus --list'"), (["zzz"], "unknown script 'zzz'; run 'daedalus --list'"),
]) ])
def test_usage_errors_exit_2(fake_registry, capsys, argv, message): def test_usage_errors_exit_2(fake_registry, plain, capsys, argv, message):
"""Bad options and unknown names exit 2 with a message on stderr.""" """Bad options and unknown names exit 2 with a message on stderr."""
assert cli.main(argv) == 2 assert cli.main(argv) == 2
assert message in capsys.readouterr().err assert message in capsys.readouterr().err
def test_dispatch_passes_args_through(fake_registry, monkeypatch): def test_dispatch_passes_args_through(fake_registry, plain, monkeypatch):
"""Everything after the name, including --help, goes to the script.""" """Everything after the name, including --help, goes to the script."""
calls = [] calls = []
monkeypatch.setattr(runners, "run", lambda path, args: calls.append((path, args)) or 7) monkeypatch.setattr(runners, "run", lambda path, args: calls.append((path, args)) or 7)
@@ -82,19 +173,92 @@ def test_dispatch_passes_args_through(fake_registry, monkeypatch):
assert calls == [(LIBRARY_ROOT / "python/src/alpha/alpha.py", ["--help", "x"])] assert calls == [(LIBRARY_ROOT / "python/src/alpha/alpha.py", ["--help", "x"])]
def test_runner_error_exits_2(fake_registry, capsys): def test_runner_error_exits_2(fake_registry, plain, capsys):
"""A missing script file exits 2 instead of a traceback.""" """A missing script file exits 2 instead of a traceback."""
assert cli.main(["alpha"]) == 2 assert cli.main(["alpha"]) == 2
assert "script not found" in capsys.readouterr().err assert "script not found" in capsys.readouterr().err
def test_main_reads_sys_argv(fake_registry, monkeypatch, capsys): def test_main_reads_sys_argv(fake_registry, plain, monkeypatch, capsys):
"""Without argv, main uses sys.argv.""" """Without argv, main uses sys.argv."""
monkeypatch.setattr(sys, "argv", ["daedalus", "--list"]) monkeypatch.setattr(sys, "argv", ["daedalus", "--list"])
assert cli.main() == 0 assert cli.main() == 0
assert "alpha" in capsys.readouterr().out assert "alpha" in capsys.readouterr().out
# --- categories (SPEC items 3.10, 3.11) -------------------------------------
def test_category_lists_scripts(fake_registry, plain, capsys):
"""daedalus <category> lists scripts that have the category."""
assert cli.main(["media"]) == 0
assert capsys.readouterr().out.splitlines()[2:] == [
row("script", "type", "categories"),
"--------- ---- ------------",
row("beta_tool", "sh", "media, linux"),
" Second tool",
row("gamma", "ps1", "media"),
" Third tool",
]
def test_categories_are_anded(fake_registry, plain, capsys):
"""Several categories list scripts that have every one of them."""
assert cli.main(["media", "linux"]) == 0
out = capsys.readouterr().out
assert "beta_tool" in out
assert "alpha" not in out
assert "gamma" not in out
def test_categories_match_no_script(fake_registry, plain, capsys):
"""Disjoint categories exit 2 with the no-scripts message."""
assert cli.main(["media", "general"]) == 2
assert "no scripts for categories: media, general" in capsys.readouterr().err
def test_category_prefix_runs_script(fake_registry, plain, monkeypatch):
"""A category-prefixed run passes the remaining args to the script."""
calls = []
monkeypatch.setattr(runners, "run", lambda path, args: calls.append((path, args)) or 5)
assert cli.main(["media", "beta_tool", "x", "--help"]) == 5
assert calls == [(LIBRARY_ROOT / "bash/beta_tool.sh", ["x", "--help"])]
def test_script_name_stops_the_prefix(fake_registry, plain, monkeypatch):
"""A token that is a script name is never eaten as a category."""
calls = []
monkeypatch.setattr(runners, "run", lambda path, args: calls.append((path, args)) or 0)
assert cli.main(["alpha"]) == 0
assert calls == [(LIBRARY_ROOT / "python/src/alpha/alpha.py", [])]
def test_script_lacks_a_prefix_category(fake_registry, plain, capsys):
"""A registered script outside the prefix explains its categories (SPEC item 3.11)."""
assert cli.main(["media", "alpha"]) == 2
err = capsys.readouterr().err
assert "script 'alpha' has categories 'general', not [media]" in err
assert "run 'daedalus alpha' or pick another prefix" in err
def test_unknown_script_after_prefix_with_close_match(fake_registry, plain, capsys):
"""Close matches after a prefix come from the prefix's scripts only."""
assert cli.main(["media", "beta"]) == 2
assert "unknown script 'beta' for 'media'; did you mean: beta_tool" in capsys.readouterr().err
def test_unknown_script_after_prefix_without_close_match(fake_registry, plain, capsys):
"""No close match after a prefix suggests listing the categories."""
assert cli.main(["media", "zzz"]) == 2
assert "unknown script 'zzz' for 'media'; run 'daedalus media'" in capsys.readouterr().err
def test_close_matches_respect_the_prefix(fake_registry, plain, capsys):
"""Names of scripts outside the prefix are never suggested."""
assert cli.main(["media", "gama"]) == 2
assert "did you mean: gamma" in capsys.readouterr().err
def run_cli(*command: str) -> subprocess.CompletedProcess: def run_cli(*command: str) -> subprocess.CompletedProcess:
"""Run a daedalus command from a directory outside the repo.""" """Run a daedalus command from a directory outside the repo."""
env = {**os.environ, "PYTHONPATH": str(REPO_ROOT)} env = {**os.environ, "PYTHONPATH": str(REPO_ROOT)}
@@ -103,10 +267,10 @@ def run_cli(*command: str) -> subprocess.CompletedProcess:
def test_module_runs_list(): def test_module_runs_list():
"""python -m daedalus --list runs with an empty registry.""" """python -m daedalus --list prints the version line with an empty registry."""
result = run_cli(sys.executable, "-m", "daedalus", "--list") result = run_cli(sys.executable, "-m", "daedalus", "--list")
assert result.returncode == 0, result.stderr assert result.returncode == 0, result.stderr
assert result.stdout.strip() == "" assert result.stdout.startswith("Daedalus Version:")
@pytest.mark.skipif(os.name != "nt", reason="cmd.exe is Windows only") @pytest.mark.skipif(os.name != "nt", reason="cmd.exe is Windows only")
+81
View File
@@ -0,0 +1,81 @@
"""Tests for the daedalus package __init__ (SPEC.md sections 2.2 and 10).
PATH computation and the checkout-time registration of python/src
subfolders as daedalus.<folder> packages.
"""
import sys
import daedalus
from daedalus import LIBRARY_ROOT
from daedalus import PACKAGE_DIR
from daedalus import REPO_ROOT
def test_paths():
"""PACKAGE_DIR is the package folder; REPO_ROOT its parent (SPEC item 2.2)."""
assert PACKAGE_DIR.is_dir()
assert REPO_ROOT == PACKAGE_DIR.parent
assert (PACKAGE_DIR / "cli.py").is_file()
def test_library_root_in_a_checkout():
"""A checkout has no _library next to the package; REPO_ROOT wins (SPEC item 9.3)."""
assert LIBRARY_ROOT == REPO_ROOT
def make_source(tmp_path, *names: str):
"""Create python/src/<name> folders (spec 10.3 layout) and return REPO_ROOT."""
for name in names:
folder = tmp_path / "python" / "src" / name
folder.mkdir(parents=True, exist_ok=True)
(folder / f"{name}.py").write_text(f'VALUE = "{name}"\n', encoding="utf-8")
(tmp_path / "python" / "src" / "__pycache__").mkdir(exist_ok=True)
def cleanup_modules(*names: str):
"""Drop test-registered modules so other tests are not affected."""
for name in names:
for module_name in (f"daedalus.{name}", f"daedalus.{name}.{name}"):
sys.modules.pop(module_name, None)
def test_registers_source_folders_as_packages(tmp_path):
"""Every python/src subfolder becomes daedalus.<folder> (SPEC item 10.3)."""
make_source(tmp_path, "alice", "bob")
try:
registered = daedalus.register_source_folders(tmp_path)
assert sorted(registered) == ["daedalus.alice", "daedalus.bob"]
import daedalus.alice.alice as alice_module # noqa: E402 (registered just above)
import daedalus.bob.bob as bob_module # noqa: E402
assert (alice_module.VALUE, bob_module.VALUE) == ("alice", "bob")
finally:
cleanup_modules("alice", "bob")
def test_skips_pycache_folders(tmp_path):
"""__pycache__ and hidden or private folders are not registered."""
make_source(tmp_path, "alice")
try:
registered = daedalus.register_source_folders(tmp_path)
assert "daedalus.__pycache__" not in registered
assert "daedalus.alice" in registered
finally:
cleanup_modules("alice")
def test_keeps_already_loaded_modules(tmp_path, monkeypatch):
"""An already-loaded daedalus.<folder> is left alone (SPEC item 10.3)."""
sentinel = sys.intern("already-loaded")
monkeypatch.setitem(sys.modules, "daedalus.bob", sentinel)
make_source(tmp_path, "bob")
try:
registered = daedalus.register_source_folders(tmp_path)
assert "daedalus.bob" not in registered
assert sys.modules["daedalus.bob"] is sentinel
finally:
cleanup_modules("bob")
def test_without_source_folder(tmp_path):
"""A repo root without python/src registers nothing."""
assert daedalus.register_source_folders(tmp_path) == []
+164
View File
@@ -0,0 +1,164 @@
"""Tests for daedalus.daedalus_logging (SPEC.md section 11).
Handlers, levels, formats, colors, and the IPv4 highlight.
"""
import logging
import os
import pytest
from daedalus import daedalus_logging
@pytest.fixture
def restore_root_logging():
"""Keep the root logger as pytest had it and isolate the log file."""
handlers = logging.root.handlers[:]
level = logging.root.level
yield
logging.root.handlers[:] = handlers
logging.root.setLevel(level)
@pytest.fixture
def log_file(tmp_path, monkeypatch):
"""Point the default log file at tmp and return its path."""
path = tmp_path / "logs" / "debug.log"
monkeypatch.setattr(daedalus_logging, "DEFAULT_LOG_FILE", path)
return path
@pytest.fixture
def no_color(monkeypatch):
"""Deterministic plain console output."""
monkeypatch.setenv("NO_COLOR", "1")
monkeypatch.delenv("FORCE_COLOR", raising=False)
def test_configure_returns_path_and_creates_file(log_file, no_color, restore_root_logging):
"""configure_logging resolves and returns the log file path (SPEC item 11.6)."""
assert daedalus_logging.configure_logging() == log_file
assert log_file.is_file()
def test_root_has_two_handlers(log_file, no_color, restore_root_logging):
"""Root level is DEBUG with one file and one console handler (SPEC item 11.2)."""
daedalus_logging.configure_logging()
assert logging.root.level == logging.DEBUG
kinds = sorted(type(handler).__name__ for handler in logging.root.handlers)
assert kinds == ["FileHandler", "StreamHandler"]
def test_configure_replaces_existing_handlers(log_file, no_color, restore_root_logging):
"""Existing root handlers are replaced, not duplicated (SPEC item 11.1)."""
logging.root.addHandler(logging.NullHandler())
daedalus_logging.configure_logging()
assert len(logging.root.handlers) == 2
def test_file_receives_all_levels(log_file, no_color, restore_root_logging):
"""The file handler format is as FIXED: pipes and file:line info (SPEC item 11.2.1)."""
daedalus_logging.configure_logging()
logging.getLogger(__name__).debug("file-only")
logging.shutdown()
text = log_file.read_text(encoding="utf-8")
assert "|DEBUG|test_logging.test_file_receives_all_levels:" in text
assert "file-only" in text
def console_handler() -> logging.StreamHandler:
"""The stderr console handler (a FileHandler is a StreamHandler too)."""
return next(handler for handler in logging.root.handlers
if isinstance(handler, logging.StreamHandler)
and not isinstance(handler, logging.FileHandler))
def test_console_level_from_env(log_file, no_color, monkeypatch, restore_root_logging):
"""DAEDALUS_LOGLEVEL sets the console level (SPEC item 11.2.2)."""
monkeypatch.setenv("DAEDALUS_LOGLEVEL", "DEBUG")
daedalus_logging.configure_logging()
assert console_handler().level == logging.DEBUG
def test_console_level_default_and_invalid(log_file, no_color, monkeypatch, restore_root_logging):
"""Missing or unknown DAEDALUS_LOGLEVEL falls back to INFO."""
monkeypatch.delenv("DAEDALUS_LOGLEVEL", raising=False)
daedalus_logging.configure_logging()
assert console_handler().level == logging.INFO
daedalus_logging.configure_logging(console_level="NOT-A-LEVEL")
assert console_handler().level == logging.INFO
def test_console_format(log_file, no_color, restore_root_logging, capsys):
"""Console lines are LEVEL|message (SPEC item 11.2.2)."""
daedalus_logging.configure_logging()
logging.getLogger().warning("careful")
assert "WARNI|careful" in capsys.readouterr().err
@pytest.mark.parametrize("level_name, message, escape", [
("warning", "careful", "\033[33m"),
("error", "broken", "\033[1;31m"),
("critical", "dead", "\033[1;91m"),
])
def test_colored_levels(log_file, monkeypatch, restore_root_logging, capsys, level_name, message, escape):
"""Colored lines start with the level color and end with a reset (SPEC item 11.5.1)."""
monkeypatch.delenv("NO_COLOR", raising=False)
monkeypatch.setenv("FORCE_COLOR", "1")
daedalus_logging.configure_logging()
getattr(logging.getLogger(), level_name)(message)
err = capsys.readouterr().err
assert escape in err, err
assert err.strip().endswith("\033[0m"), err
def test_info_stays_plain(log_file, monkeypatch, restore_root_logging, capsys):
"""DEBUG and INFO lines are not colored (SPEC item 11.5.1)."""
monkeypatch.delenv("NO_COLOR", raising=False)
monkeypatch.setenv("FORCE_COLOR", "1")
daedalus_logging.configure_logging()
logging.getLogger().info("plain talk")
assert "\033[" not in capsys.readouterr().err
def test_no_color_beats_force(log_file, monkeypatch, restore_root_logging, capsys):
"""NO_COLOR always wins (SPEC item 11.4)."""
monkeypatch.setenv("NO_COLOR", "1")
monkeypatch.setenv("FORCE_COLOR", "1")
daedalus_logging.configure_logging()
logging.getLogger().warning("careful")
assert "\033[" not in capsys.readouterr().err
def test_color_when_stderr_is_a_terminal(log_file, monkeypatch, restore_root_logging, capsys):
"""Color is on when stderr is a terminal and NO_COLOR is unset (SPEC item 11.4)."""
monkeypatch.delenv("NO_COLOR", raising=False)
monkeypatch.delenv("FORCE_COLOR", raising=False)
monkeypatch.setattr(daedalus_logging.sys.stderr, "isatty", lambda: True)
daedalus_logging.configure_logging()
logging.getLogger().warning("careful")
assert "\033[33m" in capsys.readouterr().err
def test_ipv4_highlight(log_file, no_color, monkeypatch, restore_root_logging, capsys):
"""The first address in [10.0.0.1 - 10.0.0.9] is bold blue (SPEC item 11.5.2)."""
monkeypatch.delenv("NO_COLOR", raising=False)
monkeypatch.setenv("FORCE_COLOR", "1")
daedalus_logging.configure_logging()
logging.getLogger(__name__).warning("host [10.0.0.1 - 10.0.0.9] unreachable")
err = capsys.readouterr().err
assert "\033[1;34m10.0.0.1\033[0m" in err, err
assert err.index("\033[1;34m") > err.index("\033[33m")
def test_overrides(log_file, no_color, restore_root_logging, tmp_path, capsys):
"""log file, console level, file level, and color can be overridden (SPEC item 11.6)."""
other = tmp_path / "other.log"
path = daedalus_logging.configure_logging(log_file=other, console_level="ERROR", color=False)
assert path == other
assert console_handler().level == logging.ERROR
logging.getLogger().warning("not on console")
logging.shutdown()
assert other.read_text(encoding="utf-8")
assert "not on console" in other.read_text(encoding="utf-8")
assert "not on console" not in capsys.readouterr().err
+10 -3
View File
@@ -79,11 +79,18 @@ def run_installed(installed, *args: str) -> subprocess.CompletedProcess:
text=True, check=False, cwd=installed, env=env) text=True, check=False, cwd=installed, env=env)
def test_installed_cli_lists_empty(installed): def test_wheel_holds_the_logging_package_and_child_entry(wheel):
"""The installed CLI lists nothing when SCRIPTS is empty.""" """daedalus_logging and run_python_script.py ship with the CLI (SPEC items 9.4, 5.8)."""
names = wheel_names(wheel)
assert "daedalus/daedalus_logging/__init__.py" in names
assert "daedalus/run_python_script.py" in names
def test_installed_cli_lists_version_line(installed):
"""The installed CLI prints the version line even with no scripts (SPEC item 3.3.1)."""
result = run_installed(installed, "--list") result = run_installed(installed, "--list")
assert result.returncode == 0, result.stderr assert result.returncode == 0, result.stderr
assert result.stdout.strip() == "" assert result.stdout.startswith("Daedalus Version:")
def test_installed_cli_version(installed): def test_installed_cli_version(installed):
+76 -1
View File
@@ -1,4 +1,4 @@
"""Consistency tests for daedalus.registry.SCRIPTS. """Tests for daedalus.registry: Script records, categories, and SCRIPTS consistency.
Every registered script is valid, present, and runnable (SPEC.md section 4). Every registered script is valid, present, and runnable (SPEC.md section 4).
""" """
@@ -48,3 +48,78 @@ def test_listed_in_readme(name, script):
def test_description_is_one_line(name, script): def test_description_is_one_line(name, script):
"""Descriptions are non-empty single lines.""" """Descriptions are non-empty single lines."""
assert script.description.strip() and "\n" not in script.description, name assert script.description.strip() and "\n" not in script.description, name
@pytest.mark.parametrize("name, script", ENTRIES)
def test_categories_are_valid(name, script):
"""Categories are non-empty labels matching the name pattern (SPEC item 4.8.5)."""
assert script.categories, name
for label in script.categories:
assert registry.NAME_PATTERN.match(label), f"{name}: {label}"
assert name not in registry.used_categories(), f"{name} is also a category label"
def test_script_with_default_categories():
"""A script without categories lands in the default 'general' (SPEC item 4.1.3)."""
assert registry.Script("python/src/x/x.py", "X").categories == ("general",)
@pytest.mark.parametrize("value, expected", [
("media", ("media",)),
(["media", "linux"], ("media", "linux")),
(("media", "linux"), ("media", "linux")),
])
def test_categories_normalization(value, expected):
"""Strings become one-item tuples; lists become tuples (SPEC item 4.1.3)."""
assert registry.Script("python/src/x/x.py", "X", categories=value).categories == expected
@pytest.mark.parametrize("value", ["", [], ()])
def test_empty_categories_rejected(value):
"""Empty categories are a ValueError (SPEC item 4.1.3)."""
with pytest.raises(ValueError):
registry.Script("python/src/x/x.py", "X", categories=value)
def test_categories_display():
"""The display form joins labels with a comma and a space (SPEC item 4.1.5)."""
script = registry.Script("bash/x.sh", "X", categories=["media", "linux"])
assert script.categories_display == "media, linux"
@pytest.fixture
def fake_registry(monkeypatch):
"""A fixed registry exercising several scripts and labels."""
scripts = {
"alpha": registry.Script("python/src/alpha/alpha.py", "First", categories="general"),
"beta_tool": registry.Script("bash/beta_tool.sh", "Second", categories=("media", "linux")),
"gamma": registry.Script("powershell/gamma.ps1", "Third", categories=("media",)),
}
monkeypatch.setattr(registry, "SCRIPTS", scripts)
return scripts
def test_used_categories(fake_registry):
"""used_categories() is the set of every label (SPEC item 4.4.1)."""
assert registry.used_categories() == {"general", "media", "linux"}
@pytest.mark.parametrize("token, expected", [
("media", True),
("alpha", False), # a script name is never a category token (SPEC item 3.4)
("nope", False),
])
def test_is_category_label(fake_registry, token, expected):
"""is_category_label: false for script names, true for labels in use."""
assert registry.is_category_label(token) is expected
def test_scripts_matching_categories_is_and(fake_registry):
"""Multiple labels are ANDed; results are sorted by name (SPEC item 4.4.3)."""
assert list(registry.scripts_matching_categories(["media", "linux"])) == ["beta_tool"]
assert list(registry.scripts_matching_categories(["media"])) == ["beta_tool", "gamma"]
def test_scripts_matching_categories_empty_returns_all(fake_registry):
"""No labels means every script, sorted by name."""
assert list(registry.scripts_matching_categories([])) == ["alpha", "beta_tool", "gamma"]
+126
View File
@@ -0,0 +1,126 @@
"""Tests for daedalus.run_python_script (SPEC.md item 5.8).
Usage errors, sys.path setup, logging, argv handling, and exit codes.
"""
import logging
import os
import subprocess
import sys
import pytest
from daedalus import daedalus_logging
from daedalus import run_python_script
@pytest.fixture
def restore_root_logging():
"""Keep the root logger as pytest had it."""
handlers = logging.root.handlers[:]
level = logging.root.level
yield
logging.root.handlers[:] = handlers
logging.root.setLevel(level)
def run_child(monkeypatch, tmp_path, text: str, args: list[str] | None = None) -> int:
"""Write a script file and run it as the child would; return the exit code."""
script = tmp_path / "tool.py"
script.write_text(text, encoding="utf-8")
monkeypatch.setattr(daedalus_logging, "DEFAULT_LOG_FILE",
tmp_path / "logs" / "debug.log")
return run_python_script.main([str(script), *(args or [])])
def test_no_arguments(monkeypatch, capsys):
"""Without a script, usage goes to stderr and the exit code is 2."""
monkeypatch.setattr(sys, "argv", ["run_python_script.py"])
assert run_python_script.main() == 2
assert "usage: run_python_script.py" in capsys.readouterr().err
def test_missing_script(monkeypatch, tmp_path, capsys):
"""A script path that is not a file exits 2 (SPEC item 5.8.2)."""
monkeypatch.setattr(sys, "argv", ["run_python_script.py", str(tmp_path / "nope.py")])
assert run_python_script.main() == 2
assert "script not found:" in capsys.readouterr().err
def test_normal_run_returns_zero(monkeypatch, tmp_path, restore_root_logging, capsys):
"""A clean script exits 0 and stdout passes through."""
assert run_child(monkeypatch, tmp_path, "print('hello', 'from', 'child')\n") == 0
assert capsys.readouterr().out.strip() == "hello from child"
def test_script_prints_argv(monkeypatch, tmp_path, restore_root_logging, capsys):
"""sys.argv is [script, *args], and restored afterwards (SPEC item 5.8.5)."""
before = sys.argv
text = "import sys\nprint(sys.argv[1:])\n"
script = tmp_path / "tool.py"
script.write_text(text, encoding="utf-8")
monkeypatch.setattr(daedalus_logging, "DEFAULT_LOG_FILE", tmp_path / "logs" / "debug.log")
assert run_python_script.main([str(script), "x", "y z"]) == 0
assert capsys.readouterr().out.strip() == "['x', 'y z']"
assert sys.argv == before
def test_exit_codes(monkeypatch, tmp_path, restore_root_logging):
"""exit, exit(None), exit(int), and other values map to 0, N, 1 (SPEC item 5.8.6)."""
cases = [
("import sys\nsys.exit()\n", 0),
("import sys\nsys.exit(None)\n", 0),
("import sys\nsys.exit(3)\n", 3),
("raise SystemExit('boom')\n", 1),
("\n", 0),
]
for text, expected in cases:
script = tmp_path / "tool.py"
script.write_text(text, encoding="utf-8")
monkeypatch.setattr(daedalus_logging, "DEFAULT_LOG_FILE", tmp_path / "logs" / "debug.log")
assert run_python_script.main([str(script)]) == expected, text
def test_exit_message_goes_to_stderr(monkeypatch, tmp_path, restore_root_logging, capsys):
"""sys.exit('text') prints the text and exits 1 (SPEC item 5.8.6)."""
assert run_child(monkeypatch, tmp_path, "import sys\nsys.exit('went wrong')\n") == 1
assert "went wrong" in capsys.readouterr().err
def test_exception_propagates(monkeypatch, tmp_path, restore_root_logging):
"""An uncaught exception escapes as a traceback would in the real child."""
with pytest.raises(ValueError, match="kaboom"):
run_child(monkeypatch, tmp_path, "raise ValueError('kaboom')\n")
def test_logging_configured_by_default(monkeypatch, tmp_path, restore_root_logging, capsys):
"""Without DAEDALUS_NO_LOGGING, records reach the console and file (SPEC item 5.8.4)."""
(tmp_path / "logs").mkdir()
log_file = tmp_path / "logs" / "debug.log"
monkeypatch.setattr(daedalus_logging, "DEFAULT_LOG_FILE", log_file)
script = tmp_path / "tool.py"
script.write_text("import logging\nlogging.warning('careful')\n", encoding="utf-8")
assert run_python_script.main([str(script)]) == 0
assert "WARNI|careful" in capsys.readouterr().err
assert "careful" in log_file.read_text(encoding="utf-8")
def test_logging_disabled_by_env(monkeypatch, tmp_path, restore_root_logging, capsys):
"""DAEDALUS_NO_LOGGING leaves the root logger alone (SPEC item 5.8.4)."""
monkeypatch.setenv("DAEDALUS_NO_LOGGING", "1")
script = tmp_path / "tool.py"
script.write_text("import logging\nlogging.warning('silent')\n", encoding="utf-8")
assert run_python_script.main([str(script)]) == 0
assert "silent" not in capsys.readouterr().err
def test_child_can_import_daedalus_subprocess(tmp_path):
"""The child sets sys.path so `import daedalus` works from anywhere (SPEC item 5.8.3)."""
script = tmp_path / "tool.py"
script.write_text("import daedalus.daedalus_logging as log\nprint('ok', log.__name__)\n",
encoding="utf-8")
child = os.path.join(os.path.dirname(run_python_script.__file__), "run_python_script.py")
result = subprocess.run([sys.executable, child, str(script), "-x"],
capture_output=True, text=True, check=False,
env={"DAEDALUS_NO_LOGGING": "1", "PATH": os.environ["PATH"]})
assert result.returncode == 0, result.stderr
assert result.stdout.strip() == "ok daedalus.daedalus_logging"
+24 -9
View File
@@ -8,8 +8,12 @@ import sys
import pytest import pytest
from daedalus import PACKAGE_DIR
from daedalus import REPO_ROOT
from daedalus import runners from daedalus import runners
CHILD = PACKAGE_DIR / "run_python_script.py"
@pytest.fixture @pytest.fixture
def script(tmp_path): def script(tmp_path):
@@ -22,17 +26,21 @@ def script(tmp_path):
def test_python_command(script, monkeypatch): def test_python_command(script, monkeypatch):
""".py runs with the current interpreter, args appended.""" """.py runs through run_python_script.py, args appended (SPEC item 5, first row)."""
monkeypatch.delenv("DAEDALUS_PYTHON", raising=False) monkeypatch.delenv("DAEDALUS_PYTHON", raising=False)
path = script(".py") path = script(".py")
assert runners.build_command(path, ["-x", "a b"]) == [sys.executable, str(path), "-x", "a b"] assert runners.build_command(path, ["-x", "a b"]) == [
sys.executable, str(CHILD), str(path), "-x", "a b",
]
def test_python_command_honors_daedalus_python(script, monkeypatch): def test_python_command_honors_daedalus_python(script, monkeypatch):
"""DAEDALUS_PYTHON overrides the pipx interpreter.""" """DAEDALUS_PYTHON overrides the pipx interpreter (SPEC item 5.2)."""
monkeypatch.setenv("DAEDALUS_PYTHON", "/opt/daedalus-venv/bin/python") monkeypatch.setenv("DAEDALUS_PYTHON", "/opt/daedalus-venv/bin/python")
path = script(".py") path = script(".py")
assert runners.build_command(path, []) == ["/opt/daedalus-venv/bin/python", str(path)] assert runners.build_command(path, []) == [
"/opt/daedalus-venv/bin/python", str(CHILD), str(path),
]
def test_bash_command(script, monkeypatch): def test_bash_command(script, monkeypatch):
@@ -130,14 +138,21 @@ def test_find_powershell_missing(monkeypatch):
runners.find_powershell() runners.find_powershell()
def test_script_env_prepends_python_src(monkeypatch): def test_script_env_prepends_repo_root(monkeypatch):
"""python/src comes first on PYTHONPATH; the caller's path is kept.""" """REPO_ROOT comes first on PYTHONPATH; the caller's path is kept (SPEC item 5.7.1)."""
monkeypatch.setenv("PYTHONPATH", "existing") monkeypatch.setenv("PYTHONPATH", "existing")
assert runners.script_env()["PYTHONPATH"] == os.pathsep.join([str(runners.PYTHON_SRC), "existing"]) assert runners.script_env()["PYTHONPATH"] == os.pathsep.join([str(REPO_ROOT), "existing"])
def test_run_returns_exit_code(tmp_path): def test_script_env_without_existing_path(monkeypatch):
"""The script's exit code and arguments pass through.""" """Without a caller PYTHONPATH, REPO_ROOT is the whole value."""
monkeypatch.delenv("PYTHONPATH", raising=False)
assert runners.script_env()["PYTHONPATH"] == str(REPO_ROOT)
def test_run_returns_exit_code(tmp_path, monkeypatch):
"""The script's exit code and arguments pass through (SPEC item 5.8.6)."""
monkeypatch.setenv("DAEDALUS_NO_LOGGING", "1")
path = tmp_path / "exit.py" path = tmp_path / "exit.py"
path.write_text("import sys\nsys.exit(int(sys.argv[1]))\n", encoding="utf-8") path.write_text("import sys\nsys.exit(int(sys.argv[1]))\n", encoding="utf-8")
assert runners.run(path, ["3"]) == 3 assert runners.run(path, ["3"]) == 3
+3 -2
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "daedalus" name = "daedalus"
version = "0.0.0" version = "0.1.0"
description = "Template for daedalus: loose scripts in one repo, run with: daedalus <name> [args...]" description = "Template for daedalus: loose scripts in one repo, run with: daedalus <name> [args...]"
readme = "README.md" readme = "README.md"
requires-python = ">=3.11" requires-python = ">=3.11"
@@ -18,6 +18,7 @@ daedalus = "daedalus.cli:main"
[tool.setuptools] [tool.setuptools]
packages = [ packages = [
"daedalus", "daedalus",
"daedalus.daedalus_logging",
"daedalus._library.python.src", "daedalus._library.python.src",
"daedalus._library.bash", "daedalus._library.bash",
"daedalus._library.powershell", "daedalus._library.powershell",
@@ -41,7 +42,7 @@ packages = [
[tool.pytest.ini_options] [tool.pytest.ini_options]
testpaths = ["ci/tests", "daedalus/tests", "python/tests", "bash/tests"] testpaths = ["ci/tests", "daedalus/tests", "python/tests", "bash/tests"]
pythonpath = [".", "python/src"] pythonpath = ["."]
[tool.coverage.run] [tool.coverage.run]
omit = ["*/tests/*", "*/__main__.py"] omit = ["*/tests/*", "*/__main__.py"]