From 7ebce2109e462cdd8939c650d9c3dcb42da311a1 Mon Sep 17 00:00:00 2001 From: nvaldez Date: Thu, 19 Nov 2026 10:27:57 +0100 Subject: [PATCH] feat: daedalus publish - guarded PyPI release (v0.12.0) - new script python/src/publish/publish.py: guards (clean tree, HEAD exactly tagged v, version not yet on PyPI, build+twine present), then the chained python -m build (the sdist must rebuild the wheel, SPEC 9.2.1) and twine check; --upload sends exactly this version's sdist+wheel, credentials stay with twine (~/.pypirc or prompt, __token__) - spec python/src/publish/spec.md (sections 1-7) first, then tests (13) in python/tests/test_publish.py, then code (SPEC 6.12) - fix release-blocking sdist defect (SPEC 9.2.1): empty powershell/ and batch/ folders now carry README placeholders and MANIFEST.in ships them, so an sdist installs again - release tooling in requirements.txt; registry entry, README row + section, CHANGELOG 0.12.0, version pins Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- CHANGELOG.md | 25 ++++ MANIFEST.in | 5 + README.md | 23 ++++ SPEC.md | 8 ++ batch/README.md | 6 + daedalus/registry.py | 5 + daedalus/tests/test_cli.py | 2 +- powershell/README.md | 6 + pyproject.toml | 4 +- python/src/publish/publish.py | 202 +++++++++++++++++++++++++++++ python/src/publish/spec.md | 111 ++++++++++++++++ python/tests/test_hello.py | 2 +- python/tests/test_publish.py | 236 ++++++++++++++++++++++++++++++++++ requirements.txt | 2 + 14 files changed, 634 insertions(+), 3 deletions(-) create mode 100644 MANIFEST.in create mode 100644 batch/README.md create mode 100644 powershell/README.md create mode 100644 python/src/publish/publish.py create mode 100644 python/src/publish/spec.md create mode 100644 python/tests/test_publish.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f7c7b8a..068f12e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,31 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and - Nothing yet. +## [0.12.0] - 2026-11-19 + +### Added in 0.12.0 + +- `daedalus publish`: a guarded one-command PyPI release. Checks the + working tree is clean, HEAD exactly tagged `v`, the version + not yet on PyPI (immutable once published), and `build` + `twine` + present in the running interpreter — then runs the **chained** + `python -m build` (the sdist must rebuild the wheel) and + `twine check`. `--upload` hands exactly this version's sdist and + wheel to twine; credentials stay with twine (`~/.pypirc` or the + prompt, `__token__`). Spec `python/src/publish/spec.md` first, then + tests, then code (SPEC 6.12). +- Release tooling (`build`, `twine`) added to `requirements.txt`. + +### Fixed in 0.12.0 + +- **Release-blocking sdist defect:** the sdist could not rebuild its + wheel (`package directory 'powershell' does not exist`) — the empty + `powershell/`/`batch/` folders were declared in packaging but never + shipped, so installing from an sdist of 0.11.0 failed. Empty script + folders now carry a `README.md` placeholder and `MANIFEST.in` ships + them (SPEC item 9.2.1). The chained build in `publish` keeps this + from recurring. + ## [0.11.0] - 2026-11-19 ### Added in 0.11.0 diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..177996c --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,5 @@ +# Ship the declared script folders even while they hold only +# README placeholders, so every sdist can rebuild its wheel +# (SPEC item 9.2.1). File types are filtered per 9.2 on install. +recursive-include powershell * +recursive-include batch * diff --git a/README.md b/README.md index 9cf1123..17af556 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ daedalus --list # list everything | `hello` | Python | test | Prints a hello line and the daedalus version | | `hello_bash` | Bash | test | Sample bash script through the shared help() interface | | `init` | Python | setup | Enable tab completion for daedalus: register argcomplete in bash (appends the managed hook block to ~/.bashrc), idempotent | +| `publish` | Python | release | Release daedalus to PyPI: guarded chained build (clean tree, exact `v` tag, PyPI-free version, tooling), twine check, `--upload` (credentials stay with twine) | Run the sample script: @@ -205,6 +206,28 @@ daedalus init --bashrc FILE # a different bashrc Exit code: `3` when `register-python-argcomplete` is nowhere to be found (reinstall daedalus — argcomplete is a declared dependency). +### publish + +`publish` releases the package itself. Guards first — clean working +tree, HEAD exactly tagged `v` (the version from +`pyproject.toml`), the version not yet on PyPI, and `build` + `twine` +available in the running interpreter — then a **chained** build +(the sdist must rebuild the wheel, SPEC item 9.2.1) and +`twine check`. Without `--upload` it stops there and prints the +artifacts; with `--upload` it uploads exactly this version's sdist +and wheel. Credentials never touch the script: twine prompts or +reads `~/.pypirc` (username `__token__`, your PyPI API token). + +```bash +daedalus publish # build + check, print next step +daedalus publish --upload # ... and upload to PyPI +``` + +Exit codes: `2` not run from a checkout, `3` dirty tree, `4` not +exactly tagged `v`, `5` build/twine missing, `6` version +already on PyPI (or PyPI unreachable), `7` build failed, `8` twine +check failed, `9` upload failed. + ## Getting started 1. Clone or copy this template and name the Git remote for your team. diff --git a/SPEC.md b/SPEC.md index 237d455..349fa2c 100644 --- a/SPEC.md +++ b/SPEC.md @@ -637,6 +637,14 @@ autotest results | `powershell/` | `daedalus/_library/powershell/` | `*.ps1` | | `batch/` | `daedalus/_library/batch/` | `*.bat` | +- **9.2.1** The source tree must be able to rebuild its wheel from + the sdist: every folder the packaging declares (including empty + `powershell/` and `batch/`) carries at least a `README.md` + placeholder, and `MANIFEST.in` ships both folders in the sdist. + A missing declared package directory is a release-blocking + defect: `python -m build` builds sdist and wheel chained, so a + broken sdist fails the release before it ships. + - **9.3** `LIBRARY_ROOT` is `PACKAGE_DIR/_library` when that folder exists (a normal install), otherwise `REPO_ROOT` (a checkout or an editable install). diff --git a/batch/README.md b/batch/README.md new file mode 100644 index 0000000..8fa9f6f --- /dev/null +++ b/batch/README.md @@ -0,0 +1,6 @@ +# Batch scripts live here + +`daedalus` runs every `*.bat` in this folder (SPEC.md section 9.2); +registered scripts are installed under `daedalus/_library/batch/`. +This README keeps the folder in git and in the sdist so the +sdist can rebuild its wheel (SPEC item 9.2.1). diff --git a/daedalus/registry.py b/daedalus/registry.py index d901fc7..cfe12a7 100644 --- a/daedalus/registry.py +++ b/daedalus/registry.py @@ -74,6 +74,11 @@ SCRIPTS: dict[str, Script] = { description="Enable tab completion for daedalus: register argcomplete in bash (appends the managed hook block to ~/.bashrc), idempotent", categories="setup", ), + "publish": Script( + path="python/src/publish/publish.py", + description="Release daedalus to PyPI: guarded chained build (clean tree, exact v tag, PyPI-free version, tooling), twine check, optional --upload (credentials stay with twine)", + categories="release", + ), } """Every script daedalus can run (SPEC.md section 4).""" diff --git a/daedalus/tests/test_cli.py b/daedalus/tests/test_cli.py index 24fbb2e..80845f6 100644 --- a/daedalus/tests/test_cli.py +++ b/daedalus/tests/test_cli.py @@ -150,7 +150,7 @@ def test_path_with_extra_words_is_a_usage_error(fake_registry, plain, capsys): assert "usage: daedalus --path " in capsys.readouterr().err -@pytest.mark.parametrize("installed, expected", [(True, "daedalus 1.2.3"), (False, "daedalus 0.11.0")]) +@pytest.mark.parametrize("installed, expected", [(True, "daedalus 1.2.3"), (False, "daedalus 0.12.0")]) def test_version(monkeypatch, capsys, installed, expected): """--version uses metadata or pyproject.toml in a checkout.""" def fake_version(_name): diff --git a/powershell/README.md b/powershell/README.md new file mode 100644 index 0000000..28a3096 --- /dev/null +++ b/powershell/README.md @@ -0,0 +1,6 @@ +# Powershell scripts live here + +`daedalus` runs every `*.ps1` in this folder (SPEC.md section 9.2); +registered scripts are installed under `daedalus/_library/powershell/`. +This README keeps the folder in git and in the sdist so the +sdist can rebuild its wheel (SPEC item 9.2.1). diff --git a/pyproject.toml b/pyproject.toml index 5253040..b455833 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "daedalus" -version = "0.11.0" +version = "0.12.0" description = "Template for daedalus: loose scripts in one repo, run with: daedalus [args...]" readme = "README.md" requires-python = ">=3.11" @@ -22,6 +22,7 @@ packages = [ "daedalus.gpgtools", "daedalus.hello", "daedalus.init", + "daedalus.publish", "daedalus._library.python.src", "daedalus._library.bash", "daedalus._library.powershell", @@ -32,6 +33,7 @@ packages = [ "daedalus.gpgtools" = "python/src/gpgtools" "daedalus.hello" = "python/src/hello" "daedalus.init" = "python/src/init" +"daedalus.publish" = "python/src/publish" "daedalus._library.python.src" = "python/src" "daedalus._library.bash" = "bash" "daedalus._library.powershell" = "powershell" diff --git a/python/src/publish/publish.py b/python/src/publish/publish.py new file mode 100644 index 0000000..4b9b921 --- /dev/null +++ b/python/src/publish/publish.py @@ -0,0 +1,202 @@ +"""Release daedalus to PyPI: guarded build, check, upload (publish spec). + +`daedalus publish` turns the checkout into a versioned sdist + wheel +pair and (with ``--upload``) hands them to PyPI via twine, only after +the guards pass (publish spec section 3): a clean tree, HEAD exactly +tagged ``v``, the version not yet on PyPI, and the build and +twine tooling present in the running interpreter. Credentials are +never handled by this script - twine prompts or reads ``~/.pypirc``. + +Run from the daedalus checkout: ``daedalus publish`` (spec item 1.4). +""" +from __future__ import annotations + +import argparse +import logging +import pathlib +import subprocess +import sys +import tomllib +import urllib.error +import urllib.request + +try: # SPEC item 6.9: complete publish's own arguments + from argcomplete import autocomplete +except ImportError: # pragma: no cover - completion off without argcomplete + autocomplete = None + +LOGGER = logging.getLogger(__name__) + +EXIT_OK = 0 +EXIT_NO_REPO = 2 +EXIT_DIRTY = 3 +EXIT_TAG = 4 +EXIT_TOOLING = 5 +EXIT_PYPI = 6 +EXIT_BUILD = 7 +EXIT_CHECK = 8 +EXIT_UPLOAD = 9 + +PY = sys.executable + +PYPI_VERSION_URL = "https://pypi.org/pypi/{name}/{version}/json" + + +def find_repo_root() -> pathlib.Path | None: + """The checkout root above the script (item 3.1), or None.""" + root = pathlib.Path(__file__).resolve().parents[3] + return root if (root / "pyproject.toml").is_file() else None + + +def read_project(pyproject: pathlib.Path) -> tuple[str, str]: + """Read [project] name and version from pyproject.toml (3.2).""" + project = tomllib.loads( + pyproject.read_text(encoding="utf-8"))["project"] + return project["name"], project["version"] + + +def run_in_cwd(cmd: list[str], + cwd: pathlib.Path | None = None) -> tuple[int, str]: + """Run a command (in cwd when given); return (code, output).""" + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=False, + cwd=str(cwd) if cwd else None) + except FileNotFoundError: + return 127, f"{' '.join(cmd)}: not found" + return result.returncode, (result.stdout or "") + (result.stderr or "") + + +def pypi_status(url: str) -> int | None: + """HTTP status of a PyPI JSON URL, or None when unreachable.""" + try: + with urllib.request.urlopen(url, timeout=30) as response: + return response.status + except urllib.error.HTTPError as err: + return err.code + except (urllib.error.URLError, ValueError): + return None + + +def artifact_names(name: str, version: str) -> tuple[str, str]: + """The version's sdist and wheel file names (items 3.4-3.7). + + The wheel is a pure-Python wheel (SPEC item 9.1), so its name + follows ``--py3-none-any.whl``. + """ + return (f"{name}-{version}.tar.gz", + f"{name}-{version}-py3-none-any.whl") + + +def cmd_publish(args: argparse.Namespace, run_cmd=None, + fetch_status=None) -> int: + """publish subcommand: guards, build, check, upload. + + Args: + args: parsed arguments (upload). + run_cmd: ``(cmd, cwd) -> (code, output)`` runner; + defaults to run_in_cwd. + fetch_status: ``(url) -> HTTP status | None``; + defaults to pypi_status. + + Returns: + Exit code per publish spec section 4. + """ + if run_cmd is None: + run_cmd = run_in_cwd + if fetch_status is None: + fetch_status = pypi_status + root = find_repo_root() + if root is None: + LOGGER.error("not a daedalus checkout: no pyproject.toml " + "above %s (item 3.1)", __file__) + return EXIT_NO_REPO + name, version = read_project(root / "pyproject.toml") + code, output = run_cmd(["git", "status", "--porcelain"], cwd=root) + if code != 0 or output.strip(): + LOGGER.error("working tree is dirty (or git failed); commit " + "or stash first - what ships must be committed " + "(item 3.3.1)") + return EXIT_DIRTY + code, output = run_cmd(["git", "describe", "--tags", "--exact-match", + "HEAD"], cwd=root) + if code != 0 or output.strip() != f"v{version}": + LOGGER.error("HEAD is not exactly tagged v%s; tag the release " + "first: git tag -a v%s -m \"...\" (item 3.3.2)", + version, version) + return EXIT_TAG + for module in ("build", "twine"): + code, _output = run_cmd([PY, "-m", module, "--version"], cwd=root) + if code != 0: + LOGGER.error("python -m %s is unavailable in this " + "interpreter; pipx inject daedalus build twine, " + "or pip install -r requirements.txt (item 3.3.3)", + module) + return EXIT_TOOLING + status = fetch_status( + PYPI_VERSION_URL.format(name=name, version=version)) + if status == 200: + LOGGER.error("%s %s is already on PyPI; a published version is " + "immutable - bump the version (item 3.3.4)", + name, version) + return EXIT_PYPI + if status != 404: + LOGGER.error("could not check PyPI (status %s); never publish " + "blind (item 3.3.4)", status) + return EXIT_PYPI + sdist, wheel = artifact_names(name, version) + print(f"release : {name} {version} " + "(tree clean, tag exact, PyPI free)") + print("build : python -m build (sdist -> wheel, chained)") + code, output = run_cmd([PY, "-m", "build"], cwd=root) + if code != 0: + LOGGER.error("build failed; fastest repro: %s -m build --wheel" + "\n%s", PY, output.strip()) + return EXIT_BUILD + code, output = run_cmd([PY, "-m", "twine", "check", + f"dist/{sdist}", f"dist/{wheel}"], cwd=root) + if code != 0: + LOGGER.error("twine check failed:\n%s", output.strip()) + return EXIT_CHECK + print(f"artifacts : dist/{sdist}, dist/{wheel}") + if not args.upload: + print("checked; upload this exact version with: " + "daedalus publish --upload") + return EXIT_OK + print("upload : twine (credentials from ~/.pypirc or the " + "prompt; username __token__ with your PyPI API token)") + code, output = run_cmd([PY, "-m", "twine", "upload", + f"dist/{sdist}", f"dist/{wheel}"], cwd=root) + if code != 0: + LOGGER.error("twine upload failed:\n%s", output.strip()) + return EXIT_UPLOAD + print(f"uploaded : {name} {version} -> " + f"https://pypi.org/project/{name}/{version}/") + return EXIT_OK + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + """Parse publish command-line arguments.""" + parser = argparse.ArgumentParser( + prog="publish", + description="Release daedalus to PyPI: guarded build, twine " + "check, optional upload", + ) + parser.add_argument("--upload", action="store_true", + help="upload this exact version to PyPI after " + "the checks pass (default: build and " + "check only)") + if autocomplete is not None: # SPEC item 6.9 + autocomplete(parser) + return parser.parse_args(argv) + + +def main(argv: list[str] | None = None) -> int: + """CLI entry point; return the exit code.""" + logging.basicConfig(level=logging.INFO, + format="%(levelname)-5s %(message)s") + return cmd_publish(parse_args(argv), run_in_cwd, pypi_status) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/python/src/publish/spec.md b/python/src/publish/spec.md new file mode 100644 index 0000000..2097ff9 --- /dev/null +++ b/python/src/publish/spec.md @@ -0,0 +1,111 @@ +# publish specification + +Complete description of `python/src/publish/publish.py`. Change this +file first, then tests, then code (SPEC items 6.11 and 6.12). Items +are cited as `publish spec item N.M`. + +## 1. Purpose + +- **1.1** `daedalus publish` releases the daedalus package itself: + it turns the checkout into a versioned, quality-checked + sdist + wheel pair in `dist/` and (with `--upload`) hands them + to PyPI via twine. +- **1.2** It exists so a release is one command with the + guards done for you: clean tree, exact tag, version not yet + on PyPI, tooling present in the running interpreter. +- **1.3** Credentials are never handled by this script: twine + reads `~/.pypirc` or prompts; nothing is recorded, forwarded, + or stored. +- **1.4** Runs from the daedalus checkout (editable pipx install + or the repository itself); there is no release from an + installed wheel copy - the tree is the source of truth. + +## 2. Command + +- **2.1** `daedalus publish [--upload]` - build and check the + release artifacts; `--upload` additionally uploads exactly this + version's artifacts to PyPI (section 3). + +## 3. Behavior + +- **3.1** Repo root: `pyproject.toml` found at three levels above + the script file (the `python/src/publish/` layout); missing is + exit 2. +- **3.2** Version: read from `[project] version` in that + `pyproject.toml` (tomllib); project name for PyPI checks from + `[project] name`. +- **3.3** Guards, in order, each stopping before anything is + built: + - **3.3.1** Dirty working tree (`git status --porcelain` in the + repo root, any output) is exit 3 - what ships must be what is + committed, and the tag must cover the exact tree. + - **3.3.2** HEAD not exactly tagged `v` + (`git describe --tags --exact-match HEAD`) is exit 4 - tag + first: `git tag -a v -m ...`. + - **3.3.3** The interpreter must provide `python -m build` and + `python -m twine` (`--version` probe each); a failure is exit 5 + with the inject hint (`pipx inject daedalus build twine`, or + the dev venv's `requirements.txt`). + - **3.3.4** `` `` already on PyPI + (`https://pypi.org/pypi///json` answering 200) + is exit 6 - a version, once published, is immutable; bump the + version. The probe runs through an injectable fetch; an + unreachable PyPI also stops with exit 6 (never publish blind). +- **3.4** Build: `python -m build` (sdist and wheel chained - the + sdist must be able to rebuild the wheel, SPEC item 9.2.1); + a failure is exit 7 with the troubleshooting pointer + (`python -m build --wheel` shows the error fastest). +- **3.5** Check: `python -m twine check dist/-*`; + anything twine dislikes is exit 8 - a README that will not + render blocks the release. +- **3.6** Without `--upload`, the run ends here: it prints the two + artifacts, the tag and version guard summary, and the `--upload` + command that would publish them. Exit 0. +- **3.7** With `--upload`: `python -m twine upload` over exactly + this version's sdist and wheel (never `dist/*` - stale artifacts + of other versions stay untouched and un-uploaded). Credentials: + twine prompts or reads `~/.pypirc` (API token as the username + `__token__`). Failure is exit 9; success prints the PyPI URL. + +## 4. Exit codes + +| Code | Meaning | +| --- | --- | +| 0 | checked (no `--upload`), or checked and uploaded | +| 2 | not run from a daedalus checkout (no pyproject.toml above) | +| 3 | dirty working tree | +| 4 | HEAD is not exactly tagged `v` | +| 5 | build/twine tooling missing in this interpreter | +| 6 | version already on PyPI, or PyPI unreachable | +| 7 | build failed | +| 8 | twine check failed | +| 9 | twine upload failed | + +## 5. Files written + +- **5.1** `dist/` in the repo root: the version's sdist and wheel + (plus `build/` and egg-info that `python -m build` leaves + behind); nothing else. The script never touches `~/.pypirc`, + keychains, or tokens. + +## 6. Testing approach + +- **6.1** Tests live in `python/tests/test_publish.py`; no + network, no git state, no real build (daedalus agent rule 5.6): + every guard and step runs through an injected runner + `(cmd, cwd) -> (code, output)` and an injectable PyPI fetch; + the default runner shells out with cwd and the default fetch + reads the PyPI JSON URL with urllib (30 s timeout). +- **6.2** Covered groups: pyproject discovery and the version + read, each guard branch in order (dirty tree, tag mismatch, + tooling missing, already published, PyPI unreachable), the + chained build command, the twine check command, the upload + gate (`--upload` absent/present) and its exact artifact + selection, and the CLI wiring. + +## 7. References + +- **7.1** Packaging truth: SPEC items 9.1-9.5, 9.2.1. +- **7.2** Repository rules: SPEC items 6.6 (tests), 9.8 (version + bump). +- **7.3** History: `CHANGELOG.md` entry 0.12.0. diff --git a/python/tests/test_hello.py b/python/tests/test_hello.py index 28aee0f..7caf736 100644 --- a/python/tests/test_hello.py +++ b/python/tests/test_hello.py @@ -34,7 +34,7 @@ def test_app_version_falls_back_to_pyproject(monkeypatch): raise hello.importlib.metadata.PackageNotFoundError(_name) monkeypatch.setattr(hello.importlib.metadata, "version", not_found) - assert hello.app_version() == "0.11.0" + assert hello.app_version() == "0.12.0" def test_help_exits_zero(capsys): diff --git a/python/tests/test_publish.py b/python/tests/test_publish.py new file mode 100644 index 0000000..2f170ce --- /dev/null +++ b/python/tests/test_publish.py @@ -0,0 +1,236 @@ +"""Tests for the publish script: guarded PyPI release (publish spec). + +No network, no git state, no real build: every guard and step runs +through an injected runner and an injectable PyPI status fetch +(daedalus agent rule 5.6, publish spec item 6.1). +""" +import re + +from daedalus.publish import publish + + +def make_runner(script, calls=None): + """Build an injectable run_cmd(cmd, cwd) from {prefix: (code, out)}.""" + + def run_cmd(cmd, cwd=None): + if calls is not None: + calls.append((list(cmd), cwd)) + for prefix, reply in script.items(): + if list(cmd)[:len(prefix)] == list(prefix): + return reply + raise AssertionError(f"unexpected command: {cmd}") + + return run_cmd + + +def clean_runner(version, calls=None): + """A runner with all guards green for `version`.""" + py = publish.PY + return make_runner({ + ("git", "status"): (0, ""), + ("git", "describe"): (0, f"v{version}\n"), + (py, "-m", "build", "--version"): (0, "build 1.6.1\n"), + (py, "-m", "twine", "--version"): (0, "twine 7.0.0\n"), + (py, "-m", "build"): (0, "Successfully built\n"), + (py, "-m", "twine", "check"): (0, "PASSED\n"), + (py, "-m", "twine", "upload"): (0, "Uploaded\n"), + }, calls) + + +# --- pyproject discovery (publish spec items 3.1-3.2) + + +def test_read_project_from_this_repo(): + """The script's own repo resolves: name daedalus, semver version.""" + root = publish.find_repo_root() + assert root is not None + name, version = publish.read_project(root / "pyproject.toml") + assert name == "daedalus" + assert re.fullmatch(r"\d+\.\d+\.\d+", version) + + +# --- guards (publish spec item 3.3) + + +def test_dirty_tree_stops_before_building(): + """A dirty tree is exit 3; no build runs.""" + name, version = publish.read_project( + publish.find_repo_root() / "pyproject.toml") + calls = [] + runner = make_runner({("git", "status"): (0, " M file\n")}, calls) + args = publish.parse_args([]) + assert publish.cmd_publish(args, runner, + lambda _u: 404) == 3 + assert not any(cmd[0] == "git" and cmd[1] == "describe" + or cmd[1:3] == ["-m", "build"] + for cmd, _cwd in calls) + + +def test_tag_mismatch_stops(): + """HEAD tagged with another version is exit 4.""" + calls = [] + runner = make_runner({ + ("git", "status"): (0, ""), + ("git", "describe"): (0, "v0.0.1\n"), + }, calls) + args = publish.parse_args([]) + assert publish.cmd_publish(args, runner, + lambda _u: 404) == 4 + + +def test_tag_probe_failure_stops(): + """An untagged HEAD (describe fails) is exit 4.""" + runner = make_runner({ + ("git", "status"): (0, ""), + ("git", "describe"): (128, "no tag\n"), + }) + assert publish.cmd_publish(publish.parse_args([]), runner, + lambda _u: 404) == 4 + + +def repo_version(): + """The version the checkout's pyproject carries.""" + _name, version = publish.read_project( + publish.find_repo_root() / "pyproject.toml") + return version + + +def test_tooling_missing_stops(): + """No build/twine in the interpreter is exit 5.""" + runner = make_runner({ + ("git", "status"): (0, ""), + ("git", "describe"): (0, f"v{repo_version()}\n"), + (publish.PY, "-m", "build", "--version"): (127, "no module"), + (publish.PY, "-m", "twine", "--version"): (0, "twine\n"), + }) + assert publish.cmd_publish(publish.parse_args([]), runner, + lambda _u: 404) == 5 + + +def test_already_on_pypi_stops(): + """A published version is exit 6 before any artifact is built.""" + calls = [] + runner = make_runner({ + ("git", "status"): (0, ""), + ("git", "describe"): (0, f"v{repo_version()}\n"), + (publish.PY, "-m", "build", "--version"): (0, "build\n"), + (publish.PY, "-m", "twine", "--version"): (0, "twine\n"), + }, calls) + assert publish.cmd_publish(publish.parse_args([]), runner, + lambda _u: 200) == 6 + assert not any(cmd[1:3] == ["-m", "build"] and len(cmd) == 3 + for cmd, _ in calls) + + +def test_pypi_unreachable_stops(): + """A blind publish is refused: unreachable PyPI is exit 6.""" + runner = make_runner({ + ("git", "status"): (0, ""), + ("git", "describe"): (0, f"v{repo_version()}\n"), + (publish.PY, "-m", "build", "--version"): (0, "build\n"), + (publish.PY, "-m", "twine", "--version"): (0, "twine\n"), + }) + assert publish.cmd_publish(publish.parse_args([]), runner, + lambda _u: None) == 6 + + +# --- build, check, upload (publish spec items 3.4-3.7) + + +def test_check_only_flow_builds_and_stops(tmp_path, capsys): + """Without --upload: chained build, twine check, exit 0.""" + name, version = publish.read_project( + publish.find_repo_root() / "pyproject.toml") + calls = [] + assert publish.cmd_publish(publish.parse_args([]), + clean_runner(version, calls), + lambda _u: 404) == 0 + build = [cmd for cmd, _ in calls + if cmd[1:3] == ["-m", "build"] and len(cmd) == 3] + assert len(build) == 1 # chained, not two runs + assert not any(cmd[3:4] == ["upload"] for cmd, _ in calls) + out = capsys.readouterr().out + assert f"{name}-{version}.tar.gz" in out + assert "--upload" in out # the next-step hint + + +def test_upload_sends_exactly_this_version(): + """--upload passes only this version's sdist and wheel.""" + name, version = publish.read_project( + publish.find_repo_root() / "pyproject.toml") + calls = [] + assert publish.cmd_publish(publish.parse_args(["--upload"]), + clean_runner(version, calls), + lambda _u: 404) == 0 + upload = [cmd for cmd, _ in calls if cmd[3:4] == ["upload"]][0] + assert upload[-2] == f"dist/{name}-{version}.tar.gz" + assert upload[-1].startswith(f"dist/{name}-{version}-") + assert upload[-1].endswith(".whl") + + +def test_build_failure_is_7(): + """A failed chained build is exit 7.""" + name, version = publish.read_project( + publish.find_repo_root() / "pyproject.toml") + py = publish.PY + runner = make_runner({ + ("git", "status"): (0, ""), + ("git", "describe"): (0, f"v{version}\n"), + (py, "-m", "build", "--version"): (0, "build\n"), + (py, "-m", "twine", "--version"): (0, "twine\n"), + (py, "-m", "build"): (1, "error\n"), + }) + assert publish.cmd_publish(publish.parse_args([]), runner, + lambda _u: 404) == 7 + + +def test_check_failure_is_8(): + """twine check rejecting the artifacts is exit 8.""" + name, version = publish.read_project( + publish.find_repo_root() / "pyproject.toml") + py = publish.PY + runner = make_runner({ + ("git", "status"): (0, ""), + ("git", "describe"): (0, f"v{version}\n"), + (py, "-m", "build", "--version"): (0, "build\n"), + (py, "-m", "twine", "--version"): (0, "twine\n"), + (py, "-m", "build"): (0, "ok\n"), + (py, "-m", "twine", "check"): (1, "Failed\n"), + }) + assert publish.cmd_publish(publish.parse_args([]), runner, + lambda _u: 404) == 8 + + +def test_upload_failure_is_9(): + """twine upload failing is exit 9.""" + name, version = publish.read_project( + publish.find_repo_root() / "pyproject.toml") + py = publish.PY + runner = make_runner({ + ("git", "status"): (0, ""), + ("git", "describe"): (0, f"v{version}\n"), + (py, "-m", "build", "--version"): (0, "build\n"), + (py, "-m", "twine", "--version"): (0, "twine\n"), + (py, "-m", "build"): (0, "ok\n"), + (py, "-m", "twine", "check"): (0, "PASSED\n"), + (py, "-m", "twine", "upload"): (1, "403\n"), + }) + assert publish.cmd_publish(publish.parse_args(["--upload"]), runner, + lambda _u: 404) == 9 + + +def test_cli_wires_flow(monkeypatch): + """The CLI hands cmd_publish the real runner and fetch.""" + seen = {} + + def fake_publish(args, run_cmd, fetch_status): + seen["args"] = args + seen["run_cmd"] = run_cmd + seen["fetch"] = fetch_status + return 0 + + monkeypatch.setattr(publish, "cmd_publish", fake_publish) + assert publish.main(["--upload"]) == 0 + assert seen["args"].upload is True + assert seen["run_cmd"] is publish.run_in_cwd + assert seen["fetch"] is publish.pypi_status diff --git a/requirements.txt b/requirements.txt index 7c412e6..79772a1 100644 --- a/requirements.txt +++ b/requirements.txt @@ -6,3 +6,5 @@ pyyaml>=6.0 shellcheck-py>=0.10 setuptools>=68 argcomplete>=3.3 +build>=1.6 +twine>=6.0