Files
docs-review/docs_review/forge.py
T
jaredandClaude Opus 5.5 f39409e62c
tests / unittest (push) Successful in 19s
feat: reusable review workflow
Callers use Civilytics/docs-review/.gitea/workflows/review.yml@v1 with secrets: inherit.
Stage 1 on every pull request; for drafter: claude, a 180-second wait and then the sandboxed
drafter; closed pull requests close their docs PR; schedule and dispatch run the monthly
pass. Tested live against Gitea 28.3 (drafter none, a misspelled drafter, claude, close).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 15:12:57 -05:00

169 lines
6.7 KiB
Python

"""Gitea REST API v1 client: comments, pull requests, issues."""
import json
import urllib.error
import urllib.request
from collections.abc import Mapping
from docs_review.secrets import redact
PAGE = 50
TIMEOUT = 30
class ForgeError(RuntimeError):
"""A Gitea request failed. Carries method, path and status; never the token."""
class Gitea:
def __init__(self, base_url: str, repo: str, token: str, *,
urlopen=urllib.request.urlopen,
redact_env: Mapping[str, str] | None = None):
self._root = base_url.rstrip("/") + "/api/v1"
self._repo = repo
self._token = token
self._urlopen = urlopen
self._identity: tuple[str, str] | None = None
# The bot's own token is always redacted, whatever redact_env holds.
self._redact_env = {**(redact_env or {}), "DOCS_REVIEW_GITEA_TOKEN": token}
def _redact(self, payload: dict) -> dict:
"""Every string field with secret values replaced; this is the one place text
leaves for Gitea."""
return {k: redact(v, self._redact_env) if isinstance(v, str) else v
for k, v in payload.items()}
def _request(self, method: str, path: str, payload: dict | None = None):
data = (None if payload is None
else json.dumps(self._redact(payload)).encode("utf-8"))
req = urllib.request.Request(
self._root + path,
data=data,
method=method,
headers={
"Authorization": f"token {self._token}",
"Content-Type": "application/json",
"Accept": "application/json",
},
)
try:
with self._urlopen(req, timeout=TIMEOUT) as resp:
raw = resp.read()
except urllib.error.HTTPError as err:
raise ForgeError(f"{method} {path} -> {err.code}") from None
except urllib.error.URLError as err:
raise ForgeError(f"{method} {path} -> {err.reason}") from None
if not raw:
return None
try:
return json.loads(raw)
except ValueError:
raise ForgeError(f"{method} {path} -> response was not JSON") from None
def _pages(self, path: str):
"""Yield every item of a paginated list, stopping at a short page."""
sep = "&" if "?" in path else "?"
page = 1
while True:
items = self._request("GET", f"{path}{sep}limit={PAGE}&page={page}")
yield from items
if len(items) < PAGE:
return
page += 1
def identity(self) -> tuple[str, str]:
if self._identity is None:
user = self._request("GET", "/user")
self._identity = (user["login"], user["email"])
return self._identity
def find_comment(self, issue: int, marker: str) -> dict | None:
"""The newest comment by the bot's login containing marker."""
login, _ = self.identity()
found = None
for c in self._pages(f"/repos/{self._repo}/issues/{issue}/comments"):
if c["user"]["login"] == login and marker in c["body"]:
found = c
return found
def upsert_comment(self, issue: int, marker: str, body: str) -> None:
existing = self.find_comment(issue, marker)
if existing:
self._request("PATCH",
f"/repos/{self._repo}/issues/comments/{existing['id']}",
{"body": body})
else:
self._request("POST", f"/repos/{self._repo}/issues/{issue}/comments",
{"body": body})
def _own_prs(self, state: str):
"""PRs opened by the bot from a branch of this repository. A PR by anyone else,
or from a fork, may carry a docs-review branch name and a forged body; it is
never trusted."""
login, _ = self.identity()
for pr in self._pages(f"/repos/{self._repo}/pulls?state={state}"):
head_repo = (pr["head"].get("repo") or {}).get("full_name") or ""
# Gitea owner and repository names are case-insensitive.
if ((pr.get("user") or {}).get("login") == login
and head_repo.lower() == self._repo.lower()):
yield pr
def find_open_pr_prefix(self, head_prefix: str) -> dict | None:
for pr in self._own_prs("open"):
if pr["head"]["ref"].startswith(head_prefix):
return pr
return None
def find_open_pr(self, head: str) -> dict | None:
"""The open PR whose head branch is exactly head."""
pr = self.find_pr(head, "open")
return pr
def find_pr(self, head: str, state: str = "all") -> dict | None:
"""The newest PR (highest number) whose head branch is exactly head."""
found = None
for pr in self._own_prs(state):
if pr["head"]["ref"] == head and (found is None or pr["number"] > found["number"]):
found = pr
return found
def open_pr(self, head: str, base: str, title: str, body: str) -> int:
pr = self._request("POST", f"/repos/{self._repo}/pulls",
{"head": head, "base": base, "title": title, "body": body})
return pr["number"]
@staticmethod
def _fields(**kw) -> dict:
return {k: v for k, v in kw.items() if v is not None}
def edit_pr(self, number: int, *, title: str | None = None,
body: str | None = None) -> None:
self._request("PATCH", f"/repos/{self._repo}/pulls/{number}",
self._fields(title=title, body=body))
def close_pr(self, number: int, comment: str) -> None:
self._request("POST", f"/repos/{self._repo}/issues/{number}/comments",
{"body": comment})
self._request("PATCH", f"/repos/{self._repo}/pulls/{number}",
{"state": "closed"})
def find_open_issue(self, marker: str) -> dict | None:
for issue in self._pages(f"/repos/{self._repo}/issues?state=open&type=issues"):
if marker in (issue.get("body") or ""):
return issue
return None
def open_issue(self, title: str, body: str) -> int:
issue = self._request("POST", f"/repos/{self._repo}/issues",
{"title": title, "body": body})
return issue["number"]
def edit_issue(self, number: int, *, title: str | None = None,
body: str | None = None) -> None:
self._request("PATCH", f"/repos/{self._repo}/issues/{number}",
self._fields(title=title, body=body))
def close_issue(self, number: int) -> None:
self._request("PATCH", f"/repos/{self._repo}/issues/{number}",
{"state": "closed"})