BlueGit

ict rusty-teams

Files

rusty-teams / .github / scripts / pr_gate.py

pr_gate.py

pr_gate.py 15.4 KiB Download Raw
1"""Checks whether a pull request is ready for review (CONTRIBUTING.md, "When a PR is ready for review").
2
3Run by .github/workflows/pr-gate.yml under pull_request_target: it reads the PR as data
4through the API and never checks out or runs code from the PR.
5
6Locally, before a PR leaves draft: `python3 .github/scripts/pr_gate.py --dry-run <number>`.
7It prints what is missing and changes nothing on GitHub.
8"""
9
10import json
11import os
12import re
13import sys
14import time
15import urllib.error
16import urllib.parse
17import urllib.request
18from dataclasses import dataclass, field
19from typing import Any
20
21TITLE_PATTERN = re.compile(r"^(feat|fix|perf|refactor|docs|test|chore|ci|build)(\([a-z0-9-]+\))?!?: \S")
22UI_DIRECTORIES = ("views", "settings", "components", "widgets")
23UI_PATH_PATTERN = re.compile(rf"^crates/app/src/({'|'.join(UI_DIRECTORIES)})/|^crates/app/src/[^/]+_view\.rs$|/locales/")
24IMAGE_PATTERN = re.compile(r"!\[[^\]]*\]\(|<img\s|<video\s|github\.com/user-attachments/|\.(png|jpe?g|gif|webp|mp4|webm)\b", re.IGNORECASE)
25ISSUE_REFERENCE_PATTERN = re.compile(
26 r"\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?):?\s+(?:https://github\.com/danieldaeschle/rusty-teams/issues/|#)(\d+)", re.IGNORECASE
27)
28NO_VISUAL_CHECKBOX_PATTERN = re.compile(r"^\s*[-*]\s*\[[xX]\]\s*no visible change", re.IGNORECASE | re.MULTILINE)
29PLANNING_FOLDERS = ("openspec", ".specify", ".kiro")
30FORBIDDEN_PATH_PATTERN = re.compile(rf"^({'|'.join(re.escape(folder) for folder in PLANNING_FOLDERS)})/")
31WINDOWS_CODE_PATTERN = re.compile(r"^\+.*(cfg\((all\()?windows|target_os\s*=\s*\"windows\")", re.MULTILINE)
32WINDOWS_PATH_PATTERN = re.compile(r"(^|/)(win32|windows)(/|_[a-z]+\.rs$)|_win(dows)?\.rs$")
33
34MIN_PROBLEM_CHARACTERS = 80
35MIN_REVIEW_LINES = 2
36REQUIRED_SECTIONS = ("Summary", "AI model", "Tests", "Review")
37SECTION_ALIASES = {"tests": ("test plan", "testing", "test")}
38
39LABEL_NEEDS_INFO = "status: needs info"
40LABEL_NEEDS_REVIEW = "status: needs review"
41STATUS_LABEL_PREFIX = "status: "
42EXEMPT_ASSOCIATIONS = ("OWNER", "MEMBER", "COLLABORATOR")
43LABEL_ACCEPTED = "status: accepted"
44LABEL_NO_VISUAL = "gate: no visual"
45LABEL_SKIP = "gate: skip"
46
47COMMENT_MARKER = "<!-- pr-gate -->"
48GATE_WORKFLOW = "pr-gate.yml"
49DEFAULT_REPOSITORY = "danieldaeschle/rusty-teams"
50
51
52@dataclass
53class ChangedFile:
54 path: str
55 additions: int = 0
56 deletions: int = 0
57 patch: str = ""
58
59
60@dataclass
61class PullRequest:
62 title: str
63 body: str
64 labels: list[str] = field(default_factory=list)
65 files: list[ChangedFile] = field(default_factory=list)
66 linked_issue_labels: dict[int, list[str]] = field(default_factory=dict)
67
68
69def strip_comments(text: str) -> str:
70 return re.sub(r"<!--.*?-->", "", text or "", flags=re.DOTALL)
71
72
73def parse_sections(body: str) -> dict[str, str]:
74 sections: dict[str, str] = {}
75 current_heading = None
76 current_lines: list[str] = []
77 for line in strip_comments(body).splitlines():
78 heading = re.match(r"^##\s+(.+?)\s*$", line)
79 if heading:
80 if current_heading is not None:
81 sections[current_heading] = "\n".join(current_lines).strip()
82 current_heading = heading.group(1).strip().lower()
83 current_lines = []
84 elif current_heading is not None:
85 current_lines.append(line)
86 if current_heading is not None:
87 sections[current_heading] = "\n".join(current_lines).strip()
88 return sections
89
90
91def find_section(sections: dict[str, str], name: str) -> str | None:
92 names = (name.lower(), *SECTION_ALIASES.get(name.lower(), ()))
93 for heading, content in sections.items():
94 if any(heading == wanted or heading.startswith(wanted + " ") or heading.startswith(wanted + ":") for wanted in names):
95 return content
96 return None
97
98
99def linked_issue_numbers(body: str) -> list[int]:
100 return sorted({int(number) for number in ISSUE_REFERENCE_PATTERN.findall(strip_comments(body))})
101
102
103def title_type(title: str) -> str:
104 return title.split("(", 1)[0].split(":", 1)[0].split("!", 1)[0].strip()
105
106
107def non_empty_lines(text: str) -> list[str]:
108 return [line for line in text.splitlines() if line.strip()]
109
110
111def check(pull_request: PullRequest) -> list[str]:
112 """Returns one line per missing item, empty when the PR is ready for review."""
113 missing: list[str] = []
114 sections = parse_sections(pull_request.body)
115 issue_numbers = linked_issue_numbers(pull_request.body)
116 paths = [changed.path for changed in pull_request.files]
117
118 if not TITLE_PATTERN.match(pull_request.title):
119 missing.append("**Title**: use `type(scope): message` from the user's view, e.g. `fix(chat): a sent image no longer blinks`.")
120
121 for name in REQUIRED_SECTIONS:
122 if not find_section(sections, name):
123 missing.append(f"**{name}**: the `## {name}` section is missing or empty.")
124
125 if not issue_numbers:
126 problem = find_section(sections, "Problem") or ""
127 if len(problem) < MIN_PROBLEM_CHARACTERS:
128 missing.append(
129 "**Problem**: add a `## Problem` section: what is wrong or missing, when a user hits it "
130 "(steps or when/then) and what should happen instead. A fix needs no issue; "
131 "a linked issue (`Closes #123`) replaces this section."
132 )
133
134 if title_type(pull_request.title) == "feat":
135 accepted = any(LABEL_ACCEPTED in pull_request.linked_issue_labels.get(number, []) for number in issue_numbers)
136 if not accepted:
137 missing.append(
138 f"**Issue first**: this PR is a feature. Link an issue that a maintainer marked `{LABEL_ACCEPTED}`."
139 )
140
141 if any(UI_PATH_PATTERN.search(path) for path in paths) and LABEL_NO_VISUAL not in pull_request.labels:
142 screenshot = find_section(sections, "Screenshot") or ""
143 has_image = bool(IMAGE_PATTERN.search(strip_comments(pull_request.body)))
144 if not has_image and not NO_VISUAL_CHECKBOX_PATTERN.search(screenshot):
145 missing.append(
146 "**Screenshot**: the change touches UI code. Add a shot of the changed area taken with `--demo` data, "
147 "or tick `No visible change` and say why."
148 )
149
150 tests = find_section(sections, "Tests") or ""
151 touches_windows = any(WINDOWS_CODE_PATTERN.search(changed.patch) or WINDOWS_PATH_PATTERN.search(changed.path) for changed in pull_request.files)
152 if tests and touches_windows and "windows" not in tests.lower():
153 missing.append("**Tests**: the change touches Windows-only code. Say whether you built and ran it on Windows.")
154
155 review = find_section(sections, "Review") or ""
156 if review and len(non_empty_lines(review)) < MIN_REVIEW_LINES:
157 missing.append("**Review**: list at least two independent reviews of the diff and what happened to each finding (AGENTS.md).")
158
159 forbidden = sorted({path.split("/", 1)[0] for path in paths if FORBIDDEN_PATH_PATTERN.match(path)})
160 if forbidden:
161 missing.append(f"**Scope**: remove planning folders from the PR: {', '.join(f'`{name}/`' for name in forbidden)}.")
162
163 if any(path.startswith("vendor/") for path in paths) and "vendor" not in strip_comments(pull_request.body).lower():
164 missing.append("**Scope**: the PR changes `vendor/`. Say in the summary why the fix belongs in the fork.")
165
166 return missing
167
168
169def render_comment(missing: list[str]) -> str:
170 if not missing:
171 return f"{COMMENT_MARKER}\n**PR gate: ready for review.** Thanks, a maintainer will take a look."
172 items = "\n".join(f"- [ ] {item}" for item in missing)
173 return (
174 f"{COMMENT_MARKER}\n**PR gate: not ready for review yet.** Please add:\n\n{items}\n\n"
175 "Edit the description or push, and this comment updates itself. When everything is there, mark the PR "
176 "ready for review. The rules are in CONTRIBUTING.md under \"When a PR is ready for review\". "
177 f"A PR that stays `{LABEL_NEEDS_INFO}` for 14 days is closed; it can be reopened any time."
178 )
179
180
181class GitHub:
182 def __init__(self, repository: str, token: str):
183 self.base_url = f"https://api.github.com/repos/{repository}"
184 self.token = token
185
186 def request(self, method: str, url: str, payload=None) -> Any:
187 full_url = url if url.startswith("https://") else self.base_url + url
188 data = json.dumps(payload).encode() if payload is not None else None
189 request = urllib.request.Request(full_url, data=data, method=method)
190 if self.token:
191 request.add_header("Authorization", f"Bearer {self.token}")
192 request.add_header("Accept", "application/vnd.github+json")
193 request.add_header("X-GitHub-Api-Version", "2022-11-28")
194 for attempt in range(3):
195 try:
196 with urllib.request.urlopen(request) as response:
197 content = response.read()
198 return json.loads(content) if content else None
199 except urllib.error.HTTPError as error:
200 if error.code < 500 or attempt == 2:
201 raise
202 time.sleep(2 * (attempt + 1))
203
204 def paged(self, url: str) -> list:
205 results, page = [], 1
206 while True:
207 separator = "&" if "?" in url else "?"
208 batch = self.request("GET", f"{url}{separator}per_page=100&page={page}")
209 results.extend(batch)
210 if len(batch) < 100:
211 return results
212 page += 1
213
214
215def load_pull_request(github: GitHub, number: int) -> tuple[dict, PullRequest]:
216 raw = github.request("GET", f"/pulls/{number}")
217 files = [
218 ChangedFile(item["filename"], item.get("additions", 0), item.get("deletions", 0), item.get("patch", ""))
219 for item in github.paged(f"/pulls/{number}/files")
220 ]
221 body = raw.get("body") or ""
222 issue_labels: dict[int, list[str]] = {}
223 for issue_number in linked_issue_numbers(body):
224 try:
225 issue = github.request("GET", f"/issues/{issue_number}")
226 issue_labels[issue_number] = [label["name"] for label in issue.get("labels", [])]
227 except urllib.error.HTTPError:
228 issue_labels[issue_number] = []
229 labels = [label["name"] for label in raw.get("labels", [])]
230 return raw, PullRequest(raw["title"], body, labels, files, issue_labels)
231
232
233def is_exempt(raw: dict, labels: list[str]) -> bool:
234 return LABEL_SKIP in labels or raw["user"]["type"] == "Bot" or raw.get("author_association") in EXEMPT_ASSOCIATIONS
235
236
237def upsert_comment(github: GitHub, number: int, text: str) -> None:
238 for comment in github.paged(f"/issues/{number}/comments"):
239 if COMMENT_MARKER in (comment.get("body") or "") and comment["user"]["type"] == "Bot":
240 if comment["body"] != text:
241 github.request("PATCH", f"/issues/comments/{comment['id']}", {"body": text})
242 return
243 github.request("POST", f"/issues/{number}/comments", {"body": text})
244
245
246def add_label(github: GitHub, number: int, labels: list[str], name: str) -> None:
247 if name not in labels:
248 github.request("POST", f"/issues/{number}/labels", {"labels": [name]})
249
250
251def remove_label(github: GitHub, number: int, labels: list[str], name: str) -> None:
252 if name not in labels:
253 return
254 try:
255 github.request("DELETE", f"/issues/{number}/labels/{urllib.parse.quote(name)}")
256 except urllib.error.HTTPError as error:
257 if error.code != 404:
258 raise
259
260
261def update_labels(github: GitHub, number: int, labels: list[str], ready: bool) -> None:
262 """Sets only the gate's own labels (needs info, needs review); the maintainers' status labels stay as they are."""
263 if not ready:
264 remove_label(github, number, labels, LABEL_NEEDS_REVIEW)
265 add_label(github, number, labels, LABEL_NEEDS_INFO)
266 return
267 remove_label(github, number, labels, LABEL_NEEDS_INFO)
268 if not any(label.startswith(STATUS_LABEL_PREFIX) and label != LABEL_NEEDS_INFO for label in labels):
269 add_label(github, number, labels, LABEL_NEEDS_REVIEW)
270
271
272def convert_to_draft(github: GitHub, node_id: str) -> None:
273 query = "mutation($id: ID!) { convertPullRequestToDraft(input: {pullRequestId: $id}) { clientMutationId } }"
274 try:
275 github.request("POST", "https://api.github.com/graphql", {"query": query, "variables": {"id": node_id}})
276 except urllib.error.HTTPError as error:
277 print(f"::warning::could not convert to draft: {error}")
278
279
280def run_gate(github: GitHub, number: int, enforce: bool) -> bool:
281 raw, pull_request = load_pull_request(github, number)
282 if raw["state"] != "open":
283 return True
284 if is_exempt(raw, pull_request.labels):
285 print(f"#{number}: exempt")
286 return True
287 is_draft = bool(raw.get("draft"))
288 if is_draft and enforce and LABEL_NEEDS_INFO not in pull_request.labels:
289 print(f"#{number}: draft, gate runs when it is marked ready for review")
290 return True
291 missing = check(pull_request)
292 upsert_comment(github, number, render_comment(missing))
293 update_labels(github, number, pull_request.labels, ready=not missing)
294 if missing and enforce and not is_draft:
295 convert_to_draft(github, raw["node_id"])
296 print(f"#{number}: {'ready' if not missing else 'missing ' + str(len(missing))}")
297 for item in missing:
298 print(f" - {item}")
299 return is_draft or not missing
300
301
302def rerun_failed_gate(github: GitHub, raw: dict) -> None:
303 """A sweep or an issue label passes the PR, but the red check sits on the head commit's own run: run that again."""
304 sha = urllib.parse.quote(raw["head"]["sha"])
305 runs = github.request("GET", f"/actions/workflows/{GATE_WORKFLOW}/runs?head_sha={sha}&event=pull_request_target&per_page=20")
306 latest = max((runs or {}).get("workflow_runs", []), key=lambda run: run["created_at"], default=None)
307 if latest and latest.get("conclusion") == "failure":
308 github.request("POST", f"/actions/runs/{latest['id']}/rerun")
309 print(f"#{raw['number']}: re-ran the failed gate run {latest['id']}")
310
311
312def dry_run(github: GitHub, number: int) -> int:
313 _, pull_request = load_pull_request(github, number)
314 missing = check(pull_request)
315 if not missing:
316 print(f"#{number}: ready for review")
317 return 0
318 print(f"#{number}: not ready, missing:")
319 for item in missing:
320 print(f"- {item.replace('**', '')}")
321 return 1
322
323
324def main() -> int:
325 repository = os.environ.get("GITHUB_REPOSITORY") or DEFAULT_REPOSITORY
326 github = GitHub(repository, os.environ.get("GITHUB_TOKEN", ""))
327 if len(sys.argv) > 1:
328 number_argument = re.search(r"(\d+)$", sys.argv[2]) if len(sys.argv) == 3 and sys.argv[1] == "--dry-run" else None
329 if not number_argument:
330 print("usage: python3 .github/scripts/pr_gate.py --dry-run <PR number or URL>", file=sys.stderr)
331 return 2
332 return dry_run(github, int(number_argument.group(1)))
333 if os.environ.get("GITHUB_ACTIONS") != "true":
334 print("Writes to GitHub only run in CI. Locally use --dry-run <PR number>.", file=sys.stderr)
335 return 2
336 number = os.environ.get("PR_NUMBER", "").strip()
337 if number:
338 return 0 if run_gate(github, int(number), enforce=True) else 1
339 issue = os.environ.get("ISSUE_NUMBER", "").strip()
340 failed = []
341 for raw in github.paged("/pulls?state=open"):
342 if issue and int(issue) not in linked_issue_numbers(raw.get("body") or ""):
343 continue
344 try:
345 if run_gate(github, raw["number"], enforce=False):
346 rerun_failed_gate(github, raw)
347 except urllib.error.HTTPError as error:
348 print(f"::warning::#{raw['number']}: {error}")
349 failed.append(raw["number"])
350 return 1 if failed else 0
351
352
353if __name__ == "__main__":
354 sys.exit(main())