|
| 1 | +# SPDX-FileCopyrightText: Contributors to the Power Grid Model project <[email protected]> |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: MPL-2.0 |
| 4 | + |
| 5 | +# script to set version dynamically |
| 6 | +# read VERSION and PyPI, set PYPI_VERSION |
| 7 | + |
| 8 | + |
| 9 | +import os |
| 10 | +from pathlib import Path |
| 11 | + |
| 12 | +import requests |
| 13 | + |
| 14 | + |
| 15 | +def set_version(pkg_dir: Path): |
| 16 | + with open(pkg_dir / "VERSION") as f: |
| 17 | + version = f.read().strip().strip("\n") |
| 18 | + major, minor = (int(x) for x in version.split(".")) |
| 19 | + latest_major, latest_minor, latest_patch = get_pypi_latest() |
| 20 | + # get version |
| 21 | + version = get_new_version(major, minor, latest_major, latest_minor, latest_patch) |
| 22 | + # mutate version in GitHub Actions |
| 23 | + if ("GITHUB_SHA" in os.environ) and ("GITHUB_REF" in os.environ) and ("GITHUB_RUN_NUMBER" in os.environ): |
| 24 | + sha = os.environ["GITHUB_SHA"] |
| 25 | + ref = os.environ["GITHUB_REF"] |
| 26 | + build_number = os.environ["GITHUB_RUN_NUMBER"] |
| 27 | + # short hash number in numeric |
| 28 | + short_hash = f"{int(f'0x{sha[0:6]}', base=16):08}" |
| 29 | + |
| 30 | + if "main" in ref: |
| 31 | + # main branch |
| 32 | + # major.minor.patch |
| 33 | + # do nothing |
| 34 | + pass |
| 35 | + else: |
| 36 | + # feature branch |
| 37 | + # major.minor.patch a 1 build_number short_hash |
| 38 | + version += f"a1{build_number}{short_hash}" |
| 39 | + with open(pkg_dir / "PYPI_VERSION", "w") as f: |
| 40 | + f.write(version) |
| 41 | + |
| 42 | + |
| 43 | +def get_pypi_latest(): |
| 44 | + response = requests.get("https://pypi.org/pypi/power-grid-model-ds/json") |
| 45 | + if response.status_code == 404: |
| 46 | + return 0, 0, 0 |
| 47 | + data = response.json() |
| 48 | + version = str(data["info"]["version"]) |
| 49 | + return (int(x) for x in version.split(".")) |
| 50 | + |
| 51 | + |
| 52 | +def get_new_version(major, minor, latest_major, latest_minor, latest_patch): |
| 53 | + if (major > latest_major) or ((major == latest_major) and minor > latest_minor): |
| 54 | + # brand-new version with patch zero |
| 55 | + return f"{major}.{minor}.0" |
| 56 | + |
| 57 | + if major == latest_major and minor == latest_minor: |
| 58 | + # current version, increment path |
| 59 | + return f"{major}.{minor}.{latest_patch + 1}" |
| 60 | + |
| 61 | + # does not allow building older version |
| 62 | + raise ValueError( |
| 63 | + "Invalid version number!\n" |
| 64 | + f"latest version: {latest_major}.{latest_minor}.{latest_patch}\n" |
| 65 | + f"to be built version: {major}.{minor}\n" |
| 66 | + ) |
| 67 | + |
| 68 | + |
| 69 | +if __name__ == "__main__": |
| 70 | + set_version(Path(__file__).parent) |
0 commit comments