#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Publish the last completed main/next CI result to a private badge branch.""" import base64 import json import os from pathlib import Path from urllib.error import HTTPError from urllib.parse import quote, urlencode from urllib.request import Request, urlopen WORKFLOWS = {"release.yml": "main", "next.yml": "next"} BADGE_BRANCH = "ci-badges" def badge(branch: str, conclusion: str, run_id: int) -> bytes: passed = conclusion == "success" word = "pass" if passed else "fail" color = "#2ea043" if passed else "#d1242f" title = f"CI {branch}: last completed attempt {word} (run {run_id})" return (f'{title}' '' f'' 'CI' f'{word}\n').encode() def request_json(url: str, token: str, method: str = "GET", payload: dict | None = None) -> dict: body = None if payload is None else json.dumps(payload).encode() request = Request(url, data=body, method=method, headers={"Authorization": f"token {token}", "Content-Type": "application/json"}) with urlopen(request, timeout=20) as response: return json.load(response) def latest_completed(api: str, repo: str, workflow: str, branch: str, token: str) -> tuple[int, str]: path = quote(workflow, safe="") latest = None for page in range(1, 21): query = urlencode({"branch": branch, "limit": 50, "page": page}) url = f"{api}/repos/{repo}/actions/workflows/{path}/runs?{query}" runs = request_json(url, token).get("workflow_runs", []) for run in runs: if run.get("head_branch") != branch or run.get("status") != "completed": continue if run.get("conclusion") not in ("success", "failure"): continue candidate = (int(run["id"]), run["conclusion"]) if latest is None or candidate[0] > latest[0]: latest = candidate if len(runs) < 50: break if latest is None: raise RuntimeError(f"no completed {branch} run found for {workflow}") return latest def publish(api: str, repo: str, branch: str, data: bytes, token: str) -> None: path = f"{api}/repos/{repo}/contents/{branch}.svg" encoded = base64.b64encode(data).decode("ascii") for attempt in range(3): try: current = request_json(path + "?ref=" + BADGE_BRANCH, token) current_data = base64.b64decode(current["content"]) if current_data == data: return sha = current["sha"] method = "PUT" except HTTPError as error: if error.code != 404: raise sha = None method = "POST" payload = {"branch": BADGE_BRANCH, "content": encoded, "message": f"Record completed {branch} CI attempt"} if sha is not None: payload["sha"] = sha try: request_json(path, token, method, payload) return except HTTPError as error: if error.code not in (409, 422) or attempt == 2: raise raise RuntimeError("badge write did not complete") def main() -> None: event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text()) if event.get("action") != "completed": raise RuntimeError("expected a completed workflow_run event") run = event["workflow_run"] workflow = run["path"].split("@", 1)[0].rsplit("/", 1)[-1] expected_branch = WORKFLOWS.get(workflow) if expected_branch is None or run.get("head_branch") != expected_branch: raise RuntimeError("unexpected workflow or branch") repo = os.environ["GITHUB_REPOSITORY"] if event["repository"]["full_name"] != repo: raise RuntimeError("repository mismatch") api = os.environ["GITHUB_API_URL"].rstrip("/") token = os.environ["GITEA_TOKEN"] run_id, conclusion = latest_completed(api, repo, workflow, expected_branch, token) publish(api, repo, expected_branch, badge(expected_branch, conclusion, run_id), token) print(f"{expected_branch} badge records completed run {run_id}: {conclusion}") if __name__ == "__main__": main()