From 6cf9ed162082db91f3033f51531362d79905cf3c Mon Sep 17 00:00:00 2001 From: noah Date: Wed, 14 Oct 2026 20:10:42 -0600 Subject: [PATCH] Publish measured OS badges to private branch --- .gitea/workflows/main.yml | 7 +++++ README.md | 21 +++++++------- ci/badge_store.py | 54 +++++++++++++++++++++++++++++++++++ ci/last-attempt-badge.py | 44 +++------------------------- ci/publish-metrics.py | 32 +++++++++++++++++++++ ci/test-last-attempt-badge.py | 10 +++++++ 6 files changed, 118 insertions(+), 50 deletions(-) create mode 100644 ci/badge_store.py create mode 100644 ci/publish-metrics.py diff --git a/.gitea/workflows/main.yml b/.gitea/workflows/main.yml index 04f6e14..671402b 100644 --- a/.gitea/workflows/main.yml +++ b/.gitea/workflows/main.yml @@ -7,6 +7,9 @@ on: jobs: verify-and-release: runs-on: alkane-ci + permissions: + contents: write + actions: write steps: - uses: actions/checkout@v4 with: @@ -57,6 +60,10 @@ jobs: coverage/tests.json coverage/bench.json bench-current.txt + - name: Publish measured badges privately + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: python3 ci/publish-metrics.py - name: Pairing and simulator conformance run: python3 ci/check-conformance.py - name: Select release version diff --git a/README.md b/README.md index 8053682..c7880c3 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,14 @@ # Alkane OS [![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) -![bench coverage](badges/bench-coverage.svg) -![lines of code](badges/loc.svg) -![dependencies](badges/dependencies.svg) -![code quality](badges/quality.svg) -![license](badges/license.svg) +![tests](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/tests.svg) +![coverage](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/coverage.svg) +![bench](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/bench.svg) +![bench coverage](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/bench-coverage.svg) +![lines of code](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/loc.svg) +![dependencies](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/dependencies.svg) +![code quality](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/quality.svg) +![license](https://gitea.bluefla.re/blueflare/alkane-os/raw/branch/ci-badges/badges/license.svg) Portable mining, tuning, and management logic for Alkane control boards. The source is MIT licensed. `alkane-sdk` owns the board images and supplies the @@ -67,5 +67,6 @@ 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. +CI and metric badges are served from a private, machine-maintained branch. +The CI badge shows the last completed attempt for this source branch while +newer runs are queued; main CI refreshes measured metrics before conformance. diff --git a/ci/badge_store.py b/ci/badge_store.py new file mode 100644 index 0000000..679c917 --- /dev/null +++ b/ci/badge_store.py @@ -0,0 +1,54 @@ +# SPDX-License-Identifier: MIT +"""Write small badge artifacts to the private Gitea CI badge branch.""" + +import base64 +import json +from urllib.error import HTTPError +from urllib.parse import quote +from urllib.request import Request, urlopen + +BADGE_BRANCH = "ci-badges" + + +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 publish_file(api: str, repo: str, filename: str, data: bytes, + token: str, message: str) -> None: + if not filename or filename.startswith("/") or any( + part in ("", ".", "..") for part in filename.split("/")): + raise ValueError("invalid badge path") + if len(data) > 65_536: + raise ValueError("badge artifact exceeds 64 KiB") + path = f"{api}/repos/{repo}/contents/{quote(filename, safe='/')}" + encoded = base64.b64encode(data).decode("ascii") + for attempt in range(3): + try: + current = request_json(path + "?ref=" + BADGE_BRANCH, token) + if base64.b64decode(current["content"]) == 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": message + " [skip ci]"} + 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") diff --git a/ci/last-attempt-badge.py b/ci/last-attempt-badge.py index fd58560..c7eca28 100644 --- a/ci/last-attempt-badge.py +++ b/ci/last-attempt-badge.py @@ -2,17 +2,15 @@ # 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 + +from badge_store import publish_file, request_json WORKFLOWS = {"main.yml": "main", "next.yml": "next"} -BADGE_BRANCH = "ci-badges" def badge(branch: str, conclusion: str, run_id: int) -> bytes: @@ -30,16 +28,6 @@ def badge(branch: str, conclusion: str, run_id: int) -> bytes: f'font-family="sans-serif" font-size="11">{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="") @@ -64,32 +52,8 @@ def latest_completed(api: str, repo: str, workflow: str, branch: str, 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") + publish_file(api, repo, f"{branch}.svg", data, token, + f"Record completed {branch} CI attempt") def main() -> None: diff --git a/ci/publish-metrics.py b/ci/publish-metrics.py new file mode 100644 index 0000000..46cc9c7 --- /dev/null +++ b/ci/publish-metrics.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Publish measured main-branch metric badges to the private badge branch.""" + +import os +from pathlib import Path + +from badge_store import publish_file + +ROOT = Path(__file__).resolve().parents[1] +NAMES = ("tests", "coverage", "bench", "bench-coverage", "loc", + "dependencies", "quality", "license") + + +def main() -> None: + api = os.environ["GITHUB_API_URL"].rstrip("/") + repo = os.environ["GITHUB_REPOSITORY"] + token = os.environ["GITEA_TOKEN"] + for name in NAMES: + data = (ROOT / "badges" / f"{name}.svg").read_bytes() + if not data.lstrip().startswith(b"fail" in svg assert b"#d1242f" in svg assert b">pass" in module.badge("next", "success", 108) +for invalid in ("", "/main.svg", "../main.svg", "badges//main.svg"): + try: + publish_file("https://example.invalid/api/v1", "owner/repo", invalid, + b"", "token", "test") + except ValueError: + pass + else: + raise AssertionError(f"unsafe badge path accepted: {invalid}") print("last completed CI badge: queued run ignored, pass/fail SVGs valid")