lib/checks/check-pr-meta.py
209 lines · 6797 bytes
1"""Checks PR metadata: title format, draft status, template completeness, and checkboxes."""
2
3import json
4import logging
5import os
6import re
7import subprocess
8import sys
9
10sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11import utils
12
13utils.setup_logging()
14logger = logging.getLogger(__name__)
15
16FINDINGS_PATH = "/tmp/findings-compliance.json"
17
18BAD_TITLES = {"update readme.md", "update awesome-privacy.yml"}
19
20TITLE_MSG = (
21 "The pull request title does not follow the format defined in our guidelines."
22 " Please rename it to `[Add/Remove/Update] [software name] in [software section]`"
23)
24DRAFT_MSG = (
25 "Please avoid opening WIP pull requests."
26 " Your PR should be 100% ready and complete before submitting"
27)
28TEMPLATE_MSG = (
29 "Please fill in pull request template in full."
30 " You can find a copy of this"
31 " [here](https://github.com/Lissy93/awesome-privacy/blob/main/.github/PULL_REQUEST_TEMPLATE.md)"
32)
33CHECKBOX_MSG = (
34 "Ensure you have completed the checklist (put a tick the checkboxes with `[x]`),"
35 " to confirm that you've read the contributing guidelines, checked your submission,"
36 " indicated your affiliation and agree to follow our CoC"
37)
38README_MSG = (
39 "Do not edit the README directly. This file is auto-generated from the"
40 " content in `awesome-privacy.yml`, and so your changes will be overridden!"
41 " Instead, only modify the YAML file, and be sure to follow our Contributing Guidelines."
42)
43BOT_MSG = (
44 "Submissions are only accepted from humans."
45 " This PR appears to have been authored by a bot or AI assistant."
46)
47MISSING_TYPE_MSG = (
48 "Please specify the PR type (under the Type heading of the PR template),"
49 " for example 'Addition', 'Amendment' or 'Removal'"
50)
51
52_VALID_TYPES = re.compile(
53 r"addition|amendment|removal|spelling|grammar|website|lib|ci|api|misc|other",
54 re.IGNORECASE,
55)
56
57_BOT_AUTHOR_RE = re.compile(
58 r"(?:noreply@anthropic\.com|devin-ai-integration|copilot-swe-agent|noreply@cursor\.com)",
59 re.IGNORECASE,
60)
61
62
63def extract_section(body, header):
64 """Extract content between a ### header and the next delimiter."""
65 pattern = rf"###\s*{re.escape(header)}\s*\n(.*?)(?=\n---|\n###|\Z)"
66 match = re.search(pattern, body, re.DOTALL)
67 return match.group(1) if match else None
68
69
70def strip_html_comments(text):
71 """Remove HTML comments from text."""
72 return re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL).strip()
73
74
75def check_title(title):
76 """Return a finding if the PR title matches a known-bad pattern."""
77 if title and title.strip().lower() in BAD_TITLES:
78 return TITLE_MSG
79 return None
80
81
82def check_draft(draft_str):
83 """Return a finding if the PR is in draft state."""
84 if str(draft_str).lower() == "true":
85 return DRAFT_MSG
86 return None
87
88
89def check_template(body):
90 """Return a finding if required template sections are missing or empty."""
91 for header in ("Type", "Changes", "Checklist"):
92 content = extract_section(body, header)
93 if content is None or not strip_html_comments(content):
94 return TEMPLATE_MSG
95 return None
96
97
98def check_checkboxes(body, min_checkboxes=4):
99 """Return a finding if any checklist checkboxes are unchecked or missing."""
100 section = extract_section(body, "Checklist")
101 if section is None:
102 return None
103 checked = re.findall(r"- \[x\]", section, re.IGNORECASE)
104 unchecked = re.findall(r"- \[ \]", section)
105 total = len(checked) + len(unchecked)
106 if total < min_checkboxes:
107 return CHECKBOX_MSG
108 if unchecked:
109 return CHECKBOX_MSG
110 return None
111
112
113def check_type(body):
114 """Return a finding if the Type section doesn't contain a recognised PR type."""
115 content = extract_section(body, "Type")
116 if content is None:
117 return None # missing section is already caught by check_template
118 text = strip_html_comments(content)
119 if text and not _VALID_TYPES.search(text):
120 return MISSING_TYPE_MSG
121 return None
122
123
124def check_bot_coauthors(base_ref):
125 """Return a finding if any commit in the PR has a bot author or co-author."""
126 if not base_ref:
127 return None
128 try:
129 result = subprocess.run(
130 ["git", "log", f"{base_ref}..HEAD", "--format=%aN <%aE>%n%B"],
131 capture_output=True, text=True, timeout=30,
132 )
133 if result.returncode != 0:
134 return None
135 if _BOT_AUTHOR_RE.search(result.stdout):
136 return BOT_MSG
137 except Exception as exc:
138 logger.warning("check_bot_coauthors error: %s", exc)
139 return None
140
141
142def check_readme(readme_failed):
143 """Return a finding if the README check reported a failure."""
144 if readme_failed == "true":
145 return README_MSG
146 return None
147
148
149def write_findings(findings):
150 """Write the findings list to the output JSON file."""
151 with open(FINDINGS_PATH, "w") as f:
152 json.dump(findings, f)
153
154
155def main():
156 findings = []
157 critical = False
158 try:
159 title = os.environ.get("PR_TITLE", "")
160 body = os.environ.get("PR_BODY", "")
161 draft = os.environ.get("PR_DRAFT", "false")
162 readme_failed = os.environ.get("README_FAILED", "false")
163 base_ref = os.environ.get("BASE_REF", "")
164
165 logger.info("Checking PR metadata: title, draft, template, checkboxes, type, bot authors")
166
167 finding = check_bot_coauthors(base_ref)
168 if finding:
169 findings.append(finding)
170
171 finding = check_title(title)
172 if finding:
173 findings.append({"msg": finding, "level": "error"})
174 critical = True
175
176 finding = check_draft(draft)
177 if finding:
178 findings.append(finding)
179
180 if not body or not body.strip():
181 findings.append({"msg": TEMPLATE_MSG, "level": "error"})
182 critical = True
183 else:
184 finding = check_template(body)
185 if finding:
186 findings.append({"msg": finding, "level": "error"})
187 critical = True
188 finding = check_checkboxes(body)
189 if finding:
190 findings.append({"msg": finding, "level": "error"})
191 critical = True
192 finding = check_type(body)
193 if finding:
194 findings.append(finding)
195
196 finding = check_readme(readme_failed)
197 if finding:
198 findings.append({"msg": finding, "level": "error"})
199 except Exception as exc:
200 logger.error("Unhandled error in main: %s", exc, exc_info=True)
201
202 logger.info("PR metadata: %d finding(s)%s, writing to %s",
203 len(findings), " (critical)" if critical else "", FINDINGS_PATH)
204 write_findings(findings)
205 sys.exit(1 if critical else 0)
206
207
208if __name__ == "__main__":
209 main()