|
| 1 | +#!/usr/bin/env python3 |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import argparse |
| 5 | +import json |
| 6 | +import re |
| 7 | +import subprocess |
| 8 | +import sys |
| 9 | +import tomllib |
| 10 | +from dataclasses import asdict, dataclass |
| 11 | +from pathlib import Path |
| 12 | +from typing import Sequence |
| 13 | + |
| 14 | + |
| 15 | +_FULL_OID = re.compile(r"[0-9a-fA-F]{40}") |
| 16 | +_SAFE_VERSION = re.compile(r"[0-9A-Za-z][0-9A-Za-z._+!-]{0,127}") |
| 17 | +_ZERO_OID = "0" * 40 |
| 18 | +_PROJECT_FILE = "pyproject.toml" |
| 19 | + |
| 20 | + |
| 21 | +class ReleaseVersionGateError(ValueError): |
| 22 | + def __init__(self, code: str, message: str) -> None: |
| 23 | + super().__init__(message) |
| 24 | + self.code = code |
| 25 | + |
| 26 | + |
| 27 | +@dataclass(frozen=True) |
| 28 | +class ReleaseVersionDecision: |
| 29 | + previous_version: str |
| 30 | + current_version: str |
| 31 | + should_publish: bool |
| 32 | + |
| 33 | + |
| 34 | +def _run_git(root: Path, *args: str) -> subprocess.CompletedProcess[bytes]: |
| 35 | + # SECURITY: event revisions must stay validated argv values; shell interpolation would turn |
| 36 | + # externally supplied workflow context into executable syntax. |
| 37 | + return subprocess.run( |
| 38 | + ["git", *args], |
| 39 | + cwd=root, |
| 40 | + check=False, |
| 41 | + capture_output=True, |
| 42 | + ) |
| 43 | + |
| 44 | + |
| 45 | +def _validate_repository(root: Path) -> Path: |
| 46 | + resolved = root.resolve() |
| 47 | + if not resolved.is_dir(): |
| 48 | + raise ReleaseVersionGateError("invalid-repository", "Repository root is not a directory.") |
| 49 | + |
| 50 | + completed = _run_git(resolved, "rev-parse", "--show-toplevel") |
| 51 | + if completed.returncode != 0: |
| 52 | + raise ReleaseVersionGateError("invalid-repository", "Repository root is not a Git worktree.") |
| 53 | + try: |
| 54 | + discovered = Path(completed.stdout.decode("utf-8", errors="strict").strip()).resolve() |
| 55 | + except UnicodeDecodeError as exc: |
| 56 | + raise ReleaseVersionGateError("invalid-repository", "Git returned a non-UTF-8 worktree path.") from exc |
| 57 | + if discovered != resolved: |
| 58 | + raise ReleaseVersionGateError("invalid-repository", "Repository argument must be the Git worktree root.") |
| 59 | + return resolved |
| 60 | + |
| 61 | + |
| 62 | +def _validate_commit(root: Path, revision: str, label: str) -> str: |
| 63 | + if revision == _ZERO_OID or _FULL_OID.fullmatch(revision) is None: |
| 64 | + raise ReleaseVersionGateError( |
| 65 | + "invalid-revision", |
| 66 | + f"{label} revision must be a non-zero full Git object id.", |
| 67 | + ) |
| 68 | + normalized = revision.lower() |
| 69 | + completed = _run_git(root, "cat-file", "-e", f"{normalized}^{{commit}}") |
| 70 | + if completed.returncode != 0: |
| 71 | + raise ReleaseVersionGateError("missing-revision", f"{label} revision is not an available commit.") |
| 72 | + return normalized |
| 73 | + |
| 74 | + |
| 75 | +def _read_project_version(root: Path, revision: str, label: str) -> str: |
| 76 | + completed = _run_git(root, "cat-file", "blob", f"{revision}:{_PROJECT_FILE}") |
| 77 | + if completed.returncode != 0: |
| 78 | + raise ReleaseVersionGateError( |
| 79 | + "missing-project-metadata", |
| 80 | + f"{label} revision does not contain {_PROJECT_FILE}.", |
| 81 | + ) |
| 82 | + try: |
| 83 | + document = completed.stdout.decode("utf-8-sig", errors="strict") |
| 84 | + except UnicodeDecodeError as exc: |
| 85 | + raise ReleaseVersionGateError( |
| 86 | + "invalid-project-metadata", |
| 87 | + f"{label} {_PROJECT_FILE} is not valid UTF-8.", |
| 88 | + ) from exc |
| 89 | + try: |
| 90 | + metadata = tomllib.loads(document) |
| 91 | + except tomllib.TOMLDecodeError as exc: |
| 92 | + raise ReleaseVersionGateError( |
| 93 | + "invalid-project-metadata", |
| 94 | + f"{label} {_PROJECT_FILE} is not valid TOML.", |
| 95 | + ) from exc |
| 96 | + |
| 97 | + project = metadata.get("project") |
| 98 | + version = project.get("version") if isinstance(project, dict) else None |
| 99 | + if not isinstance(version, str) or _SAFE_VERSION.fullmatch(version) is None: |
| 100 | + raise ReleaseVersionGateError( |
| 101 | + "invalid-project-version", |
| 102 | + f"{label} [project].version must be a non-empty, single-line package version.", |
| 103 | + ) |
| 104 | + return version |
| 105 | + |
| 106 | + |
| 107 | +def classify_release_version_change(root: Path, base: str, head: str) -> ReleaseVersionDecision: |
| 108 | + repository = _validate_repository(root) |
| 109 | + base_oid = _validate_commit(repository, base, "base") |
| 110 | + head_oid = _validate_commit(repository, head, "head") |
| 111 | + previous_version = _read_project_version(repository, base_oid, "base") |
| 112 | + current_version = _read_project_version(repository, head_oid, "head") |
| 113 | + return ReleaseVersionDecision( |
| 114 | + previous_version=previous_version, |
| 115 | + current_version=current_version, |
| 116 | + should_publish=previous_version != current_version, |
| 117 | + ) |
| 118 | + |
| 119 | + |
| 120 | +def _write_github_output(path: Path, decision: ReleaseVersionDecision) -> None: |
| 121 | + try: |
| 122 | + with path.open("a", encoding="utf-8", newline="\n") as stream: |
| 123 | + stream.write(f"should_publish={'true' if decision.should_publish else 'false'}\n") |
| 124 | + stream.write(f"previous_version={decision.previous_version}\n") |
| 125 | + stream.write(f"current_version={decision.current_version}\n") |
| 126 | + except OSError as exc: |
| 127 | + raise ReleaseVersionGateError("github-output-write-failed", "Could not write GitHub job output.") from exc |
| 128 | + |
| 129 | + |
| 130 | +def build_parser() -> argparse.ArgumentParser: |
| 131 | + parser = argparse.ArgumentParser( |
| 132 | + description="Compare immutable push revisions and authorize Registry publication only for a version change." |
| 133 | + ) |
| 134 | + parser.add_argument("--repo", type=Path, default=Path.cwd(), help="Git worktree root.") |
| 135 | + parser.add_argument("--base", required=True, help="Push event base commit (full object id).") |
| 136 | + parser.add_argument("--head", required=True, help="Push event head commit (full object id).") |
| 137 | + parser.add_argument("--github-output", type=Path, help="Optional GitHub Actions output file.") |
| 138 | + return parser |
| 139 | + |
| 140 | + |
| 141 | +def main(argv: Sequence[str] | None = None) -> int: |
| 142 | + args = build_parser().parse_args(argv) |
| 143 | + try: |
| 144 | + decision = classify_release_version_change(args.repo, args.base, args.head) |
| 145 | + if args.github_output is not None: |
| 146 | + _write_github_output(args.github_output, decision) |
| 147 | + except ReleaseVersionGateError as exc: |
| 148 | + print(json.dumps({"status": "error", "error": exc.code}, sort_keys=True)) |
| 149 | + print(f"[release-version] ERROR: {exc}", file=sys.stderr) |
| 150 | + return 2 |
| 151 | + |
| 152 | + print(json.dumps({"status": "ok", **asdict(decision)}, sort_keys=True)) |
| 153 | + return 0 |
| 154 | + |
| 155 | + |
| 156 | +if __name__ == "__main__": |
| 157 | + raise SystemExit(main()) |
0 commit comments