lib/checks/check-pr-meta.py

182 lines · 5754 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
 10logging.basicConfig(
 11    level=logging.INFO,
 12    format="%(levelname)s [%(filename)s] %(message)s",
 13    stream=sys.stderr,
 14)
 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)
 47
 48_BOT_AUTHOR_RE = re.compile(
 49    r"(?:noreply@anthropic\.com|devin-ai-integration|copilot-swe-agent|noreply@cursor\.com)",
 50    re.IGNORECASE,
 51)
 52
 53
 54def extract_section(body, header):
 55    """Extract content between a ### header and the next delimiter."""
 56    pattern = rf"###\s*{re.escape(header)}\s*\n(.*?)(?=\n---|\n###|\Z)"
 57    match = re.search(pattern, body, re.DOTALL)
 58    return match.group(1) if match else None
 59
 60
 61def strip_html_comments(text):
 62    """Remove HTML comments from text."""
 63    return re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL).strip()
 64
 65
 66def check_title(title):
 67    """Return a finding if the PR title matches a known-bad pattern."""
 68    if title and title.strip().lower() in BAD_TITLES:
 69        return TITLE_MSG
 70    return None
 71
 72
 73def check_draft(draft_str):
 74    """Return a finding if the PR is in draft state."""
 75    if str(draft_str).lower() == "true":
 76        return DRAFT_MSG
 77    return None
 78
 79
 80def check_template(body):
 81    """Return a finding if required template sections are missing or empty."""
 82    for header in ("Type", "Changes", "Checklist"):
 83        content = extract_section(body, header)
 84        if content is None or not strip_html_comments(content):
 85            return TEMPLATE_MSG
 86    return None
 87
 88
 89def check_checkboxes(body):
 90    """Return a finding if any checklist checkboxes are unchecked."""
 91    section = extract_section(body, "Checklist")
 92    if section is None:
 93        return None
 94    checked = re.findall(r"- \[x\]", section, re.IGNORECASE)
 95    unchecked = re.findall(r"- \[ \]", section)
 96    if not checked and not unchecked:
 97        return None
 98    if unchecked:
 99        return CHECKBOX_MSG
100    return None
101
102
103def check_bot_coauthors(base_ref):
104    """Return a finding if any commit in the PR has a bot author or co-author."""
105    if not base_ref:
106        return None
107    try:
108        result = subprocess.run(
109            ["git", "log", f"{base_ref}..HEAD", "--format=%aN <%aE>%n%B"],
110            capture_output=True, text=True, timeout=30,
111        )
112        if result.returncode != 0:
113            return None
114        if _BOT_AUTHOR_RE.search(result.stdout):
115            return BOT_MSG
116    except Exception as exc:
117        logging.warning("check_bot_coauthors error: %s", exc)
118    return None
119
120
121def check_readme(readme_failed):
122    """Return a finding if the README check reported a failure."""
123    if readme_failed == "true":
124        return README_MSG
125    return None
126
127
128def write_findings(findings):
129    """Write the findings list to the output JSON file."""
130    with open(FINDINGS_PATH, "w") as f:
131        json.dump(findings, f)
132
133
134def main():
135    findings = []
136    critical = False
137    try:
138        title = os.environ.get("PR_TITLE", "")
139        body = os.environ.get("PR_BODY", "")
140        draft = os.environ.get("PR_DRAFT", "false")
141        readme_failed = os.environ.get("README_FAILED", "false")
142        base_ref = os.environ.get("BASE_REF", "")
143
144        finding = check_bot_coauthors(base_ref)
145        if finding:
146            findings.append(finding)
147
148        finding = check_title(title)
149        if finding:
150            findings.append({"msg": finding, "level": "error"})
151            critical = True
152
153        finding = check_draft(draft)
154        if finding:
155            findings.append(finding)
156
157        if not body or not body.strip():
158            findings.append({"msg": TEMPLATE_MSG, "level": "error"})
159            critical = True
160        else:
161            finding = check_template(body)
162            if finding:
163                findings.append({"msg": finding, "level": "error"})
164                critical = True
165            finding = check_checkboxes(body)
166            if finding:
167                findings.append({"msg": finding, "level": "error"})
168                critical = True
169
170        finding = check_readme(readme_failed)
171        if finding:
172            findings.append({"msg": finding, "level": "error"})
173    except Exception as exc:
174        logging.error("Unhandled error in main: %s", exc, exc_info=True)
175
176    logging.info("Writing %d finding(s) to %s", len(findings), FINDINGS_PATH)
177    write_findings(findings)
178    sys.exit(1 if critical else 0)
179
180
181if __name__ == "__main__":
182    main()