BlueGit

ict rusty-teams

Files

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

pr_gate.py

pr_gate.py 13.7 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"""
6
7import json
8import os
9import re
10import sys
11import time
12import urllib.error
13import urllib.parse
14import urllib.request
15from dataclasses import dataclass, field
16from typing import Any
17
18TITLE_PATTERN = re.compile(r"^(feat|fix|perf|refactor|docs|test|chore|ci|build)(\([a-z0-9-]+\))?!?: \S")
19UI_PATH_PATTERN = re.compile(r"^crates/app/src/(views|settings|components|widgets)/|^crates/app/src/[^/]+_view\.rs$|/locales/")
20IMAGE_PATTERN = re.compile(r"!\[[^\]]*\]\(|<img\s|<video\s|github\.com/user-attachments/|\.(png|jpe?g|gif|webp|mp4|webm)\b", re.IGNORECASE)
21ISSUE_REFERENCE_PATTERN = re.compile(
22 r"\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?):?\s+(?:https://github\.com/danieldaeschle/rusty-teams/issues/|#)(\d+)", re.IGNORECASE
23)
24NO_VISUAL_CHECKBOX_PATTERN = re.compile(r"^\s*[-*]\s*\[[xX]\]\s*no visible change", re.IGNORECASE | re.MULTILINE)
25FORBIDDEN_PATH_PATTERN = re.compile(r"^(openspec|\.specify|\.kiro)/")
26WINDOWS_CODE_PATTERN = re.compile(r"^\+.*(cfg\((all\()?windows|target_os\s*=\s*\"windows\")", re.MULTILINE)
27WINDOWS_PATH_PATTERN = re.compile(r"(^|/)(win32|windows)(/|_[a-z]+\.rs$)|_win(dows)?\.rs$")
28LOCKFILE_NAMES =("Cargo.lock", "package-lock.json", "pnpm-lock.yaml", "yarn.lock")
29
30MAX_CHANGED_LINES = 400
31MIN_PROBLEM_CHARACTERS = 80
32MIN_REVIEW_LINES = 2
33REQUIRED_SECTIONS = ("Summary", "AI model", "Tests", "Review")
34SECTION_ALIASES = {"tests": ("test plan", "testing", "test")}
35
36LABEL_NEEDS_INFO = "status: needs info"
37LABEL_NEEDS_REVIEW = "status: needs review"
38STATUS_LABEL_PREFIX = "status: "
39EXEMPT_ASSOCIATIONS = ("OWNER", "MEMBER", "COLLABORATOR")
40LABEL_ACCEPTED = "status: accepted"
41LABEL_NO_VISUAL = "gate: no visual"
42LABEL_SKIP = "gate: skip"
43
44COMMENT_MARKER = "<!-- pr-gate -->"
45
46
47@dataclass
48class ChangedFile:
49 path: str
50 additions: int = 0
51 deletions: int = 0
52 patch: str = ""
53
54
55@dataclass
56class PullRequest:
57 title: str
58 body: str
59 labels: list[str] = field(default_factory=list)
60 files: list[ChangedFile] = field(default_factory=list)
61 linked_issue_labels: dict[int, list[str]] = field(default_factory=dict)
62
63
64def strip_comments(text: str) -> str:
65 return re.sub(r"<!--.*?-->", "", text or "", flags=re.DOTALL)
66
67
68def parse_sections(body: str) -> dict[str, str]:
69 sections: dict[str, str] = {}
70 current_heading = None
71 current_lines: list[str] = []
72 for line in strip_comments(body).splitlines():
73 heading = re.match(r"^##\s+(.+?)\s*$", line)
74 if heading:
75 if current_heading is not None:
76 sections[current_heading] = "\n".join(current_lines).strip()
77 current_heading = heading.group(1).strip().lower()
78 current_lines = []
79 elif current_heading is not None:
80 current_lines.append(line)
81 if current_heading is not None:
82 sections[current_heading] = "\n".join(current_lines).strip()
83 return sections
84
85
86def find_section(sections: dict[str, str], name: str) -> str | None:
87 names = (name.lower(), *SECTION_ALIASES.get(name.lower(), ()))
88 for heading, content in sections.items():
89 if any(heading == wanted or heading.startswith(wanted + " ") or heading.startswith(wanted + ":") for wanted in names):
90 return content
91 return None
92
93
94def linked_issue_numbers(body: str) -> list[int]:
95 return sorted({int(number) for number in ISSUE_REFERENCE_PATTERN.findall(strip_comments(body))})
96
97
98def changed_lines(files: list[ChangedFile]) -> int:
99 return sum(changed.additions + changed.deletions for changed in files if changed.path.rsplit("/", 1)[-1] not in LOCKFILE_NAMES)
100
101
102def title_type(title: str) -> str:
103 return title.split("(", 1)[0].split(":", 1)[0].split("!", 1)[0].strip()
104
105
106def non_empty_lines(text: str) -> list[str]:
107 return [line for line in text.splitlines() if line.strip()]
108
109
110def check(pull_request: PullRequest) -> list[str]:
111 """Returns one line per missing item, empty when the PR is ready for review."""
112 missing: list[str] = []
113 sections = parse_sections(pull_request.body)
114 issue_numbers = linked_issue_numbers(pull_request.body)
115 paths = [changed.path for changed in pull_request.files]
116
117 if not TITLE_PATTERN.match(pull_request.title):
118 missing.append("**Title**: use `type(scope): message` from the user's view, e.g. `fix(chat): a sent image no longer blinks`.")
119
120 for name in REQUIRED_SECTIONS:
121 if not find_section(sections, name):
122 missing.append(f"**{name}**: the `## {name}` section is missing or empty.")
123
124 if not issue_numbers:
125 problem = find_section(sections, "Problem") or ""
126 if len(problem) < MIN_PROBLEM_CHARACTERS:
127 missing.append(
128 "**Problem**: no linked issue (`Closes #123`), so a `## Problem` section must describe it: "
129 "what is wrong or missing, when a user hits it (steps or when/then) and what should happen instead."
130 )
131
132 size = changed_lines(pull_request.files)
133 needs_accepted_issue = title_type(pull_request.title) == "feat" or size > MAX_CHANGED_LINES
134 if needs_accepted_issue:
135 accepted = any(LABEL_ACCEPTED in pull_request.linked_issue_labels.get(number, []) for number in issue_numbers)
136 if not accepted:
137 reason = "a feature" if title_type(pull_request.title) == "feat" else f"{size} changed lines (over {MAX_CHANGED_LINES})"
138 missing.append(
139 f"**Issue first**: this PR is {reason}. Link an issue that a maintainer marked `{LABEL_ACCEPTED}`, "
140 "or split the change into smaller PRs."
141 )
142
143 if any(UI_PATH_PATTERN.search(path) for path in paths) and LABEL_NO_VISUAL not in pull_request.labels:
144 screenshot = find_section(sections, "Screenshot") or ""
145 has_image = bool(IMAGE_PATTERN.search(strip_comments(pull_request.body)))
146 if not has_image and not NO_VISUAL_CHECKBOX_PATTERN.search(screenshot):
147 missing.append(
148 "**Screenshot**: the change touches UI code. Add a shot of the changed area taken with `--demo` data, "
149 "or tick `No visible change` and say why."
150 )
151
152 tests = find_section(sections, "Tests") or ""
153 touches_windows = any(WINDOWS_CODE_PATTERN.search(changed.patch) or WINDOWS_PATH_PATTERN.search(changed.path) for changed in pull_request.files)
154 if tests and touches_windows and "windows" not in tests.lower():
155 missing.append("**Tests**: the change touches Windows-only code. Say whether you built and ran it on Windows.")
156
157 review = find_section(sections, "Review") or ""
158 if review and len(non_empty_lines(review)) < MIN_REVIEW_LINES:
159 missing.append("**Review**: list at least two independent reviews of the diff and what happened to each finding (AGENTS.md).")
160
161 forbidden = sorted({path.split("/", 1)[0] for path in paths if FORBIDDEN_PATH_PATTERN.match(path)})
162 if forbidden:
163 missing.append(f"**Scope**: remove planning folders from the PR: {', '.join(f'`{name}/`' for name in forbidden)}.")
164
165 if any(path.startswith("vendor/") for path in paths) and "vendor" not in strip_comments(pull_request.body).lower():
166 missing.append("**Scope**: the PR changes `vendor/`. Say in the summary why the fix belongs in the fork.")
167
168 return missing
169
170
171def render_comment(missing: list[str]) -> str:
172 if not missing:
173 return f"{COMMENT_MARKER}\n**PR gate: ready for review.** Thanks, a maintainer will take a look."
174 items = "\n".join(f"- [ ] {item}" for item in missing)
175 return (
176 f"{COMMENT_MARKER}\n**PR gate: not ready for review yet.** Please add:\n\n{items}\n\n"
177 "Edit the description or push, and this comment updates itself. When everything is there, mark the PR "
178 "ready for review. The rules are in CONTRIBUTING.md under \"When a PR is ready for review\". "
179 f"A PR that stays `{LABEL_NEEDS_INFO}` for 14 days is closed; it can be reopened any time."
180 )
181
182
183class GitHub:
184 def __init__(self, repository: str, token: str):
185 self.base_url = f"https://api.github.com/repos/{repository}"
186 self.token = token
187
188 def request(self, method: str, url: str, payload=None) -> Any:
189 full_url = url if url.startswith("https://") else self.base_url + url
190 data = json.dumps(payload).encode() if payload is not None else None
191 request = urllib.request.Request(full_url, data=data, method=method)
192 request.add_header("Authorization", f"Bearer {self.token}")
193 request.add_header("Accept", "application/vnd.github+json")
194 request.add_header("X-GitHub-Api-Version", "2022-11-28")
195 for attempt in range(3):
196 try:
197 with urllib.request.urlopen(request) as response:
198 content = response.read()
199 return json.loads(content) if content else None
200 except urllib.error.HTTPError as error:
201 if error.code < 500 or attempt == 2:
202 raise
203 time.sleep(2 * (attempt + 1))
204
205 def paged(self, url: str) -> list:
206 results, page = [], 1
207 while True:
208 separator = "&" if "?" in url else "?"
209 batch = self.request("GET", f"{url}{separator}per_page=100&page={page}")
210 results.extend(batch)
211 if len(batch) < 100:
212 return results
213 page += 1
214
215
216def load_pull_request(github: GitHub, number: int) -> tuple[dict, PullRequest]:
217 raw = github.request("GET", f"/pulls/{number}")
218 files = [
219 ChangedFile(item["filename"], item.get("additions", 0), item.get("deletions", 0), item.get("patch", ""))
220 for item in github.paged(f"/pulls/{number}/files")
221 ]
222 body = raw.get("body") or ""
223 issue_labels: dict[int, list[str]] = {}
224 for issue_number in linked_issue_numbers(body):
225 try:
226 issue = github.request("GET", f"/issues/{issue_number}")
227 issue_labels[issue_number] = [label["name"] for label in issue.get("labels", [])]
228 except urllib.error.HTTPError:
229 issue_labels[issue_number] = []
230 labels = [label["name"] for label in raw.get("labels", [])]
231 return raw, PullRequest(raw["title"], body, labels, files, issue_labels)
232
233
234def is_exempt(raw: dict, labels: list[str]) -> bool:
235 return LABEL_SKIP in labels or raw["user"]["type"] == "Bot" or raw.get("author_association") in EXEMPT_ASSOCIATIONS
236
237
238def upsert_comment(github: GitHub, number: int, text: str) -> None:
239 for comment in github.paged(f"/issues/{number}/comments"):
240 if COMMENT_MARKER in (comment.get("body") or "") and comment["user"]["type"] == "Bot":
241 if comment["body"] != text:
242 github.request("PATCH", f"/issues/comments/{comment['id']}", {"body": text})
243 return
244 github.request("POST", f"/issues/{number}/comments", {"body": text})
245
246
247def add_label(github: GitHub, number: int, labels: list[str], name: str) -> None:
248 if name not in labels:
249 github.request("POST", f"/issues/{number}/labels", {"labels": [name]})
250
251
252def remove_label(github: GitHub, number: int, labels: list[str], name: str) -> None:
253 if name not in labels:
254 return
255 try:
256 github.request("DELETE", f"/issues/{number}/labels/{urllib.parse.quote(name)}")
257 except urllib.error.HTTPError as error:
258 if error.code != 404:
259 raise
260
261
262def update_labels(github: GitHub, number: int, labels: list[str], ready: bool) -> None:
263 """Sets only the gate's own labels; the maintainers' status labels stay as they are."""
264 if not ready:
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 main() -> int:
303 github = GitHub(os.environ["GITHUB_REPOSITORY"], os.environ["GITHUB_TOKEN"])
304 number = os.environ.get("PR_NUMBER", "").strip()
305 if number:
306 return 0 if run_gate(github, int(number), enforce=True) else 1
307 failed = []
308 for raw in github.paged("/pulls?state=open"):
309 try:
310 run_gate(github, raw["number"], enforce=False)
311 except urllib.error.HTTPError as error:
312 print(f"::warning::#{raw['number']}: {error}")
313 failed.append(raw["number"])
314 return 1 if failed else 0
315
316
317if __name__ == "__main__":
318 sys.exit(main())