# 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, max_bytes: int = 65_536) -> None: if not filename or filename.startswith("/") or any( part in ("", ".", "..") for part in filename.split("/")): raise ValueError("invalid badge path") if len(data) > max_bytes: raise ValueError("artifact exceeds size limit") 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")