From 6cbadb4087136839c787e195d7b16c105e2ea521 Mon Sep 17 00:00:00 2001 From: brencher_bot Date: Thu, 17 Sep 2026 19:27:02 +0200 Subject: [PATCH] feat(steps): GiteaActionsTrigger and GiteaActionsAwait for build dispatch --- backend/steps/actions.py | 153 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 153 insertions(+) create mode 100644 backend/steps/actions.py diff --git a/backend/steps/actions.py b/backend/steps/actions.py new file mode 100644 index 0000000..fc0b7ca --- /dev/null +++ b/backend/steps/actions.py @@ -0,0 +1,153 @@ +import json +import logging +import os +import time +import urllib.error +import urllib.request +from dataclasses import dataclass +from typing import Any, Callable, Dict, Optional + +from enironment import AbstractStep +from steps.git import CheckoutMerged + +logger = logging.getLogger(__name__) + + +@dataclass +class GiteaActionsRun: + run_id: int + status: str + conclusion: Optional[str] + html_url: str + + +class GiteaActionsTrigger(AbstractStep[GiteaActionsRun]): + """Trigger a Gitea Actions workflow via the dispatches API.""" + + def __init__(self, + api_base: str, + owner: str, + repo: str, + workflow_file: str, + ref: str, + token: str, + inputs: Optional[Dict[str, str]] = None, + wd: Optional[CheckoutMerged] = None, + poll_timeout_sec: int = 1800, + poll_interval_sec: int = 10, + **kwargs: Any) -> None: + super().__init__(**kwargs) + self.api_base = api_base.rstrip("/") + self.owner = owner + self.repo = repo + self.workflow_file = workflow_file + self.ref = ref + self.token = token + self.inputs = inputs or {} + self.wd = wd + self.poll_timeout_sec = poll_timeout_sec + self.poll_interval_sec = poll_interval_sec + + def _http(self, method: str, url: str, body: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + data = None + headers = {"Authorization": f"token {self.token}", "Accept": "application/json"} + if body is not None: + data = json.dumps(body).encode() + headers["Content-Type"] = "application/json" + req = urllib.request.Request(url, data=data, headers=headers, method=method) + with urllib.request.urlopen(req, timeout=30) as r: + return json.loads(r.read().decode()) + + def _list_recent_runs(self) -> Optional[GiteaActionsRun]: + url = f"{self.api_base}/repos/{self.owner}/{self.repo}/actions/runs?limit=1" + try: + data = self._http("GET", url) + except urllib.error.HTTPError as e: + logger.error("list runs failed: %s", e) + return None + items = data.get("workflow_runs") or [] + if not items: + return None + r = items[0] + return GiteaActionsRun( + run_id=r["id"], + status=r.get("status", ""), + conclusion=r.get("conclusion"), + html_url=r.get("html_url", ""), + ) + + def progress(self) -> GiteaActionsRun: + latest = self._list_recent_runs() + body: Dict[str, Any] = {"ref": self.ref} + if self.inputs: + body["inputs"] = self.inputs + url = ( + f"{self.api_base}/repos/{self.owner}/{self.repo}" + f"/actions/workflows/{self.workflow_file}/dispatches" + ) + self._http("POST", url, body=body) + deadline = time.time() + self.poll_timeout_sec + while time.time() < deadline: + current = self._list_recent_runs() + if current is None or (latest is not None and current.run_id == latest.run_id): + time.sleep(self.poll_interval_sec) + continue + return current + raise TimeoutError( + f"Gitea Actions did not pick up a new run within {self.poll_timeout_sec}s" + ) + + +class GiteaActionsAwait(AbstractStep[GiteaActionsRun]): + """Wait for a previously-triggered Gitea Actions run to complete.""" + + def __init__(self, + api_base: str, + owner: str, + repo: str, + token: str, + run: Callable[[], GiteaActionsRun], + poll_timeout_sec: int = 1800, + poll_interval_sec: int = 10, + **kwargs: Any) -> None: + super().__init__(**kwargs) + self.api_base = api_base.rstrip("/") + self.owner = owner + self.repo = repo + self.token = token + self._run = run + self.poll_timeout_sec = poll_timeout_sec + self.poll_interval_sec = poll_interval_sec + + def _http(self, method: str, url: str) -> Dict[str, Any]: + headers = {"Authorization": f"token {self.token}", "Accept": "application/json"} + req = urllib.request.Request(url, headers=headers, method=method) + with urllib.request.urlopen(req, timeout=30) as r: + return json.loads(r.read().decode()) + + def progress(self) -> GiteaActionsRun: + run = self._run() + deadline = time.time() + self.poll_timeout_sec + while time.time() < deadline: + data = self._http( + "GET", + f"{self.api_base}/repos/{self.owner}/{self.repo}/actions/runs/{run.run_id}", + ) + status = data.get("status", "") + conclusion = data.get("conclusion") + if status == "completed": + if conclusion != "success": + raise RuntimeError( + f"Gitea Actions run {run.run_id} concluded with {conclusion}: " + f"{run.html_url}" + ) + return GiteaActionsRun( + run_id=run.run_id, + status=status, + conclusion=conclusion, + html_url=run.html_url, + ) + time.sleep(self.poll_interval_sec) + raise TimeoutError( + f"Gitea Actions run {run.run_id} did not complete within {self.poll_timeout_sec}s" + )