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..9d6c0b5 --- /dev/null +++ b/scripts/check_release_version.py @@ -0,0 +1,165 @@ +#!/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. 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 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 + +import ast +import re +import sys +from pathlib import Path +from typing import List, Optional, Union + +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.\-+]+)?)$") + + +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. + + 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: + 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 _constant_assignment(node: ast.stmt) -> Optional[tuple]: + """(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(source: Union[bytes, str]) -> Optional[str]: + """Return ``__version__`` from a plain version module. + + 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(data) + except (SyntaxError, ValueError, LookupError, UnicodeError): + return None + 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 + assignment = _constant_assignment(node) + if assignment is 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: + """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"^##[ \t]+(?:\[" + escaped + r"\]|" + escaped + r")(?:[ \t\r]|$)", 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 = [] + 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( + "pyproject.toml [project] version is %r, tag is %r" % (py, version) + ) + 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" + % (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..b3b2624 --- /dev/null +++ b/tests/test_release_version_check.py @@ -0,0 +1,270 @@ +"""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" + +# 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) + 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) != [] + + +@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) == [] + + +@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) != [] + + +@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. + 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 + + +@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_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') 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+") +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" + + +@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) + 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", + # 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" + + +# 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( + "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")