From 876a8be28a75f4df0dd156c55e1c099e22e96310 Mon Sep 17 00:00:00 2001 From: TARS Date: Tue, 20 Oct 2026 05:02:00 +0000 Subject: [PATCH 1/4] ci(publish): refuse a release tag whose version does not match the package The publish workflow now runs a read-only verify-version job before the publish job. It fails the tag run unless vX.Y.Z matches the pyproject.toml [project] version, src/shieldcortex/_version.py __version__ and a "## X.Y.Z" CHANGELOG.md heading. The publish job needs it, so a mismatched tag builds and publishes nothing. The check is a stdlib-only script (scripts/check_release_version.py) with tests, including one that asserts the checked-out package is self-consistent, so a release PR that bumps only some of the version files fails ordinary CI before any tag is pushed. Refs #1 --- .github/workflows/publish.yml | 19 ++++++ CHANGELOG.md | 7 ++ scripts/check_release_version.py | 99 +++++++++++++++++++++++++++++ tests/test_release_version_check.py | 83 ++++++++++++++++++++++++ 4 files changed, 208 insertions(+) create mode 100644 scripts/check_release_version.py create mode 100644 tests/test_release_version_check.py diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 710f663..85fe58b 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -6,7 +6,26 @@ on: - "v*" jobs: + verify-version: + # Refuse the tag before anything is built or published unless the tag, + # pyproject.toml, src/shieldcortex/_version.py and CHANGELOG.md agree. + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Check tag matches package version and CHANGELOG + env: + RELEASE_TAG: ${{ github.ref_name }} + run: python scripts/check_release_version.py "$RELEASE_TAG" + publish: + needs: verify-version runs-on: ubuntu-latest environment: pypi permissions: diff --git a/CHANGELOG.md b/CHANGELOG.md index 33be97e..239e641 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## [Unreleased] +### Release process + +- The PyPI publish workflow now refuses a `v*` tag before building unless the + tag matches the `pyproject.toml` version, `shieldcortex.__version__` and a + `CHANGELOG.md` heading for that version. The same check runs in the test + suite, so a release PR that bumps only some of them fails CI. + ### Documentation - README: the introductory LangChain example now narrows diff --git a/scripts/check_release_version.py b/scripts/check_release_version.py new file mode 100644 index 0000000..cbbc83f --- /dev/null +++ b/scripts/check_release_version.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""Refuse a release tag whose version does not match the package. + +Used by the publish workflow before anything is built. A tag ``vX.Y.Z`` is +accepted only when ``pyproject.toml``'s ``[project] version``, +``src/shieldcortex/_version.py``'s ``__version__`` and a ``## X.Y.Z`` +heading in ``CHANGELOG.md`` all name the same version. + +Standard library only, and compatible with every Python the test matrix runs. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path +from typing import List, Optional + +_TAG_RE = re.compile(r"^v(\d+\.\d+\.\d+(?:[-.+][0-9A-Za-z.\-+]+)?)$") +_VERSION_LINE_RE = re.compile(r'^version\s*=\s*"([^"]+)"\s*$') +_DUNDER_RE = re.compile(r'^__version__\s*=\s*["\']([^"\']+)["\']\s*$', re.M) + + +def tag_version(tag: str) -> Optional[str]: + """Return X.Y.Z for a ``vX.Y.Z`` tag (``refs/tags/`` prefix allowed).""" + if tag.startswith("refs/tags/"): + tag = tag[len("refs/tags/") :] + match = _TAG_RE.match(tag) + return match.group(1) if match else None + + +def pyproject_version(text: str) -> Optional[str]: + """Return the ``version`` key of the ``[project]`` table.""" + in_project = False + for raw in text.splitlines(): + line = raw.strip() + if line.startswith("["): + in_project = line == "[project]" + continue + if in_project: + match = _VERSION_LINE_RE.match(line) + if match: + return match.group(1) + return None + + +def module_version(text: str) -> Optional[str]: + match = _DUNDER_RE.search(text) + return match.group(1) if match else None + + +def changelog_has(text: str, version: str) -> bool: + """True when CHANGELOG.md has a ``## X.Y.Z`` (or ``## [X.Y.Z]``) heading.""" + pattern = re.compile( + r"^##\s+\[?" + re.escape(version) + r"\]?(?:\s|$)", re.M + ) + return bool(pattern.search(text)) + + +def check(tag: str, root: Path) -> List[str]: + """Return a list of problems; empty means the tag matches the package.""" + version = tag_version(tag) + if version is None: + return ["tag %r is not of the form vX.Y.Z" % tag] + problems = [] + py = pyproject_version((root / "pyproject.toml").read_text(encoding="utf-8")) + if py != version: + problems.append( + "pyproject.toml [project] version is %r, tag is %r" % (py, version) + ) + mod = module_version( + (root / "src" / "shieldcortex" / "_version.py").read_text(encoding="utf-8") + ) + if mod != version: + problems.append( + "src/shieldcortex/_version.py __version__ is %r, tag is %r" + % (mod, version) + ) + if not changelog_has((root / "CHANGELOG.md").read_text(encoding="utf-8"), version): + problems.append("CHANGELOG.md has no '## %s' heading" % version) + return problems + + +def main(argv: List[str]) -> int: + if len(argv) != 2: + print("usage: check_release_version.py ", file=sys.stderr) + return 2 + root = Path(__file__).resolve().parent.parent + problems = check(argv[1], root) + for problem in problems: + print("release check: " + problem, file=sys.stderr) + if problems: + return 1 + print("release check: %s matches pyproject, _version and CHANGELOG" % argv[1]) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/tests/test_release_version_check.py b/tests/test_release_version_check.py new file mode 100644 index 0000000..61287ff --- /dev/null +++ b/tests/test_release_version_check.py @@ -0,0 +1,83 @@ +"""Tests for scripts/check_release_version.py (the publish workflow's tag guard).""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parent.parent +_SPEC = importlib.util.spec_from_file_location( + "check_release_version", ROOT / "scripts" / "check_release_version.py" +) +assert _SPEC is not None and _SPEC.loader is not None +crv = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(crv) + + +def _make_repo(tmp_path: Path, pyproject: str, module: str, changelog: str) -> Path: + (tmp_path / "src" / "shieldcortex").mkdir(parents=True) + (tmp_path / "pyproject.toml").write_text( + '[build-system]\nrequires = ["hatchling"]\n\n' + '[project]\nname = "shieldcortex"\nversion = "%s"\n\n' + '[tool.other]\nversion = "9.9.9"\n' % pyproject, + encoding="utf-8", + ) + (tmp_path / "src" / "shieldcortex" / "_version.py").write_text( + '__version__ = "%s"\n' % module, encoding="utf-8" + ) + (tmp_path / "CHANGELOG.md").write_text(changelog, encoding="utf-8") + return tmp_path + + +CHANGELOG = "# Changelog\n\n## [Unreleased]\n\n## 1.2.3 — 2026-10-20\n\n- x\n" + + +def test_matching_tag_passes(tmp_path: Path) -> None: + root = _make_repo(tmp_path, "1.2.3", "1.2.3", CHANGELOG) + assert crv.check("v1.2.3", root) == [] + assert crv.check("refs/tags/v1.2.3", root) == [] + + +def test_pyproject_mismatch_fails(tmp_path: Path) -> None: + root = _make_repo(tmp_path, "1.2.2", "1.2.3", CHANGELOG) + problems = crv.check("v1.2.3", root) + assert len(problems) == 1 and "pyproject.toml" in problems[0] + + +def test_other_table_version_is_ignored(tmp_path: Path) -> None: + # [tool.other] version = "9.9.9" must not be read as the project version. + root = _make_repo(tmp_path, "1.2.3", "1.2.3", CHANGELOG) + assert crv.check("v9.9.9", root) != [] + + +def test_module_mismatch_fails(tmp_path: Path) -> None: + root = _make_repo(tmp_path, "1.2.3", "1.2.0", CHANGELOG) + problems = crv.check("v1.2.3", root) + assert len(problems) == 1 and "_version.py" in problems[0] + + +def test_missing_changelog_entry_fails(tmp_path: Path) -> None: + root = _make_repo(tmp_path, "1.2.3", "1.2.3", "# Changelog\n\n## 1.2.30 — x\n") + problems = crv.check("v1.2.3", root) + assert len(problems) == 1 and "CHANGELOG.md" in problems[0] + + +def test_bracketed_changelog_heading_accepted(tmp_path: Path) -> None: + root = _make_repo(tmp_path, "1.2.3", "1.2.3", "## [1.2.3] - 2026-10-20\n") + assert crv.check("v1.2.3", root) == [] + + +@pytest.mark.parametrize("tag", ["1.2.3", "v1.2", "release/python-1.2.3", "vx.y.z", ""]) +def test_malformed_tag_fails(tmp_path: Path, tag: str) -> None: + root = _make_repo(tmp_path, "1.2.3", "1.2.3", CHANGELOG) + assert crv.check(tag, root) != [] + + +def test_current_repository_is_self_consistent() -> None: + # The checked-out package must pass for its own version, so a release PR + # that bumps one version file but not the others fails CI before tagging. + version = crv.pyproject_version((ROOT / "pyproject.toml").read_text(encoding="utf-8")) + assert version is not None + assert crv.check("v" + version, ROOT) == [] From db9e3118bbc8cc382d1ca5dcaabe82e75deedcd1 Mon Sep 17 00:00:00 2001 From: TARS Date: Tue, 20 Oct 2026 05:37:18 +0000 Subject: [PATCH 2/4] fix(release): read versions semantically in the tag guard Review round 1 (independent) found three false acceptances: - a version line inside a TOML multi-line string stood in for [project] version: now tomllib on 3.11+ (workflow runs 3.12); the line reader on older Pythons refuses any triple-quoted string or duplicate key. - a docstring stood in for __version__: now ast, exactly one binding, a top-level string assignment; any other binding is refused. - "##\n0.5.0" passed as a heading: the version must sit on the heading line (horizontal whitespace only); a stray closing bracket no longer matches. Regression tests for each (red on the previous script, green here). --- scripts/check_release_version.py | 97 ++++++++++++++++++++++++++--- tests/test_release_version_check.py | 76 ++++++++++++++++++++++ 2 files changed, 164 insertions(+), 9 deletions(-) diff --git a/scripts/check_release_version.py b/scripts/check_release_version.py index cbbc83f..46f4225 100644 --- a/scripts/check_release_version.py +++ b/scripts/check_release_version.py @@ -7,18 +7,27 @@ heading in ``CHANGELOG.md`` all name the same version. Standard library only, and compatible with every Python the test matrix runs. +The version files are read semantically (TOML via ``tomllib`` where the +interpreter has it, Python via ``ast``) and never imported or executed. Where +a reading would be ambiguous the guard returns no version, so the tag is +refused rather than accepted. """ from __future__ import annotations +import ast import re import sys from pathlib import Path from typing import List, Optional +try: # Python 3.11+. The publish workflow runs 3.12. + import tomllib as _tomllib +except ImportError: # pragma: no cover - exercised on the 3.9/3.10 test jobs + _tomllib = None + _TAG_RE = re.compile(r"^v(\d+\.\d+\.\d+(?:[-.+][0-9A-Za-z.\-+]+)?)$") _VERSION_LINE_RE = re.compile(r'^version\s*=\s*"([^"]+)"\s*$') -_DUNDER_RE = re.compile(r'^__version__\s*=\s*["\']([^"\']+)["\']\s*$', re.M) def tag_version(tag: str) -> Optional[str]: @@ -29,9 +38,29 @@ def tag_version(tag: str) -> Optional[str]: return match.group(1) if match else None -def pyproject_version(text: str) -> Optional[str]: - """Return the ``version`` key of the ``[project]`` table.""" +def _pyproject_version_toml(text: str) -> Optional[str]: + try: + data = _tomllib.loads(text) + except Exception: + return None + project = data.get("project") + if not isinstance(project, dict): + return None + version = project.get("version") + return version if isinstance(version, str) else None + + +def _pyproject_version_lines(text: str) -> Optional[str]: + """Line reader for interpreters without ``tomllib``. + + A multi-line string can hold text that looks like a ``version`` line, so + any triple-quote delimiter makes the reading ambiguous and returns None. + More than one ``version`` line in ``[project]`` also returns None. + """ + if '"""' in text or "'''" in text: + return None in_project = False + found = [] for raw in text.splitlines(): line = raw.strip() if line.startswith("["): @@ -40,19 +69,69 @@ def pyproject_version(text: str) -> Optional[str]: if in_project: match = _VERSION_LINE_RE.match(line) if match: - return match.group(1) - return None + found.append(match.group(1)) + return found[0] if len(found) == 1 else None + + +def pyproject_version(text: str) -> Optional[str]: + """Return the ``version`` key of the ``[project]`` table.""" + if _tomllib is not None: + return _pyproject_version_toml(text) + return _pyproject_version_lines(text) + + +def _binds_version(node: ast.AST) -> bool: + if isinstance(node, ast.Name): + return node.id == "__version__" and isinstance(node.ctx, (ast.Store, ast.Del)) + if isinstance(node, ast.alias): + bound = node.asname or node.name.split(".")[0] + return bound == "__version__" + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + return node.name == "__version__" + if isinstance(node, (ast.Global, ast.Nonlocal)): + return "__version__" in node.names + return False def module_version(text: str) -> Optional[str]: - match = _DUNDER_RE.search(text) - return match.group(1) if match else None + """Return ``__version__`` from a single top-level string assignment. + + The source is parsed, not imported. Text inside strings or comments is + ignored. Any other binding of ``__version__`` (a second assignment, an + augmented assignment, an import alias, a loop target) makes the reading + ambiguous and returns None. + """ + try: + tree = ast.parse(text) + except (SyntaxError, ValueError): + return None + if sum(1 for node in ast.walk(tree) if _binds_version(node)) != 1: + return None + for node in tree.body: + if isinstance(node, ast.Assign): + targets, value = node.targets, node.value + elif isinstance(node, ast.AnnAssign): + targets, value = [node.target], node.value + else: + continue + if len(targets) != 1: + continue + target = targets[0] + if isinstance(target, ast.Name) and target.id == "__version__": + if isinstance(value, ast.Constant) and isinstance(value.value, str): + return value.value + return None + return None def changelog_has(text: str, version: str) -> bool: - """True when CHANGELOG.md has a ``## X.Y.Z`` (or ``## [X.Y.Z]``) heading.""" + """True when CHANGELOG.md has a ``## X.Y.Z`` (or ``## [X.Y.Z]``) heading. + + The version must sit on the heading line itself. + """ + escaped = re.escape(version) pattern = re.compile( - r"^##\s+\[?" + re.escape(version) + r"\]?(?:\s|$)", re.M + r"^##[ \t]+(?:\[" + escaped + r"\]|" + escaped + r")(?:[ \t\r]|$)", re.M ) return bool(pattern.search(text)) diff --git a/tests/test_release_version_check.py b/tests/test_release_version_check.py index 61287ff..a6909ed 100644 --- a/tests/test_release_version_check.py +++ b/tests/test_release_version_check.py @@ -81,3 +81,79 @@ def test_current_repository_is_self_consistent() -> None: version = crv.pyproject_version((ROOT / "pyproject.toml").read_text(encoding="utf-8")) assert version is not None assert crv.check("v" + version, ROOT) == [] + + +# --- Review round 1 regressions: text inside strings must not stand in for +# the real version, and the changelog version must sit on the heading line. + +MULTILINE_PYPROJECT = ( + '[project]\nname = "shieldcortex"\ndescription = """\nversion = "1.2.3"\n"""\n' + 'version = "1.2.4"\n' +) + + +def _write(root: Path, pyproject: str, module: str, changelog: str) -> Path: + (root / "src" / "shieldcortex").mkdir(parents=True) + (root / "pyproject.toml").write_text(pyproject, encoding="utf-8") + (root / "src" / "shieldcortex" / "_version.py").write_text(module, encoding="utf-8") + (root / "CHANGELOG.md").write_text(changelog, encoding="utf-8") + return root + + +def test_version_line_inside_toml_string_is_not_the_version(tmp_path: Path) -> None: + root = _write(tmp_path, MULTILINE_PYPROJECT, '__version__ = "1.2.3"\n', CHANGELOG) + problems = crv.check("v1.2.3", root) + assert len(problems) == 1 and "pyproject.toml" in problems[0] + + +def test_line_reader_refuses_multiline_strings(monkeypatch: pytest.MonkeyPatch) -> None: + # The 3.9/3.10 path (no tomllib) must not accept the string's text either. + monkeypatch.setattr(crv, "_tomllib", None) + assert crv.pyproject_version(MULTILINE_PYPROJECT) is None + assert crv.pyproject_version('[project]\nversion = "1.2.3"\n') == "1.2.3" + + +@pytest.mark.skipif(getattr(crv, "_tomllib", None) is None, reason="tomllib needs Python 3.11+") +def test_toml_reader_returns_the_real_key() -> None: + assert crv.pyproject_version(MULTILINE_PYPROJECT) == "1.2.4" + assert crv.pyproject_version('project.version = "1.2.3"\n') == "1.2.3" + + +def test_docstring_does_not_stand_in_for_dunder_version(tmp_path: Path) -> None: + module = '"""\n__version__ = "1.2.3"\n"""\n__version__ = "1.2.4"\n' + root = _write(tmp_path, '[project]\nversion = "1.2.3"\n', module, CHANGELOG) + problems = crv.check("v1.2.3", root) + assert len(problems) == 1 and "_version.py" in problems[0] + assert crv.module_version(module) == "1.2.4" + + +@pytest.mark.parametrize( + "module", + [ + '__version__ = "1.2.3"\n__version__ = "1.2.4"\n', + '__version__ = "1.2.3"\n__version__ += ".post1"\n', + '__version__ = "1.2.3"\nfrom x import y as __version__\n', + '__version__ = "1.2.3"\nfor __version__ in ["1.2.4"]:\n pass\n', + "__version__ = VERSION\n", + "# __version__ = \"1.2.3\"\n", + ], +) +def test_ambiguous_dunder_version_is_refused(module: str) -> None: + assert crv.module_version(module) is None + + +def test_annotated_dunder_version_is_read() -> None: + assert crv.module_version('__version__: str = "1.2.3"\n') == "1.2.3" + + +@pytest.mark.parametrize( + "changelog", + ["##\n1.2.3\n", "## \n1.2.3 - x\n", "## 1.2.3]\n", "## [1.2.3\n"], +) +def test_changelog_version_must_be_on_the_heading_line(changelog: str) -> None: + assert not crv.changelog_has(changelog, "1.2.3") + + +def test_changelog_heading_with_crlf_is_accepted() -> None: + assert crv.changelog_has("## 1.2.3\r\n", "1.2.3") + assert crv.changelog_has("## [1.2.3]\r\n", "1.2.3") From 85d84abd64bc1222feeb4ff62c80b90910acb6ad Mon Sep 17 00:00:00 2001 From: TARS Date: Tue, 20 Oct 2026 05:49:18 +0000 Subject: [PATCH 3/4] fix(release): refuse what the tag guard cannot read exactly Review round 2 found two more false acceptances, both in reading code that tried to interpret more than it needed to: - the no-tomllib line reader split on Unicode line separators inside a TOML literal string. Removed: without tomllib (Python < 3.11) the guard now reads no version and refuses every tag. The publish workflow runs 3.12. - the AST binding count missed bindings held in string fields (match capture, except-as). Replaced with an allowlist: a version module may hold only a docstring and NAME = assignments, with __version__ assigned once to a string; anything else is refused. Regression tests for both (red on the previous script). --- scripts/check_release_version.py | 120 ++++++++++++---------------- tests/test_release_version_check.py | 65 ++++++++++++++- 2 files changed, 114 insertions(+), 71 deletions(-) diff --git a/scripts/check_release_version.py b/scripts/check_release_version.py index 46f4225..e1eaec7 100644 --- a/scripts/check_release_version.py +++ b/scripts/check_release_version.py @@ -6,11 +6,13 @@ ``src/shieldcortex/_version.py``'s ``__version__`` and a ``## X.Y.Z`` heading in ``CHANGELOG.md`` all name the same version. -Standard library only, and compatible with every Python the test matrix runs. -The version files are read semantically (TOML via ``tomllib`` where the -interpreter has it, Python via ``ast``) and never imported or executed. Where -a reading would be ambiguous the guard returns no version, so the tag is -refused rather than accepted. +Standard library only. The version files are read semantically and never +imported or executed: ``pyproject.toml`` with ``tomllib`` (Python 3.11+; the +publish workflow runs 3.12) and ``_version.py`` with ``ast``. The guard does +not try to read TOML without ``tomllib``: on an older interpreter it reports +no version, so every tag is refused. ``_version.py`` must have the plain shape +the package uses (a docstring and constant assignments, ``__version__`` set +exactly once); anything else is refused rather than interpreted. """ from __future__ import annotations @@ -27,7 +29,6 @@ _tomllib = None _TAG_RE = re.compile(r"^v(\d+\.\d+\.\d+(?:[-.+][0-9A-Za-z.\-+]+)?)$") -_VERSION_LINE_RE = re.compile(r'^version\s*=\s*"([^"]+)"\s*$') def tag_version(tag: str) -> Optional[str]: @@ -38,7 +39,13 @@ def tag_version(tag: str) -> Optional[str]: return match.group(1) if match else None -def _pyproject_version_toml(text: str) -> Optional[str]: +def pyproject_version(text: str) -> Optional[str]: + """Return the ``version`` key of the ``[project]`` table. + + Needs ``tomllib``. Without it there is no reading, and None refuses the tag. + """ + if _tomllib is None: + return None try: data = _tomllib.loads(text) except Exception: @@ -50,78 +57,53 @@ def _pyproject_version_toml(text: str) -> Optional[str]: return version if isinstance(version, str) else None -def _pyproject_version_lines(text: str) -> Optional[str]: - """Line reader for interpreters without ``tomllib``. - - A multi-line string can hold text that looks like a ``version`` line, so - any triple-quote delimiter makes the reading ambiguous and returns None. - More than one ``version`` line in ``[project]`` also returns None. - """ - if '"""' in text or "'''" in text: +def _constant_assignment(node: ast.stmt) -> Optional[tuple]: + """(name, value) for ``NAME = `` or ``NAME: T = ``.""" + if isinstance(node, ast.Assign): + if len(node.targets) != 1: + return None + target, value = node.targets[0], node.value + elif isinstance(node, ast.AnnAssign): + target, value = node.target, node.value + else: return None - in_project = False - found = [] - for raw in text.splitlines(): - line = raw.strip() - if line.startswith("["): - in_project = line == "[project]" - continue - if in_project: - match = _VERSION_LINE_RE.match(line) - if match: - found.append(match.group(1)) - return found[0] if len(found) == 1 else None - - -def pyproject_version(text: str) -> Optional[str]: - """Return the ``version`` key of the ``[project]`` table.""" - if _tomllib is not None: - return _pyproject_version_toml(text) - return _pyproject_version_lines(text) - - -def _binds_version(node: ast.AST) -> bool: - if isinstance(node, ast.Name): - return node.id == "__version__" and isinstance(node.ctx, (ast.Store, ast.Del)) - if isinstance(node, ast.alias): - bound = node.asname or node.name.split(".")[0] - return bound == "__version__" - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): - return node.name == "__version__" - if isinstance(node, (ast.Global, ast.Nonlocal)): - return "__version__" in node.names - return False + if not isinstance(target, ast.Name) or not isinstance(value, ast.Constant): + return None + return target.id, value.value def module_version(text: str) -> Optional[str]: - """Return ``__version__`` from a single top-level string assignment. - - The source is parsed, not imported. Text inside strings or comments is - ignored. Any other binding of ``__version__`` (a second assignment, an - augmented assignment, an import alias, a loop target) makes the reading - ambiguous and returns None. + """Return ``__version__`` from a plain version module. + + The source is parsed, not imported. Every top-level statement must be a + docstring or a ``NAME = `` assignment, and ``__version__`` must + be assigned exactly once, to a string. Any other statement (imports, + conditionals, loops, ``try``, ``match``, definitions, augmented + assignments) makes the module something this guard does not interpret, + and the reading is None. """ try: tree = ast.parse(text) except (SyntaxError, ValueError): return None - if sum(1 for node in ast.walk(tree) if _binds_version(node)) != 1: - return None - for node in tree.body: - if isinstance(node, ast.Assign): - targets, value = node.targets, node.value - elif isinstance(node, ast.AnnAssign): - targets, value = [node.target], node.value - else: - continue - if len(targets) != 1: + found = [] + for index, node in enumerate(tree.body): + if ( + index == 0 + and isinstance(node, ast.Expr) + and isinstance(node.value, ast.Constant) + and isinstance(node.value.value, str) + ): continue - target = targets[0] - if isinstance(target, ast.Name) and target.id == "__version__": - if isinstance(value, ast.Constant) and isinstance(value.value, str): - return value.value + assignment = _constant_assignment(node) + if assignment is None: return None - return None + name, value = assignment + if name == "__version__": + found.append(value) + if len(found) != 1 or not isinstance(found[0], str): + return None + return found[0] def changelog_has(text: str, version: str) -> bool: @@ -142,6 +124,8 @@ def check(tag: str, root: Path) -> List[str]: if version is None: return ["tag %r is not of the form vX.Y.Z" % tag] problems = [] + if _tomllib is None: + problems.append("tomllib is unavailable (Python 3.11+ is required)") py = pyproject_version((root / "pyproject.toml").read_text(encoding="utf-8")) if py != version: problems.append( diff --git a/tests/test_release_version_check.py b/tests/test_release_version_check.py index a6909ed..0bd4e95 100644 --- a/tests/test_release_version_check.py +++ b/tests/test_release_version_check.py @@ -33,13 +33,22 @@ def _make_repo(tmp_path: Path, pyproject: str, module: str, changelog: str) -> P CHANGELOG = "# Changelog\n\n## [Unreleased]\n\n## 1.2.3 — 2026-10-20\n\n- x\n" +# The guard reads pyproject.toml only with tomllib (3.11+; the publish +# workflow runs 3.12). On 3.9/3.10 it refuses every tag, which +# test_without_tomllib_every_tag_is_refused pins; exact-result tests skip there. +needs_tomllib = pytest.mark.skipif( + getattr(crv, "_tomllib", None) is None, reason="the guard needs tomllib (Python 3.11+)" +) + +@needs_tomllib def test_matching_tag_passes(tmp_path: Path) -> None: root = _make_repo(tmp_path, "1.2.3", "1.2.3", CHANGELOG) assert crv.check("v1.2.3", root) == [] assert crv.check("refs/tags/v1.2.3", root) == [] +@needs_tomllib def test_pyproject_mismatch_fails(tmp_path: Path) -> None: root = _make_repo(tmp_path, "1.2.2", "1.2.3", CHANGELOG) problems = crv.check("v1.2.3", root) @@ -52,18 +61,21 @@ def test_other_table_version_is_ignored(tmp_path: Path) -> None: assert crv.check("v9.9.9", root) != [] +@needs_tomllib def test_module_mismatch_fails(tmp_path: Path) -> None: root = _make_repo(tmp_path, "1.2.3", "1.2.0", CHANGELOG) problems = crv.check("v1.2.3", root) assert len(problems) == 1 and "_version.py" in problems[0] +@needs_tomllib def test_missing_changelog_entry_fails(tmp_path: Path) -> None: root = _make_repo(tmp_path, "1.2.3", "1.2.3", "# Changelog\n\n## 1.2.30 — x\n") problems = crv.check("v1.2.3", root) assert len(problems) == 1 and "CHANGELOG.md" in problems[0] +@needs_tomllib def test_bracketed_changelog_heading_accepted(tmp_path: Path) -> None: root = _make_repo(tmp_path, "1.2.3", "1.2.3", "## [1.2.3] - 2026-10-20\n") assert crv.check("v1.2.3", root) == [] @@ -75,6 +87,7 @@ def test_malformed_tag_fails(tmp_path: Path, tag: str) -> None: assert crv.check(tag, root) != [] +@needs_tomllib def test_current_repository_is_self_consistent() -> None: # The checked-out package must pass for its own version, so a release PR # that bumps one version file but not the others fails CI before tagging. @@ -100,17 +113,47 @@ def _write(root: Path, pyproject: str, module: str, changelog: str) -> Path: return root +@needs_tomllib def test_version_line_inside_toml_string_is_not_the_version(tmp_path: Path) -> None: root = _write(tmp_path, MULTILINE_PYPROJECT, '__version__ = "1.2.3"\n', CHANGELOG) problems = crv.check("v1.2.3", root) assert len(problems) == 1 and "pyproject.toml" in problems[0] -def test_line_reader_refuses_multiline_strings(monkeypatch: pytest.MonkeyPatch) -> None: - # The 3.9/3.10 path (no tomllib) must not accept the string's text either. +def test_without_tomllib_every_tag_is_refused( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + # No TOML reading without tomllib: a matching repository is still refused, + # and the decoy line inside a multi-line string is not read either. monkeypatch.setattr(crv, "_tomllib", None) assert crv.pyproject_version(MULTILINE_PYPROJECT) is None - assert crv.pyproject_version('[project]\nversion = "1.2.3"\n') == "1.2.3" + assert crv.pyproject_version('[project]\nversion = "1.2.3"\n') is None + root = _make_repo(tmp_path, "1.2.3", "1.2.3", CHANGELOG) + problems = crv.check("v1.2.3", root) + assert problems and "tomllib" in problems[0] + + +# Round 2: a Unicode line separator inside a TOML literal string is not a +# TOML line break, so its text cannot supply the version either. +SEPARATOR_PYPROJECT = ( + "[project]\ndescription = 'text\u2028version = \"1.2.3\"\u2028text'\nversion = '1.2.4'\n" +) + + +def test_separator_decoy_without_tomllib_is_refused( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(crv, "_tomllib", None) + root = _write(tmp_path, SEPARATOR_PYPROJECT, '__version__ = "1.2.3"\n', CHANGELOG) + assert crv.check("v1.2.3", root) != [] + + +@needs_tomllib +def test_separator_decoy_with_tomllib_reads_the_real_key(tmp_path: Path) -> None: + assert crv.pyproject_version(SEPARATOR_PYPROJECT) == "1.2.4" + root = _write(tmp_path, SEPARATOR_PYPROJECT, '__version__ = "1.2.3"\n', CHANGELOG) + problems = crv.check("v1.2.3", root) + assert len(problems) == 1 and "pyproject.toml" in problems[0] @pytest.mark.skipif(getattr(crv, "_tomllib", None) is None, reason="tomllib needs Python 3.11+") @@ -119,6 +162,7 @@ def test_toml_reader_returns_the_real_key() -> None: assert crv.pyproject_version('project.version = "1.2.3"\n') == "1.2.3" +@needs_tomllib def test_docstring_does_not_stand_in_for_dunder_version(tmp_path: Path) -> None: module = '"""\n__version__ = "1.2.3"\n"""\n__version__ = "1.2.4"\n' root = _write(tmp_path, '[project]\nversion = "1.2.3"\n', module, CHANGELOG) @@ -136,12 +180,27 @@ def test_docstring_does_not_stand_in_for_dunder_version(tmp_path: Path) -> None: '__version__ = "1.2.3"\nfor __version__ in ["1.2.4"]:\n pass\n', "__version__ = VERSION\n", "# __version__ = \"1.2.3\"\n", + # Round 2: bindings that live in string fields of the AST. + '__version__ = "1.2.3"\nmatch "1.2.4":\n case __version__:\n pass\n', + '__version__ = "1.2.3"\ntry:\n raise ValueError("1.2.4")\n' + "except ValueError as __version__:\n pass\n", + # Anything but a docstring and constant assignments is not interpreted. + 'import os\n__version__ = "1.2.3"\n', + '__version__ = "1.2.3"\nif True:\n pass\n', + '__version__ = "1.2.3"\ndef f():\n global __version__\n', + '__version__ = 123\n', + "__version__: str\n", ], ) def test_ambiguous_dunder_version_is_refused(module: str) -> None: assert crv.module_version(module) is None +def test_plain_version_module_shapes_are_read() -> None: + assert crv.module_version('"""Version."""\n__version__ = "1.2.3"\n') == "1.2.3" + assert crv.module_version('__version__ = "1.2.3"\nVERSION_TUPLE = None\n') == "1.2.3" + + def test_annotated_dunder_version_is_read() -> None: assert crv.module_version('__version__: str = "1.2.3"\n') == "1.2.3" From 1b8dce79e79a90b1a9ca237cddf65c26c09aa3ff Mon Sep 17 00:00:00 2001 From: TARS Date: Tue, 20 Oct 2026 06:26:46 +0000 Subject: [PATCH 4/4] fix(release): refuse annotated assignments; parse _version.py as bytes Round-3 review found two false acceptances. A module-level annotation is evaluated when the module runs and can rebind __version__ (B6), so annotated assignments are no longer accepted at all. The module was decoded as UTF-8 text while Python honours a coding declaration (B7), so it is now parsed from its bytes with Python's own source decoding. Tests pin both on module_version() and check(); 10 of them fail on the previous script. --- scripts/check_release_version.py | 39 ++++++++++---------- tests/test_release_version_check.py | 56 +++++++++++++++++++++++++++-- 2 files changed, 75 insertions(+), 20 deletions(-) diff --git a/scripts/check_release_version.py b/scripts/check_release_version.py index e1eaec7..9d6c0b5 100644 --- a/scripts/check_release_version.py +++ b/scripts/check_release_version.py @@ -11,8 +11,11 @@ publish workflow runs 3.12) and ``_version.py`` with ``ast``. The guard does not try to read TOML without ``tomllib``: on an older interpreter it reports no version, so every tag is refused. ``_version.py`` must have the plain shape -the package uses (a docstring and constant assignments, ``__version__`` set -exactly once); anything else is refused rather than interpreted. +the package uses (a docstring and plain ``NAME = `` assignments, +``__version__`` set exactly once); anything else, including annotated +assignments, is refused rather than interpreted. ``_version.py`` is parsed from +its bytes, so Python's own source decoding (including any coding declaration) +decides what the statements are. """ from __future__ import annotations @@ -21,7 +24,7 @@ import re import sys from pathlib import Path -from typing import List, Optional +from typing import List, Optional, Union try: # Python 3.11+. The publish workflow runs 3.12. import tomllib as _tomllib @@ -58,33 +61,35 @@ def pyproject_version(text: str) -> Optional[str]: def _constant_assignment(node: ast.stmt) -> Optional[tuple]: - """(name, value) for ``NAME = `` or ``NAME: T = ``.""" - if isinstance(node, ast.Assign): - if len(node.targets) != 1: - return None - target, value = node.targets[0], node.value - elif isinstance(node, ast.AnnAssign): - target, value = node.target, node.value - else: + """(name, value) for ``NAME = ``. + + Annotated assignments are not accepted: a module-level annotation is + evaluated when the module runs and can rebind ``__version__``. + """ + if not isinstance(node, ast.Assign) or len(node.targets) != 1: return None + target, value = node.targets[0], node.value if not isinstance(target, ast.Name) or not isinstance(value, ast.Constant): return None return target.id, value.value -def module_version(text: str) -> Optional[str]: +def module_version(source: Union[bytes, str]) -> Optional[str]: """Return ``__version__`` from a plain version module. - The source is parsed, not imported. Every top-level statement must be a + The source is parsed, not imported. It is parsed as bytes (a ``str`` is + encoded as UTF-8 first), so a coding declaration is honoured exactly as + when Python runs the file. Every top-level statement must be a docstring or a ``NAME = `` assignment, and ``__version__`` must be assigned exactly once, to a string. Any other statement (imports, conditionals, loops, ``try``, ``match``, definitions, augmented assignments) makes the module something this guard does not interpret, and the reading is None. """ + data = source.encode("utf-8") if isinstance(source, str) else source try: - tree = ast.parse(text) - except (SyntaxError, ValueError): + tree = ast.parse(data) + except (SyntaxError, ValueError, LookupError, UnicodeError): return None found = [] for index, node in enumerate(tree.body): @@ -131,9 +136,7 @@ def check(tag: str, root: Path) -> List[str]: problems.append( "pyproject.toml [project] version is %r, tag is %r" % (py, version) ) - mod = module_version( - (root / "src" / "shieldcortex" / "_version.py").read_text(encoding="utf-8") - ) + mod = module_version((root / "src" / "shieldcortex" / "_version.py").read_bytes()) if mod != version: problems.append( "src/shieldcortex/_version.py __version__ is %r, tag is %r" diff --git a/tests/test_release_version_check.py b/tests/test_release_version_check.py index 0bd4e95..b3b2624 100644 --- a/tests/test_release_version_check.py +++ b/tests/test_release_version_check.py @@ -201,8 +201,60 @@ def test_plain_version_module_shapes_are_read() -> None: assert crv.module_version('__version__ = "1.2.3"\nVERSION_TUPLE = None\n') == "1.2.3" -def test_annotated_dunder_version_is_read() -> None: - assert crv.module_version('__version__: str = "1.2.3"\n') == "1.2.3" +# Round 3: a module-level annotation runs when the module runs, so annotated +# assignments are refused outright, on __version__ and on any other name. +ANNOTATION_MODULES = [ + '__version__: (__version__ := "1.2.4") = "1.2.3"\n', + '__version__ = "1.2.3"\nOTHER: (__version__ := "1.2.4") = None\n', + '__version__ = "1.2.3"\nOTHER: globals().__setitem__("__version__", "1.2.4") = None\n', + '__version__: str = "1.2.3"\n', +] + + +@pytest.mark.parametrize("module", ANNOTATION_MODULES) +def test_annotated_assignments_are_refused(module: str) -> None: + assert crv.module_version(module) is None + + +@needs_tomllib +@pytest.mark.parametrize("module", ANNOTATION_MODULES[:3]) +def test_annotation_rebinding_fails_the_check(tmp_path: Path, module: str) -> None: + root = _write(tmp_path, '[project]\nversion = "1.2.3"\n', module, CHANGELOG) + problems = crv.check("v1.2.3", root) + assert len(problems) == 1 and "_version.py" in problems[0] + + +# Round 3: the module is parsed with Python's own source decoding. Under the +# utf-7 declaration "+AAo-" is a newline, so the last line is a real second +# assignment, not a comment. +UTF7_MODULE = b'# coding: utf-7\n__version__ = "1.2.3"\n# +AAo-__version__ = "1.2.4"\n' + + +def test_coding_declaration_is_honoured() -> None: + namespace: dict = {} + exec(compile(UTF7_MODULE, "v.py", "exec", dont_inherit=True), namespace) + assert namespace["__version__"] == "1.2.4" + assert crv.module_version(UTF7_MODULE) is None + assert crv.module_version(UTF7_MODULE.decode("ascii")) is None + + +@needs_tomllib +def test_coding_declaration_disagreement_fails_the_check(tmp_path: Path) -> None: + root = _write(tmp_path, '[project]\nversion = "1.2.3"\n', "", CHANGELOG) + (root / "src" / "shieldcortex" / "_version.py").write_bytes(UTF7_MODULE) + problems = crv.check("v1.2.3", root) + assert len(problems) == 1 and "_version.py" in problems[0] + + +def test_undecodable_module_is_refused() -> None: + # Python itself refuses these sources, so there is no version to compare. + assert crv.module_version(b'__version__ = "\xff"\n') is None + assert crv.module_version(b'# coding: no-such-codec\n__version__ = "1.2.3"\n') is None + + +def test_plain_coding_declaration_still_reads() -> None: + assert crv.module_version(b'# -*- coding: utf-8 -*-\n__version__ = "1.2.3"\n') == "1.2.3" + assert crv.module_version(b'# coding: latin-1\n__version__ = "1.2.3"\n') == "1.2.3" @pytest.mark.parametrize(