diff --git a/scripts/check-release-owed.py b/scripts/check-release-owed.py new file mode 100644 index 00000000..e8d44536 --- /dev/null +++ b/scripts/check-release-owed.py @@ -0,0 +1,347 @@ +#!/usr/bin/env python3 +"""Does this tree declare a version that no tag carries? + +The release chain asks its version question five times, and every one of the five +starts from a tag that already exists: `check-release-tag.py` compares one tag with +the tagged tree, `check-release-published.py` asks whether one tag is published, +`check-release-orphan-tags.py` enumerates tags that are already there, and +`check-release-artifact-version.py` / `check-release-prompt.py` read a built product. +None asks whether a tag **should** exist -- so a tree that declares a version nothing +has tagged is invisible to all five, and that is the one failure in this chain that +gets worse with every merge and turns nothing red. + +Measured 2026-11-18 (`cyc20261118-095848`) on master `d5b17fea`: + +* `emrg/__init__.py` declares `0.3.59`; +* `git describe --tags` answers `v0.3.58`; +* `git rev-list --count v0.3.58..HEAD` answers **9**. + +Nine merged commits -- including two that change what every installation reads -- were +on master and reached no host, because a host only receives them from a published +release. The condition had been noticed by hand twice, once per release, each time +re-deriving the same three facts. This tool is that reading, mechanised. + +Versions compare by **numeric parts**, never by string and never by tag date: `0.3.10` +is newer than `0.3.9`, and a tag's commit date says nothing about which version is +later. A tag that does not parse as three dotted numbers is counted and reported, never +sorted in as though it were one -- otherwise an unrelated tag named `latest` would +silently become "the newest release". + +Only a tag **that can publish a release** counts: `build-release.yml` fires on +`tags: ["v*"]`, and its `verify-tag` job rejects a lightweight tag before any platform +builds, so neither a `v`-less name nor a lightweight tag can carry a version. Each is +reported by name as a near miss rather than accepted, because accepting either answers +`nothing is owed` for work that reached no host -- and both shapes have happened here +(`v0.2.97` went out lightweight). + +It is a **screen for a host, not a CI gate.** On an unreleased master it is red by +design, so wiring it into CI would make the release cadence a permanently failing check +and teach its readers to ignore it. Its role is the one `bump-version.py --check` and +`check-release-tag.py` already play: the command run before cutting a release. + +Exit codes, the family's contract: + + 0 nothing is owed: the declared version is the newest tag's version + 1 the declared version is not the newest tag's version, and **which way** decides the + remedy: *newer* means a release is owed (both versions and the commit count are + printed), *older* means this checkout is behind a release that already exists and + must not be tagged -- publishing an older version would put it ahead of a newer one. + Reporting the second as the first, measured 2026-11-18 (`cyc20261118-102744`), sent a + reader to `git tag -a v0.3.59` on a tree whose newest release was `v0.3.60`. + 2 not measurable: no version declaration could be read, or the repository could + not be read at all (no `git`, not a work tree). Never 0 -- a guard that passes + because it could not read its subject is the defect this one exists to catch. + +An empty tag list is a **measurement**, not an unmeasured one: `git tag --list` answered, +and the answer is that nothing carries the declaration. So that case is exit 1, where a +repository that cannot be read at all is exit 2. + +Usage: + + uv run --no-sync python3 scripts/check-release-owed.py + uv run --no-sync python3 scripts/check-release-owed.py --root /path/to/checkout +""" + +from __future__ import annotations + +import argparse +import re +import subprocess +import sys +from pathlib import Path + +#: The tree read when `--root` is not given: the checkout this script lives in. +REPO_ROOT = Path(__file__).resolve().parent.parent + +#: Where the version is declared. The same file and the same anchored shape +#: `check-release-tag.py` and `tests/test_version_sync.py` read, so this reader and +#: those cannot disagree about what a declaration looks like. +VERSION_SOURCE = Path("emrg") / "__init__.py" +_DECLARATION = re.compile(r'^__version__\s*=\s*"([^"]+)"', re.MULTILINE) + +#: The version shape a tag may carry: three dotted numbers, optional `v`. +_TAG = re.compile(r"^v?(\d+)\.(\d+)\.(\d+)$") + +#: The shape that actually **triggers a release**: `build-release.yml` fires on +#: `tags: ["v*"]` and nothing else. A tag spelled `0.3.59` never builds, never publishes and +#: never reaches a host -- so it cannot be what "carries" a version, however much it looks +#: like one. Measured 2026-11-18 (`cyc20261118-104130`): a tree declaring `0.3.59` whose only +#: tag was `0.3.59` answered `nothing is owed`, which is the exact false clean this tool +#: exists to prevent -- the work had shipped to nobody and the guard said it had. +_RELEASE_TAG = re.compile(r"^v(\d+)\.(\d+)\.(\d+)$") + + +class Unmeasurable(Exception): + """The question could not be put to this tree at all -- exit 2's cause, never a pass.""" + + +def declared_version(root: Path) -> str: + """The tree's declared version, or `Unmeasurable` when it does not name exactly one. + + Two declarations are unmeasurable rather than a choice: the file names two versions, + so it does not name one. `tests/test_no_duplicate_sources.py` owns that question and + this reader must not answer it by picking the first. + """ + try: + text = (root / VERSION_SOURCE).read_text(encoding="utf-8") + except OSError as exc: + raise Unmeasurable(f"no version declaration could be read from {VERSION_SOURCE}: {exc}") + found = _DECLARATION.findall(text) + if len(found) != 1: + raise Unmeasurable( + f"{VERSION_SOURCE} carries {len(found)} `__version__ = \"...\"` declaration(s), " + f"so it does not name one version" + ) + version = found[0].strip() + if not version: + raise Unmeasurable(f"{VERSION_SOURCE} declares an empty version") + return version + + +def _git(root: Path, *args: str) -> str: + """Run one git command in `root` and return its stdout, or raise `Unmeasurable`.""" + try: + proc = subprocess.run( + ["git", *args], + cwd=root, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + ) + except OSError as exc: + raise Unmeasurable(f"git could not be run in {root}: {exc}") + if proc.returncode != 0: + detail = (proc.stderr or proc.stdout or "").strip() + raise Unmeasurable(f"`git {' '.join(args)}` failed in {root}: {detail}") + return proc.stdout + + +def _require_a_work_tree_of_its_own(root: Path) -> None: + """`root` must be the repository's top level, not a directory inside another one. + + `git` walks **up** to find a repository, so pointing this tool at any subdirectory of + any checkout makes it read that enclosing repository's tags and answer about a tree + it was not asked about -- measured 2026-11-18 by the test that gives it a plain + directory inside this checkout: it reported this checkout's 158 tags for a directory + that is not a work tree at all. A reading about the wrong repository is worse than no + reading, so the mismatch is refused. + """ + top = Path(_git(root, "rev-parse", "--show-toplevel").strip()).resolve() + if top != root: + raise Unmeasurable( + f"{root} is inside the repository at {top}, not a work tree of its own -- " + f"the tags read would be that repository's, so this tree's release state " + f"cannot be read from here. Point --root at a work tree's top level." + ) + + +def tags(root: Path) -> tuple[list[tuple[tuple[int, int, int], str]], list[str], list[str], list[str]]: + """Every **release** tag, newest last, plus three buckets of names that are not one. + + A tag carries a version only when all three hold: + + * it matches `_RELEASE_TAG` - `build-release.yml` triggers on `tags: ["v*"]` and nothing + else, so a `v`-less tag builds nothing; + * it is **annotated**. The workflow's `verify-tag` job reads `object.type` from the API + and exits 1 unless it is `tag`, so a lightweight tag stops the run before any platform + builds and no release is published. This repository has already shipped one: `v0.2.97` + was lightweight while every release since `v0.2.94` is annotated, and the instruction + that produced it was the bare `git tag v` (`tests/test_release_tag_form.py` + records the measurement). `%(objecttype)` answers the same question locally; + * therefore neither `v`-less nor lightweight can be what "carries" a version, and + counting either would answer `nothing is owed` for work that reached no host. + + The buckets are kept apart because the remedies differ: a version-shaped tag missing its + `v`, a version-shaped tag that is lightweight, and an unrelated name (`latest`) which is + only noise. + + Sorted by numeric parts, because string order puts `v0.3.9` after `v0.3.10`. One + `for-each-ref` call answers both name and type, rather than N `cat-file` calls. + """ + _require_a_work_tree_of_its_own(root) + text = _git(root, "for-each-ref", "refs/tags", "--format=%(refname:short)%09%(objecttype)") + annotated: set[str] = set() + for line in text.splitlines(): + parts = line.rstrip("\r\n").split("\t") + if len(parts) == 2 and parts[1] == "tag": + annotated.add(parts[0]) + names = [line.rstrip("\r\n").split("\t")[0] for line in text.splitlines() if line.strip()] + + parsed: list[tuple[tuple[int, int, int], str]] = [] + lightweight: list[str] = [] + vless: list[str] = [] + skipped: list[str] = [] + for name in names: + release = _RELEASE_TAG.match(name) + if release is not None: + if name in annotated: + parsed.append((tuple(int(part) for part in release.groups()), name)) + else: + lightweight.append(name) + continue + if _TAG.match(name) is not None: + vless.append(name) + continue + skipped.append(name) + parsed.sort() + return parsed, lightweight, vless, skipped + + +def _name_list(names: list[str], limit: int = 5) -> str: + """A few names, then a count -- because this checkout has 79 lightweight tags. + + Measured 2026-11-18 (`cyc20261118-105553`) on this repository: naming all 79 pushed the + `A RELEASE IS OWED` line off the visible width, hiding the only actionable sentence + behind a list nobody reads to the end. The count is the fact; the names are examples. + """ + ordered = sorted(names) + if len(ordered) <= limit: + return ", ".join(ordered) + return f"{', '.join(ordered[:limit])} and {len(ordered) - limit} more" + + +def check(root: Path) -> int: + """Print the reading and return the exit code.""" + print(f"tree: {root}") + try: + declared = declared_version(root) + parsed, lightweight, vless, skipped = tags(root) + except Unmeasurable as exc: + print(f"not measurable: {exc}") + return 2 + print(f"declared: {declared} ({VERSION_SOURCE})") + + # A version-shaped declaration is compared as parts too, so `0.3.10` is not read as + # older than `0.3.9`; a declaration that is not three dotted numbers cannot be + # ordered against the tags at all. + declared_match = _TAG.match(declared) + if declared_match is None: + print( + f"not measurable: the declared version {declared!r} is not three dotted " + f"numbers, so it cannot be ordered against a tag" + ) + return 2 + + skipped_note = f", {len(skipped)} tag(s) not version-shaped and not compared" if skipped else "" + vless_note = ( + f", {len(vless)} version-shaped tag(s) with no `v` and therefore no build: " + f"{_name_list(vless)}" + if vless + else "" + ) + light_note = ( + f", {len(lightweight)} lightweight tag(s) that verify-tag rejects and so publish " + f"nothing: {_name_list(lightweight)}" + if lightweight + else "" + ) + if not parsed: + print(f"tags: none that would publish a release{light_note}{vless_note}{skipped_note}") + causes = [] + if vless: + causes.append( + f"the version-shaped tag(s) {_name_list(vless)} carry it, but " + f"`build-release.yml` triggers on `v*` only, so a tag spelled without the `v` " + f"builds nothing and publishes nothing" + ) + if lightweight: + causes.append( + f"the tag(s) {_name_list(lightweight)} carry it, but they are " + f"lightweight and `verify-tag` requires an annotated tag, so the run stops " + f"before any platform builds" + ) + carried = (" -- " + "; and ".join(causes)) if causes else "" + print( + f"A RELEASE IS OWED: the tree declares {declared} and no tag that publishes a " + f"release carries it{carried}" + ) + return 1 + + newest = parsed[-1][1] + print( + f"tags: {len(parsed)} that would publish a release, newest {newest}" + f"{light_note}{vless_note}{skipped_note}" + ) + + declared_parts = tuple(int(part) for part in declared_match.groups()) + newest_parts = parsed[-1][0] + + if declared == newest.lstrip("v"): + print(f"OK: nothing is owed - the tree declares {declared} and {newest} carries it") + return 0 + + if declared_parts < newest_parts: + # The tree is OLDER than the newest tag: a checkout behind the release, or a branch + # cut before it. Nothing merged unreleased, and the remedy is not a tag - tagging an + # older version would publish it as the latest, ahead of a newer one that already + # exists. Keep telling this apart from "owed": reporting it as owed sends a reader to + # cut a release of a version that is already superseded. + print( + f"THIS CHECKOUT IS BEHIND: the tree declares {declared} and the newest tag is " + f"{newest}, so nothing here is waiting to be published -- the tree predates a " + f"release that already exists. Update the checkout to {newest} (or to master) " + f"before reading its release state; do NOT tag {declared}, because that would " + f"publish an older version as the newest release, ahead of {newest}." + ) + return 1 + + try: + count_text = _git(root, "rev-list", "--count", f"{newest}..HEAD").strip() + count: int | None = int(count_text) + except (Unmeasurable, ValueError): + # The comparison is still a fact without the count, so it is reported with the + # count named as unread rather than withheld. + count = None + reach = ( + f"{count} commit(s) on HEAD are not in {newest}" + if count is not None + else f"the commit count between {newest} and HEAD could not be read" + ) + print( + f"A RELEASE IS OWED: the tree declares {declared} and the newest tag is {newest} " + f"-- {reach}, so that work has merged and reaches no host until it is published. " + f"Cut the release: bump to the version you mean to ship, merge it, then " + f"`git tag -a v{declared} -m \"emrg v{declared}\"` and push the tag (the tag is the " + f"only trigger of build-release.yml). Run `scripts/check-release-tag.py v{declared}` " + f"first, and `scripts/check-release-published.py v{declared}` afterwards." + ) + return 1 + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description="A tree that declares a version no tag carries owes a release.", + ) + parser.add_argument( + "--root", + type=Path, + default=REPO_ROOT, + help="the tree to read (default: the checkout this script lives in)", + ) + args = parser.parse_args(argv) + return check(args.root.resolve()) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_a_tree_reading_guard_names_its_tree.py b/tests/test_a_tree_reading_guard_names_its_tree.py index c7ca7f81..e7c86772 100644 --- a/tests/test_a_tree_reading_guard_names_its_tree.py +++ b/tests/test_a_tree_reading_guard_names_its_tree.py @@ -189,6 +189,7 @@ def _carries(subjects: tuple[str, ...]) -> bool: "check-undefined-names.py": ("--root",), "check-workflows.py": ("--root",), "check-gui-package-refs.py": ("--root",), + "check-release-owed.py": ("--root",), } #: Guards that advertise `--root` in their own `--help` and are deliberately **not** in the @@ -304,6 +305,17 @@ def _refusal_reason(out: str) -> str: "`tmp_path` and pins the `tree:` line and each exit code (0 identical / 1 a " "product carries a different text / 2 nothing could be read)" ), + "check-release-owed.py": ( + "answers rc **1** on any checkout that owes a release, which is correct rather than " + "a defect - master stands in exactly that state between a version bump merging and " + "its tag being cut, so the bare loop's rc-0 requirement would turn every such " + "interval into a failing suite, which is also why this guard is a host-side screen " + "and not a CI gate. It reads a working tree (`--root`, default `REPO_ROOT`) and " + "names it on the first line before the verdict, and that naming IS verified rather " + "than classified: `tests/test_check_release_owed.py` builds `tmp_path` repositories " + "and pins the `tree:` line and each exit code (0 nothing owed / 1 a release is owed " + "/ 2 no declaration or no repository)" + ), } #: Answers about something other than a working tree, so the rule does not apply - each diff --git a/tests/test_check_release_owed.py b/tests/test_check_release_owed.py new file mode 100644 index 00000000..65c12514 --- /dev/null +++ b/tests/test_check_release_owed.py @@ -0,0 +1,313 @@ +"""`scripts/check-release-owed.py` — a tree declaring an untagged version owes a release. + +Every case builds its own git repository under `tmp_path`: the guard runs `git` in the tree +it is given, so a fixture that reused this checkout would measure this checkout's tags +instead of the layout it means to test. +""" + +from __future__ import annotations + +import importlib.util +import subprocess +from pathlib import Path + +SCRIPT = Path(__file__).resolve().parent.parent / "scripts" / "check-release-owed.py" + +#: Pinned so a host's own git identity never decides whether a fixture can commit. +_GIT_ID = ( + "-c", "user.email=test@example.invalid", + "-c", "user.name=check-release-owed test", + "-c", "commit.gpgsign=false", +) + + +def _load(): + spec = importlib.util.spec_from_file_location("check_release_owed", SCRIPT) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def _git(root: Path, *args: str) -> None: + proc = subprocess.run( + ["git", *_GIT_ID, *args], cwd=root, capture_output=True, text=True, + encoding="utf-8", errors="replace", + ) + assert proc.returncode == 0, f"git {' '.join(args)} failed: {proc.stderr}" + + +def _repo( + root: Path, + declared: str | None, + tags: list[str], + *, + commits_after_tag: int = 0, + lightweight: list[str] | None = None, +) -> Path: + """A repository whose tree declares `declared` and carries `tags`. + + `tags` are created **annotated**, because that is what a release tag is: the workflow's + `verify-tag` job rejects a lightweight tag, so a fixture building lightweight ones would + be testing a shape that publishes nothing. `commits_after_tag` adds that many further + commits on top, so the "how many commits are not in the release" reading has something + to count. `lightweight` names tags to create the other way, for the test that asks what + the guard does with them. + """ + root.mkdir(parents=True, exist_ok=True) + _git(root, "init") + (root / "emrg").mkdir() + body = '# nothing\n' if declared is None else f'__version__ = "{declared}"\n' + (root / "emrg" / "__init__.py").write_text(body, encoding="utf-8") + _git(root, "add", "-A") + _git(root, "commit", "-m", "first") + for tag in tags: + _git(root, "tag", "-a", tag, "-m", f"emrg {tag}") + for tag in lightweight or []: + _git(root, "tag", tag) + for index in range(commits_after_tag): + (root / "note.txt").write_text(f"{index}\n", encoding="utf-8") + _git(root, "add", "-A") + _git(root, "commit", "-m", f"after {index}") + return root + + +def _run(mod, root: Path, capsys) -> tuple[int, str]: + """Call `check` the way `main` does, returning its code and everything it printed.""" + rc = mod.check(root) + captured = capsys.readouterr() + return rc, captured.out + + +def test_a_lightweight_tag_publishes_nothing_so_a_release_is_still_owed(tmp_path, capsys): + """`verify-tag` rejects a lightweight tag, so it cannot carry a version. + + Measured 2026-11-18 (`cyc20261118-105553`): on a tree declaring `0.3.59` whose tag was a + **lightweight** `v0.3.59`, the guard answered `rc 0, nothing is owed` - while + `git cat-file -t` says `commit`, and `build-release.yml`'s `verify-tag` job exits 1 + unless the object type is `tag`, so the run stops before any platform builds. This + repository has shipped one such tag (`v0.2.97`), produced by the bare + `git tag v` that `tests/test_release_tag_form.py` records. + """ + mod = _load() + root = _repo(tmp_path / "light", "0.3.59", [], lightweight=["v0.3.59"]) + + rc, out = _run(mod, root, capsys) + + assert rc == 1, f"a lightweight tag publishes nothing, so a release is still owed:\n{out}" + assert "A RELEASE IS OWED" in out, out + assert "lightweight" in out, ( + f"the near miss has to be named, and by the word that says why it failed:\n{out}") + + +def test_an_annotated_tag_of_the_same_version_does_satisfy_it(tmp_path, capsys): + """The other direction, so the fix above cannot be "always report owed".""" + mod = _load() + root = _repo(tmp_path / "annotated", "0.3.59", ["v0.3.59"]) + + rc, out = _run(mod, root, capsys) + + assert rc == 0, out + assert "nothing is owed" in out, out + + +def test_a_tag_without_the_v_publishes_nothing_so_a_release_is_still_owed(tmp_path, capsys): + """`build-release.yml` triggers on `tags: ["v*"]`, so a `v`-less tag is not a release. + + Measured 2026-11-18 (`cyc20261118-104130`) on exactly this fixture: the guard answered + **rc 0, "nothing is owed"** for a tree declaring `0.3.59` whose only tag was `0.3.59`. + That tag builds nothing and publishes nothing, so the work had shipped to nobody while + the guard - whose whole purpose is catching that - reported it as shipped. The tag passes + the version regex but must not count as a release. + """ + mod = _load() + root = _repo(tmp_path / "vless", "0.3.59", ["0.3.59"]) + + rc, out = _run(mod, root, capsys) + + assert rc == 1, f"a tag that triggers no build cannot satisfy the declaration:\n{out}" + assert "A RELEASE IS OWED" in out, out + assert "0.3.59" in out, out + assert "no `v`" in out, ( + f"the near miss has to be named, or the reader cannot tell it from no tag at all:\n{out}") + + +def test_a_v_prefixed_tag_of_the_same_version_does_satisfy_it(tmp_path, capsys): + """The other direction, so the fix above cannot be "always report owed".""" + mod = _load() + root = _repo(tmp_path / "vfull", "0.3.59", ["v0.3.59"]) + + rc, out = _run(mod, root, capsys) + + assert rc == 0, out + assert "nothing is owed" in out, out + + +def test_a_tree_older_than_the_newest_tag_is_behind_not_owed(tmp_path, capsys): + """A checkout behind the release must not be told to cut one. + + Measured 2026-11-18 (`cyc20261118-102744`) on a fixture built exactly like this: a tree + declaring `0.3.59` whose newest tag is `v0.3.60` was reported as `A RELEASE IS OWED ... + 1 commit(s) on HEAD are not in v0.3.60, so that work has merged` with the remedy + `git tag -a v0.3.59` - three false statements in one verdict, because nothing had merged + unreleased and that tag would publish an **older** version ahead of `v0.3.60`. + + The direction of the difference is the whole answer, so it is asserted both ways: the + message must say the checkout is behind, must not offer the tag remedy, and the newer + case must still say a release is owed. + """ + mod = _load() + root = tmp_path / "behind" + root.mkdir() + _git(root, "init") + (root / "emrg").mkdir() + decl = root / "emrg" / "__init__.py" + decl.write_text('__version__ = "0.3.60"\n', encoding="utf-8") + _git(root, "add", "-A") + _git(root, "commit", "-m", "release 0.3.60") + _git(root, "tag", "-a", "v0.3.60", "-m", "emrg v0.3.60") + # The declaration moves backwards on top of that release: a stale checkout's shape. + decl.write_text('__version__ = "0.3.59"\n', encoding="utf-8") + _git(root, "add", "-A") + _git(root, "commit", "-m", "an older declaration on top") + + rc, out = _run(mod, root, capsys) + + assert rc == 1, out + assert "BEHIND" in out, f"the verdict has to name the state it found: {out}" + assert "A RELEASE IS OWED" not in out, ( + f"nothing merged unreleased here, so 'owed' is the wrong verdict: {out}") + assert f"tag -a v0.3.59" not in out, ( + f"the remedy must not invite tagging an older version over v0.3.60: {out}") + assert "v0.3.60" in out and "0.3.59" in out, ( + f"both versions are the evidence for the direction: {out}") + + +def test_the_tree_it_read_is_named_before_the_verdict(tmp_path, capsys): + """The family's rule: a tree-reading guard names the tree it read, first. + + This is the assertion the classification in + `tests/test_a_tree_reading_guard_names_its_tree.py` leans on when it puts this guard in + the *names-its-tree-but-is-not-run-here* bucket instead of the bare loop - a claim about + the naming that has to be a measurement rather than a promise. + """ + mod = _load() + root = _repo(tmp_path / "named", "0.3.59", ["v0.3.58"]) + + rc, out = _run(mod, root, capsys) + + assert rc == 1, out + assert out.splitlines()[0] == f"tree: {root}", ( + f"the first line is the reading's subject, and it must be the tree that was read: " + f"{out.splitlines()[:2]}") + + +def test_a_pointable_guard_refuses_a_tree_it_cannot_read(tmp_path, capsys): + """An empty directory and an absent path both answer rc 2 with a reason, never 0. + + The same two shapes the family's empty-tree leg puts to every pointable guard: a tree it + read no file from is not "measured and clean". + """ + mod = _load() + empty = tmp_path / "empty" + empty.mkdir() + absent = tmp_path / "not-there" + + for target in (empty, absent): + rc, out = _run(mod, target, capsys) + assert rc == 2, f"{target}: rc={rc} is 'measured' for a tree no file was read from:\n{out}" + assert "not measurable" in out, f"{target}: the code has to carry a reason:\n{out}" + assert "OK:" not in out and "A RELEASE IS OWED" not in out, ( + f"{target}: it printed a verdict as well as refusing:\n{out}") + + +def test_a_declared_version_with_no_tag_owes_a_release(tmp_path, capsys): + """The whole point: 0.3.59 declared, v0.3.58 the newest tag, commits in between.""" + mod = _load() + root = _repo(tmp_path / "owed", "0.3.59", ["v0.3.58"], commits_after_tag=2) + + rc, out = _run(mod, root, capsys) + + assert rc == 1, out + assert "A RELEASE IS OWED" in out, out + assert "0.3.59" in out and "v0.3.58" in out, out + assert "2 commit(s)" in out, ( + f"the count between the tag and HEAD is the fact that makes the gap real: {out}") + + +def test_a_declared_version_its_tag_carries_owes_nothing(tmp_path, capsys): + """The other direction, without which a guard that always answers "owed" would pass.""" + mod = _load() + root = _repo(tmp_path / "settled", "0.3.58", ["v0.3.57", "v0.3.58"]) + + rc, out = _run(mod, root, capsys) + + assert rc == 0, out + assert "nothing is owed" in out, out + + +def test_versions_compare_as_numbers_not_as_strings(tmp_path, capsys): + """`0.3.10` is newer than `0.3.9`; string order says the opposite. + + A guard sorting tag names as strings picks `v0.3.9` as the newest, then reports a + release owed for a version that is already tagged -- a false red on the exact release + it was meant to confirm. + """ + mod = _load() + root = _repo(tmp_path / "numeric", "0.3.10", ["v0.3.9", "v0.3.10"]) + + rc, out = _run(mod, root, capsys) + + assert rc == 0, out + assert "v0.3.10" in out, out + + +def test_a_tag_that_is_not_version_shaped_is_reported_and_never_chosen(tmp_path, capsys): + """A tag named `latest` must not become "the newest release".""" + mod = _load() + root = _repo(tmp_path / "skipped", "0.3.59", ["v0.3.58", "latest"]) + + rc, out = _run(mod, root, capsys) + + assert rc == 1, out + assert "v0.3.58" in out, out + assert "not version-shaped" in out, ( + f"a skipped tag is a fact about the reading and has to be named: {out}") + + +def test_no_version_declaration_is_unmeasurable_never_a_pass(tmp_path, capsys): + mod = _load() + root = _repo(tmp_path / "no-declaration", None, ["v0.3.58"]) + + rc, out = _run(mod, root, capsys) + + assert rc == 2, out + assert "not measurable" in out, out + + +def test_an_unreadable_repository_is_unmeasurable_never_a_pass(tmp_path, capsys): + """A directory that is not a work tree cannot answer the question at all.""" + mod = _load() + root = tmp_path / "not-a-repo" + root.mkdir() + (root / "emrg").mkdir() + (root / "emrg" / "__init__.py").write_text('__version__ = "0.3.59"\n', encoding="utf-8") + + rc, out = _run(mod, root, capsys) + + assert rc == 2, out + assert "not measurable" in out, out + + +def test_no_tags_at_all_is_a_measurement_and_says_a_release_is_owed(tmp_path, capsys): + """An empty tag list was read, and it answered: nothing carries the declaration. + + Exit 2 is for a question that could not be put. Here it was put and answered, so + reporting "not measurable" would tell a fresh fork it has nothing to publish. + """ + mod = _load() + root = _repo(tmp_path / "no-tags", "0.3.59", []) + + rc, out = _run(mod, root, capsys) + + assert rc == 1, out + assert "A RELEASE IS OWED" in out, out