#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Publish the last completed main/next CI result to a private badge branch.""" import os from urllib.parse import quote, urlencode from badge_store import publish_file, request_json WORKFLOWS = {"main.yml": "main", "next.yml": "next"} 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 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: publish_file(api, repo, f"{branch}.svg", data, token, f"Record completed {branch} CI attempt") def main() -> None: if os.environ["GITHUB_EVENT_NAME"] not in ("schedule", "workflow_dispatch"): raise RuntimeError("badge publisher must run on a timer or manual dispatch") if os.environ["GITHUB_REF"] != "refs/heads/main": raise RuntimeError("badge publisher must use the main branch") repo = os.environ["GITHUB_REPOSITORY"] api = os.environ["GITHUB_API_URL"].rstrip("/") token = os.environ["GITEA_TOKEN"] completed = {branch: latest_completed(api, repo, workflow, branch, token) for workflow, branch in WORKFLOWS.items()} for branch, (run_id, conclusion) in completed.items(): publish(api, repo, branch, badge(branch, conclusion, run_id), token) print(f"{branch} badge records completed run {run_id}: {conclusion}") if __name__ == "__main__": main()