"""Patch pyproject.toml and __init__.py version for CI builds (not committed).""" from __future__ import annotations import os import re import sys from pathlib import Path ROOT = Path(__file__).resolve().parent.parent def _read_base_version() -> str: text = (ROOT / "pyproject.toml").read_text(encoding="utf-8") match = re.search(r'^version\s*=\s*"([^"]+)"', text, re.MULTILINE) if not match: raise SystemExit("ERROR: version not found in pyproject.toml") base = match.group(1) return re.sub(r"\.post\d+$", "", base) def resolve_version() -> str: ref = os.environ.get("GITHUB_REF", "") if ref.startswith("refs/tags/v"): return ref.removeprefix("refs/tags/v") if ref.startswith("refs/tags/"): return ref.removeprefix("refs/tags/") run_number = ( os.environ.get("GITHUB_RUN_NUMBER") or os.environ.get("GITHUB_RUN_ID") or "0" ) base = _read_base_version() return f"{base}.post{run_number}" def patch_version(version: str) -> None: pyproject = ROOT / "pyproject.toml" py_text = pyproject.read_text(encoding="utf-8") py_text, n = re.subn( r'^version\s*=\s*"[^"]*"', f'version = "{version}"', py_text, count=1, flags=re.MULTILINE, ) if n != 1: raise SystemExit("ERROR: failed to patch version in pyproject.toml") pyproject.write_text(py_text, encoding="utf-8") init_py = ROOT / "src" / "jiangchang_desktop_sdk" / "__init__.py" init_text = init_py.read_text(encoding="utf-8") init_text, n = re.subn( r'^__version__\s*=\s*"[^"]*"', f'__version__ = "{version}"', init_text, count=1, flags=re.MULTILINE, ) if n != 1: raise SystemExit("ERROR: failed to patch __version__ in __init__.py") init_py.write_text(init_text, encoding="utf-8") def main() -> None: version = resolve_version() print(f"Resolved package version: {version}") patch_version(version) if os.environ.get("GITHUB_OUTPUT"): with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as fh: fh.write(f"package_version={version}\n") if __name__ == "__main__": try: main() except SystemExit as exc: print(exc, file=sys.stderr) raise