#!/usr/bin/env python3 """Publish dist/ as the rolling Gitea release. Run by .gitea/workflows/rolling-release.yml.""" import json import os from pathlib import Path import subprocess import urllib.error import urllib.parse import urllib.request TAG = "rolling" STAGED = "new-" ASSETS = ["orbit-linux-x86_64", "SHA256SUMS"] ROOT = Path(__file__).resolve().parent.parent DIST = ROOT / "dist" SERVER = os.environ["GITHUB_SERVER_URL"].rstrip("/") REPO = os.environ["GITHUB_REPOSITORY"] COMMIT = os.environ["GITHUB_SHA"] TOKEN = os.environ["GITEA_TOKEN"] RELEASES = f"{SERVER}/api/v1/repos/{REPO}/releases" def call(method, url, data=None, content_type="application/json"): """Make a Gitea API call. Returns None when a GET finds nothing.""" if isinstance(data, dict): data = json.dumps(data).encode() request = urllib.request.Request(url, data=data, method=method) request.add_header("Authorization", f"token {TOKEN}") if data is not None: request.add_header("Content-Type", content_type) try: with urllib.request.urlopen(request, timeout=300) as response: body = response.read() except urllib.error.HTTPError as error: if method == "GET" and error.code == 404: return None detail = error.read().decode(errors="replace") raise SystemExit(f"{method} {url}: HTTP {error.code}: {detail}") return json.loads(body) if body else None def replace_assets(release_id): """Upload under staging names, then swap, so downloads are only missing for a moment.""" assets_url = f"{RELEASES}/{release_id}/assets" for asset in call("GET", assets_url): if asset["name"].startswith(STAGED): call("DELETE", f"{assets_url}/{asset['id']}") for name in ASSETS: query = urllib.parse.urlencode({"name": STAGED + name}) call("POST", f"{assets_url}?{query}", (DIST / name).read_bytes(), "application/octet-stream") ids = {asset["name"]: asset["id"] for asset in call("GET", assets_url)} for name in ASSETS: if name in ids: call("DELETE", f"{assets_url}/{ids[name]}") call("PATCH", f"{assets_url}/{ids[STAGED + name]}", {"name": name}) def main(): missing = [name for name in ASSETS if not (DIST / name).is_file()] if missing: raise SystemExit(f"missing from dist/: {', '.join(missing)}") sums = (DIST / "SHA256SUMS").read_text().strip() download = f"{SERVER}/{REPO}/releases/download/{TAG}" release = { "tag_name": TAG, "target_commitish": COMMIT, "name": f"Rolling build ({COMMIT[:7]})", "prerelease": True, "body": ( f"Automated build of `main` at [`{COMMIT[:7]}`]({SERVER}/{REPO}/commit/{COMMIT}). " "A static Linux x86_64 binary built with Zig's musl toolchain, with OpenSSL included.\n\n" f"```sh\ncurl -fLo orbit {download}/orbit-linux-x86_64\nchmod +x orbit\n```\n\n" f"```\n{sums}\n```\n" ), } existing = call("GET", f"{RELEASES}/tags/{TAG}") if existing is None: existing = call("POST", RELEASES, {**release, "draft": False}) replace_assets(existing["id"]) subprocess.run( ["git", "push", "--force", "origin", f"{COMMIT}:refs/tags/{TAG}"], cwd=ROOT, check=True ) call("PATCH", f"{RELEASES}/{existing['id']}", {**release, "draft": False}) print(f"Published {SERVER}/{REPO}/releases/tag/{TAG}") if __name__ == "__main__": main()