|
| 1 | +"""Validate tag, project version, and PyPI publishability for releases.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json |
| 6 | +import os |
| 7 | +from pathlib import Path |
| 8 | +import sys |
| 9 | +import tomllib |
| 10 | +import urllib.error |
| 11 | +import urllib.request |
| 12 | + |
| 13 | + |
| 14 | +def fail(message: str) -> int: |
| 15 | + print(f"ERROR: {message}", file=sys.stderr) |
| 16 | + return 1 |
| 17 | + |
| 18 | + |
| 19 | +def main() -> int: |
| 20 | + event_name = os.environ.get("GITHUB_EVENT_NAME", "") |
| 21 | + ref = os.environ.get("GITHUB_REF", "") |
| 22 | + |
| 23 | + if not (event_name == "push" and ref.startswith("refs/tags/v")): |
| 24 | + print("Skipping release version check outside tag push context.") |
| 25 | + return 0 |
| 26 | + |
| 27 | + tag_version = ref.removeprefix("refs/tags/v") |
| 28 | + pyproject = Path("pyproject.toml") |
| 29 | + data = tomllib.loads(pyproject.read_text(encoding="utf-8")) |
| 30 | + project = data["project"] |
| 31 | + package_name = project["name"] |
| 32 | + project_version = project["version"] |
| 33 | + |
| 34 | + print(f"Package: {package_name}") |
| 35 | + print(f"Tag version: {tag_version}") |
| 36 | + print(f"pyproject.toml version: {project_version}") |
| 37 | + |
| 38 | + if project_version != tag_version: |
| 39 | + return fail( |
| 40 | + "Tag version does not match pyproject.toml version " |
| 41 | + f"({tag_version} != {project_version})." |
| 42 | + ) |
| 43 | + |
| 44 | + url = f"https://pypi.org/pypi/{package_name}/json" |
| 45 | + try: |
| 46 | + with urllib.request.urlopen(url) as response: |
| 47 | + pypi_data = json.load(response) |
| 48 | + except urllib.error.HTTPError as exc: |
| 49 | + if exc.code == 404: |
| 50 | + print("Package does not exist on PyPI yet; version is publishable.") |
| 51 | + return 0 |
| 52 | + raise |
| 53 | + |
| 54 | + releases = pypi_data.get("releases", {}) |
| 55 | + latest = pypi_data.get("info", {}).get("version", "<unknown>") |
| 56 | + print(f"Latest version on PyPI: {latest}") |
| 57 | + |
| 58 | + if tag_version in releases and releases[tag_version]: |
| 59 | + return fail(f"Version {tag_version} is already published on PyPI.") |
| 60 | + |
| 61 | + print(f"Version {tag_version} is not yet published on PyPI.") |
| 62 | + return 0 |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + raise SystemExit(main()) |
0 commit comments