#!/usr/bin/env python3 """Starts a release: makes the branch release/vX.Y.Z from develop. Features are pull requests to that branch (they merge by themselves when CI is green). When the release is ready, a pull request from it to production makes the release. Environment: GT_URL, GT_OWNER, GT_REPO, GT_TOKEN (may create branches), VERSION (1.4.0, or v1.4.0). Standard library only. """ import json import os import re import sys import urllib.error import urllib.request sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import semver # noqa: E402 URL = os.environ.get("GT_URL", "").rstrip("/") OWNER = os.environ.get("GT_OWNER", "") REPO = os.environ.get("GT_REPO", "") TOKEN = os.environ.get("GT_TOKEN", "") def api(method, path, body=None, allow=()): request = urllib.request.Request( f"{URL}/api/v1/repos/{OWNER}/{REPO}/{path}", data=json.dumps(body).encode() if body is not None else None, method=method, headers={"Authorization": f"token {TOKEN}", "Content-Type": "application/json"}, ) try: with urllib.request.urlopen(request, timeout=30) as response: text = response.read().decode() except urllib.error.HTTPError as e: if e.code in allow: return None sys.exit(f"Gitea API {method} {path} failed: {e.code} {e.read().decode()}") return json.loads(text) if text else None def main(): if not (URL and OWNER and REPO and TOKEN): sys.exit("GT_URL, GT_OWNER, GT_REPO and GT_TOKEN are required.") given = os.environ.get("VERSION", "").strip().lstrip("v") if not semver.VERSION.fullmatch(given): sys.exit(f"'{given}' is not a version: use three numbers, like 1.4.0.") version = tuple(int(part) for part in given.split(".")) tags = [tag["name"] for tag in api("GET", "tags?limit=50") or []] newest = semver.latest(tags) if newest is not None and version <= newest: sys.exit(f"v{given} is not above the latest tag v{semver.text(newest)}.") name = f"release/v{given}" if api("GET", f"branches/{name}", allow=(404,)): sys.exit(f"{name} already exists.") api("POST", "branches", {"new_branch_name": name, "old_branch_name": "develop"}) print(f"{name} made from develop. Make features as pull requests to it; when it is ready, open one to production.") if __name__ == "__main__": main()