BlueGit

ict rusty-teams

Files

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

pr_gate.py

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