BlueGit

ict rusty-teams

Files

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

pr_gate.py

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