#!/usr/bin/env python """ Script to set version depending on a git tag starting with "v", or on the latest commit SHA. Meant to be run in sourcehut builds context: https://builds.sr.ht Modifies ~/.buildev, __init__.py and pyproject.toml """ import re from datetime import datetime from pathlib import Path from subprocess import check_output def git(*a: str) -> str: return check_output(["git"] + list(a), cwd=ROOT).decode().strip() def is_branch(b: str) -> bool: return git("rev-parse", "HEAD") == git("rev-parse", b) def get_sha(length=10) -> str: return git("rev-parse", "HEAD")[:length] def get_dev_ver() -> str: return "0.0.0-dev+" + datetime.now().strftime("%Y%m%d") + "_git" + get_sha() def get_tag() -> str: tags = git("tag", "--points-at", "HEAD").split(" ") for tag in tags: if tag.startswith("v"): return tag[1:].strip() return "" def in_sourcehut_build() -> bool: return BUILD_ENV.exists() def set_buildenv(tag: str, ver: str) -> None: if in_sourcehut_build(): content = BUILD_ENV.read_text() else: content = "" if tag: print("There is a git version tag") if is_branch("master"): container = tag pypi = "1" else: container = "experimental" pypi = "" ver = tag else: print("There is no git tag") if is_branch("master"): container = "master" else: container = "experimental" pypi = "" content += f"CONTAINER_TAG={container}\n" content += f"PYPI={pypi}\n" content += f"VER={ver}\n" if in_sourcehut_build(): BUILD_ENV.write_text(content) else: print("--- ~/.buildenv") print(content) def set_main(ver: str) -> None: for m in ROOT.glob("*/*.py"): existing = m.read_text() new = re.sub( r"^__version__ = .*$", f'__version__ = "{ver}"', existing, flags=re.MULTILINE, ) if existing == new: continue if in_sourcehut_build(): m.write_text(new) else: print(f"--- {m.relative_to(ROOT)}") print(new) def set_pyproject(ver: str) -> None: existing = PYPROJECT.read_text() new = re.sub( r"^version = .*$", f'version = "{ver}"', existing, flags=re.MULTILINE, ) if in_sourcehut_build(): PYPROJECT.write_text(new) else: print(f"--- {PYPROJECT.relative_to(ROOT)}") print(new) def main(): tag = get_tag() ver = get_dev_ver() set_buildenv(tag, ver) set_main(tag or ver) set_pyproject(tag or ver) ROOT = Path(".") BUILD_ENV = Path("~/.buildenv").expanduser() PYPROJECT = ROOT / "pyproject.toml" if __name__ == "__main__": main()