From 81d726cca22125e5887641451120db29940df2d7 Mon Sep 17 00:00:00 2001 From: noah Date: Wed, 14 Oct 2026 19:46:44 -0600 Subject: [PATCH] Publish branch badges from completed CI runs --- .gitea/workflows/ci-badge.yml | 19 ++++++ .gitea/workflows/main.yml | 2 + README.md | 4 +- ci/last-attempt-badge.py | 115 ++++++++++++++++++++++++++++++++++ ci/test-last-attempt-badge.py | 34 ++++++++++ 5 files changed, 173 insertions(+), 1 deletion(-) create mode 100644 .gitea/workflows/ci-badge.yml create mode 100644 ci/last-attempt-badge.py create mode 100644 ci/test-last-attempt-badge.py diff --git a/.gitea/workflows/ci-badge.yml b/.gitea/workflows/ci-badge.yml new file mode 100644 index 0000000..1a344a7 --- /dev/null +++ b/.gitea/workflows/ci-badge.yml @@ -0,0 +1,19 @@ +name: completed-ci-badge + +on: + workflow_run: + workflows: [main-release-gate, next-build] + types: [completed] + +jobs: + publish: + runs-on: alkane-ci + permissions: + actions: read + contents: write + steps: + - uses: actions/checkout@v4 + - name: Publish last completed attempt + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: python3 ci/last-attempt-badge.py diff --git a/.gitea/workflows/main.yml b/.gitea/workflows/main.yml index 3e9268b..04f6e14 100644 --- a/.gitea/workflows/main.yml +++ b/.gitea/workflows/main.yml @@ -15,6 +15,8 @@ jobs: run: rustup component add rustfmt clippy - name: Formatting run: cargo fmt --check + - name: Last-attempt badge checks + run: python3 ci/test-last-attempt-badge.py - name: Quality run: cargo clippy --all-targets --locked -- -D warnings - name: Build diff --git a/README.md b/README.md index a4092d4..a0ee294 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Alkane OS -[![CI](https://gitea.bluefla.re/blueflare/alkane-os/actions/workflows/next.yml/badge.svg?branch=next)](https://gitea.bluefla.re/blueflare/alkane-os/actions) +[![CI](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/next.svg)](https://gitea.bluefla.re/blueflare/alkane-os/actions) ![tests](badges/tests.svg) ![coverage](badges/coverage.svg) ![bench](badges/bench.svg) @@ -62,3 +62,5 @@ still pending. It is a release gate, not a unit test. The badges record measured host-side checks for this initial core. They do not imply that any board image or mining target has passed conformance. +The CI badge is served from a private, machine-maintained branch and shows +the last completed attempt for this source branch while newer runs are queued. diff --git a/ci/last-attempt-badge.py b/ci/last-attempt-badge.py new file mode 100644 index 0000000..c77bdb1 --- /dev/null +++ b/ci/last-attempt-badge.py @@ -0,0 +1,115 @@ +#!/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 = {"main.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", "cancelled", "skipped"): + 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() diff --git a/ci/test-last-attempt-badge.py b/ci/test-last-attempt-badge.py new file mode 100644 index 0000000..2c19243 --- /dev/null +++ b/ci/test-last-attempt-badge.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Check that queued CI runs do not displace the last completed result.""" + +import importlib.util +from pathlib import Path +from unittest.mock import patch +import xml.etree.ElementTree as ET + +path = Path(__file__).with_name("last-attempt-badge.py") +spec = importlib.util.spec_from_file_location("last_attempt_badge", path) +module = importlib.util.module_from_spec(spec) +spec.loader.exec_module(module) + + +def runs(_url, _token): + return {"workflow_runs": [ + {"id": 104, "head_branch": "main", "status": "queued", "conclusion": None}, + {"id": 103, "head_branch": "main", "status": "completed", "conclusion": "failure"}, + {"id": 102, "head_branch": "main", "status": "completed", "conclusion": "success"}, + ]} + + +with patch.object(module, "request_json", runs): + assert module.latest_completed("https://example.invalid/api/v1", "owner/repo", + "main.yml", "main", "token") == (103, "failure") + +svg = module.badge("main", "failure", 103) +root = ET.fromstring(svg) +assert root.attrib["aria-label"] == "CI main: last completed attempt fail (run 103)" +assert b">fail" in svg +assert b"#d1242f" in svg +assert b">pass" in module.badge("next", "success", 108) +print("last completed CI badge: queued run ignored, pass/fail SVGs valid")