BlueGit

ict rusty-teams

Files

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

pr_gate.py

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