Coverage for src/retrospeedlab/maintainer/github.py: 74%
185 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-12-02 22:44 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-12-02 22:44 +0000
1import base64
2import itertools
3import re
4from http import HTTPStatus
5from typing import Any
7import httpx
8from cachetools import LRUCache, TTLCache
9from tenacity import retry, retry_if_exception, stop_after_attempt
11from retrospeedlab.maintainer.settings import redacted
13API_URL = "https://api.github.com"
14TIMEOUT_SECONDS = 60.0
15MAIN = "main"
16BRANCH_PREFIX = "maintainer/"
17INSTRUCTION_LABEL = "maintainer"
18RUNS_READ = 30
19MAIN_RUNS_ATTEMPTS = 2
20PAGE_SIZE = 100
21UNREADABLE = (httpx.codes.FORBIDDEN, httpx.codes.NOT_FOUND)
22NOT_MERGEABLE = (httpx.codes.METHOD_NOT_ALLOWED, httpx.codes.CONFLICT)
23PASSED = frozenset({"success", "skipped"})
24CI_RUNNING = "CI running"
25CI_PASSED = "CI passed"
26CI_FAILED = "CI failed"
27PULL_MERGED = "merged"
28PULL_CLOSED = "closed"
29PULL_SECONDS = 300
30PULLS_KEPT = 256
31FINISHED_KEPT = 4096
32MISSING = (httpx.codes.NOT_FOUND,)
33RAW = "application/vnd.github.raw+json"
34LOG_STAMP = re.compile(r"^\S+Z ")
35STEP_START = "##[group]Run "
36STEP_ERROR = "##[error]"
37FAILURES_HEADING = re.compile(r"^=+ FAILURES =+$")
38LOG_HALF = 3000
39LOG_GAP = "\n[... the middle of the log is left out ...]\n"
40LOG_UNREADABLE = (*UNREADABLE, httpx.codes.GONE)
43def clone_url(repository: str) -> str:
44 return f"https://github.com/{repository}.git"
47def git_auth(token: str) -> dict[str, str]:
48 credentials = base64.b64encode(f"x-access-token:{token}".encode()).decode()
49 return {
50 "GIT_CONFIG_COUNT": "1",
51 "GIT_CONFIG_KEY_0": "http.https://github.com/.extraheader",
52 "GIT_CONFIG_VALUE_0": f"Authorization: Basic {credentials}",
53 }
56def client(token: str) -> httpx.Client:
57 headers = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json"}
58 return httpx.Client(base_url=API_URL, headers=headers, timeout=TIMEOUT_SECONDS)
61def own(pull: dict[str, Any]) -> bool:
62 head = pull["head"]
63 if head["repo"] is None or head["repo"]["full_name"] != pull["base"]["repo"]["full_name"]:
64 return False
65 return head["ref"].startswith(BRANCH_PREFIX)
68def own_pulls(token: str, repository: str) -> list[dict[str, Any]]:
69 with client(token) as github:
70 response = github.get(f"/repos/{repository}/pulls", params={"state": "open", "per_page": PAGE_SIZE})
71 response.raise_for_status()
72 return [pull for pull in response.json() if own(pull)]
75def workflow_runs(token: str, repository: str, sha: str) -> list[dict[str, Any]]:
76 with client(token) as github:
77 response = github.get(f"/repos/{repository}/actions/runs", params={"head_sha": sha, "per_page": PAGE_SIZE})
78 response.raise_for_status()
79 return response.json()["workflow_runs"]
82def ci_state(runs: list[dict[str, Any]]) -> str:
83 if not runs or any(run["conclusion"] is None for run in runs):
84 return CI_RUNNING
85 return CI_PASSED if all(run["conclusion"] in PASSED for run in runs) else CI_FAILED
88PullState = tuple[str, str, str | None]
89open_states: TTLCache[tuple[str, str], PullState] = TTLCache(maxsize=PULLS_KEPT, ttl=PULL_SECONDS)
90finished_states: LRUCache[tuple[str, str], PullState] = LRUCache(maxsize=FINISHED_KEPT)
93# a merged or closed pull request never changes again, so its state is kept for good
94def pull_state(token: str, repository: str, number: str) -> PullState:
95 key = (repository, number)
96 if (found := finished_states.get(key)) is not None:
97 return found
98 if (found := open_states.get(key)) is not None:
99 return found
100 found = read_pull_state(token, repository, number)
101 kept = finished_states if found[1] in (PULL_MERGED, PULL_CLOSED) else open_states
102 kept[key] = found
103 return found
106def read_pull_state(token: str, repository: str, number: str) -> PullState:
107 with client(token) as github:
108 response = github.get(f"/repos/{repository}/pulls/{number}")
109 response.raise_for_status()
110 pull = response.json()
111 if pull["merged"]:
112 return pull["title"], PULL_MERGED, pull["merged_at"]
113 if pull["state"] == "closed":
114 return pull["title"], PULL_CLOSED, None
115 return pull["title"], ci_state(workflow_runs(token, repository, pull["head"]["sha"])), None
118def merge(token: str, repository: str, pull: dict[str, Any]) -> str | None:
119 body = {
120 "sha": pull["head"]["sha"],
121 "merge_method": "squash",
122 "commit_title": pull["title"],
123 "commit_message": pull["body"],
124 }
125 with client(token) as github:
126 response = github.put(f"/repos/{repository}/pulls/{pull['number']}/merge", json=body)
127 if response.status_code in NOT_MERGEABLE:
128 return None
129 response.raise_for_status()
130 return response.json()["sha"]
133def file_at(token: str, repository: str, path: str, ref: str) -> str | None:
134 with client(token) as github:
135 response = github.get(f"/repos/{repository}/contents/{path}", params={"ref": ref}, headers={"Accept": RAW})
136 if response.status_code in MISSING:
137 return None
138 response.raise_for_status()
139 return response.text
142def head_commit(token: str, repository: str) -> str:
143 with client(token) as github:
144 response = github.get(f"/repos/{repository}/commits/{MAIN}")
145 response.raise_for_status()
146 return response.json()["sha"]
149def path_commits(token: str, repository: str, path: str) -> list[str]:
150 with client(token) as github:
151 response = github.get(f"/repos/{repository}/commits", params={"path": path, "per_page": RUNS_READ})
152 response.raise_for_status()
153 return [commit["sha"] for commit in response.json()]
156def changed_paths(changed: dict[str, str]) -> list[str]:
157 return (
158 [changed["filename"], changed["previous_filename"]] if "previous_filename" in changed else [changed["filename"]]
159 )
162def pull_files(token: str, repository: str, number: int) -> list[str]:
163 files: list[str] = []
164 with client(token) as github:
165 for page in itertools.count(1):
166 query = {"per_page": PAGE_SIZE, "page": page}
167 response = github.get(f"/repos/{repository}/pulls/{number}/files", params=query)
168 response.raise_for_status()
169 files += [path for changed in response.json() for path in changed_paths(changed)]
170 if len(response.json()) < PAGE_SIZE:
171 break
172 return files
175def close_pull(token: str, repository: str, number: int) -> None:
176 with client(token) as github:
177 github.patch(f"/repos/{repository}/pulls/{number}", json={"state": "closed"}).raise_for_status()
180def delete_branch(token: str, repository: str, branch: str) -> None:
181 with client(token) as github:
182 github.delete(f"/repos/{repository}/git/refs/heads/{branch}").raise_for_status()
185def instructions(token: str, repository: str, owner: str) -> list[dict[str, str | None]]:
186 query = {"state": "open", "labels": INSTRUCTION_LABEL, "creator": owner}
187 with client(token) as github:
188 response = github.get(f"/repos/{repository}/issues", params=query)
189 response.raise_for_status()
190 issues = [issue for issue in response.json() if "pull_request" not in issue and issue["user"]["login"] == owner]
191 return [
192 {"issue": f"{repository}#{issue['number']}", "title": issue["title"], "body": issue["body"]} for issue in issues
193 ]
196def open_pull_request(token: str, repository: str, branch: str, title: str, body: str) -> str:
197 pull = {"title": title, "head": branch, "base": MAIN, "body": body}
198 with client(token) as github:
199 response = github.post(f"/repos/{repository}/pulls", json=pull)
200 response.raise_for_status()
201 return response.json()["html_url"]
204def failed_step(log: str) -> str:
205 lines = [LOG_STAMP.sub("", line, count=1) for line in log.splitlines()]
206 end = next((index for index, line in enumerate(lines) if line.startswith(STEP_ERROR)), len(lines) - 1)
207 starts = [index for index, line in enumerate(lines[:end]) if line.startswith(STEP_START)]
208 step = lines[starts[-1] if starts else 0 : end + 1]
209 failures = next((index for index, line in enumerate(step) if FAILURES_HEADING.match(line)), 0)
210 shown = "\n".join(step[failures:])
211 return shown if len(shown) <= 2 * LOG_HALF else shown[:LOG_HALF] + LOG_GAP + shown[-LOG_HALF:]
214def failed_jobs(github: httpx.Client, repository: str, run: dict[str, Any]) -> str:
215 response = github.get(f"/repos/{repository}/actions/runs/{run['id']}/jobs", params={"filter": "latest"})
216 response.raise_for_status()
217 shown: list[str] = []
218 for job in (job for job in response.json()["jobs"] if job["conclusion"] == "failure"):
219 log = github.get(f"/repos/{repository}/actions/jobs/{job['id']}/logs", follow_redirects=True)
220 text = (
221 f"HTTP {log.status_code}" if log.status_code in LOG_UNREADABLE else failed_step(log.raise_for_status().text)
222 )
223 shown.append(f"{run['name']} / {job['name']}:\n```\n{redacted(text)}\n```")
224 return "\n\n".join(shown)
227def failure_logs(token: str, repository: str, runs: list[dict[str, Any]]) -> str:
228 with client(token) as github:
229 return "\n\n".join(failed_jobs(github, repository, run) for run in runs if run["conclusion"] == "failure")
232def latest_failures(runs: list[dict[str, Any]]) -> list[dict[str, Any]]:
233 latest: dict[str, dict[str, Any]] = {}
234 for run in runs:
235 if run["status"] == "completed":
236 latest.setdefault(run["name"], run)
237 return [run for run in latest.values() if run["conclusion"] == "failure"]
240def bad_gateway(error: BaseException) -> bool:
241 return isinstance(error, httpx.HTTPStatusError) and error.response.status_code == HTTPStatus.BAD_GATEWAY
244@retry(retry=retry_if_exception(bad_gateway), stop=stop_after_attempt(MAIN_RUNS_ATTEMPTS), reraise=True)
245def main_runs(github: httpx.Client, repository: str) -> httpx.Response:
246 query = {"branch": MAIN, "event": "push", "per_page": RUNS_READ}
247 response = github.get(f"/repos/{repository}/actions/runs", params=query)
248 if response.status_code not in UNREADABLE:
249 response.raise_for_status()
250 return response
253def red_checks(token: str, repository: str) -> list[dict[str, str]]:
254 with client(token) as github:
255 response = main_runs(github, repository)
256 if response.status_code in UNREADABLE:
257 return [{"repository": repository, "unreadable": f"HTTP {response.status_code}"}]
258 return [
259 {
260 "repository": repository,
261 "workflow": run["name"],
262 "commit": run["head_sha"][:7],
263 "url": run["html_url"],
264 "log": failed_jobs(github, repository, run),
265 }
266 for run in latest_failures(response.json()["workflow_runs"])
267 ]