lib/checks/format-comment.py

243 lines · 7829 bytes

  1"""Aggregates findings from all check jobs into a formatted PR comment."""
  2
  3import json
  4import logging
  5import os
  6import sys
  7from datetime import datetime, timezone
  8
  9logging.basicConfig(
 10    level=logging.INFO,
 11    format="%(levelname)s [%(filename)s] %(message)s",
 12    stream=sys.stderr,
 13)
 14
 15ARTIFACTS_DIR = "/tmp/artifacts"
 16OUTPUT_DIR = "/tmp/pr-meta"
 17
 18REPO_URL = "https://github.com/Lissy93/awesome-privacy"
 19CONTRIBUTING = f"{REPO_URL}/blob/main/.github/CONTRIBUTING.md"
 20DIFF_SUMMARY_PATH = os.path.join(ARTIFACTS_DIR, "pr-diff-summary.md")
 21REPO_STATS_PATH = os.path.join(ARTIFACTS_DIR, "repo-stats.md")
 22
 23
 24def load_repo_stats():
 25    """Load the repo stats markdown, or None if unavailable."""
 26    try:
 27        with open(REPO_STATS_PATH) as f:
 28            content = f.read().strip()
 29            return content if content else None
 30    except Exception:
 31        return None
 32
 33
 34def load_findings(filename):
 35    """Load a findings JSON array from the artifacts directory, or empty list on error."""
 36    try:
 37        with open(os.path.join(ARTIFACTS_DIR, filename)) as f:
 38            data = json.load(f)
 39            return data if isinstance(data, list) else []
 40    except Exception:
 41        return []
 42
 43
 44def normalize_finding(f):
 45    """Return {"msg": str, "level": str} from a dict or plain string."""
 46    if isinstance(f, dict):
 47        return {"msg": str(f.get("msg", "")), "level": f.get("level", "warning")}
 48    return {"msg": str(f), "level": "warning"}
 49
 50
 51def collect_findings():
 52    """Gather all findings, split into (errors, warnings) lists of message strings."""
 53    raw = []
 54    raw.extend(load_findings("findings-compliance.json"))
 55    raw.extend(load_findings("findings-data.json"))
 56    raw.extend(load_findings("findings-project.json"))
 57    errors = []
 58    warnings = []
 59    for f in raw:
 60        normalized = normalize_finding(f)
 61        if normalized["level"] == "error":
 62            errors.append(normalized["msg"])
 63        else:
 64            warnings.append(normalized["msg"])
 65    return errors, warnings
 66
 67
 68def load_diff_summary():
 69    """Load the pre-formatted diff summary, or None if unavailable."""
 70    try:
 71        with open(DIFF_SUMMARY_PATH) as f:
 72            content = f.read().strip()
 73            return content if content else None
 74    except Exception:
 75        return None
 76
 77
 78def _extract_changes_bullets(diff_summary):
 79    """Re-format bullet lines from the diff summary with a blue circle prefix."""
 80    if not diff_summary:
 81        return None
 82    bullets = []
 83    for line in diff_summary.splitlines():
 84        if line.startswith("- "):
 85            bullets.append(f"- \U0001f535 {line[2:]}")
 86    return "\n".join(bullets) if bullets else None
 87
 88
 89def format_comment(findings, user, changes_summary, run_id, repo_stats=None):
 90    """Build the markdown comment."""
 91    parts = [
 92        f"<!-- pr-check-bot -->\nHello @{user}\n",
 93        f"Thank you for contributing to Awesome Privacy! We will review your "
 94        f"submission shortly. In the meantime, please ensure all changes are "
 95        f"correct and inline with our [Contributing Requirements]({CONTRIBUTING}).\n",
 96    ]
 97
 98    if findings:
 99        bullet_list = "\n".join(f"- {f}" for f in findings)
100        parts.append(
101            f"Our automated checks detected some issues:\n\n{bullet_list}\n\n"
102        )
103    else:
104        parts.append("> \u2705 All our automated checks have passed.")
105
106    if changes_summary:
107        parts.append(
108            f"<details><summary>Summary of Changes:</summary>\n\n"
109            f"{changes_summary}\n</details>"
110        )
111
112    if repo_stats:
113        parts.append(
114            f"<details><summary>Submission Info</summary>\n\n"
115            f"{repo_stats}\n</details>"
116        )
117
118    if run_id:
119        parts.append(
120            f'<sup>For full details, please see workflow run '
121            f'<a href="{REPO_URL}/actions/runs/{run_id}">{run_id}</a></sup>'
122        )
123
124    return "\n\n".join(parts) + "\n"
125
126
127def write_step_summary(errors, warnings, user, pr_number, run_id, changes_summary,
128                       repo_stats=None):
129    """Write a structured summary to GITHUB_STEP_SUMMARY."""
130    summary_file = os.environ.get("GITHUB_STEP_SUMMARY")
131    if not summary_file:
132        return
133
134    lines = ["## Status Check Results\n"]
135
136    # Summary sentence
137    ne, nw = len(errors), len(warnings)
138    lines.append("### Summary\n")
139    if ne and nw:
140        lines.append(
141            f"There are {ne} error(s) which must be resolved before this PR can be"
142            f" reviewed, as well as {nw} warning(s) which need to be addressed or"
143            f" justified.\n"
144        )
145    elif ne:
146        lines.append(
147            f"There are {ne} error(s) which must be resolved before this PR can be"
148            f" reviewed.\n"
149        )
150    elif nw:
151        lines.append(
152            f"There were no errors but {nw} warning(s) which need to be addressed"
153            f" or justified before the PR can be merged.\n"
154        )
155    else:
156        lines.append(
157            "All checks are passing, with no errors and no warnings \U0001f389\n"
158            "A maintainer has been notified, and will review the submission shortly.\n"
159        )
160
161    # Errors
162    lines.append("### Errors\n")
163    if errors:
164        for e in errors:
165            lines.append(f"- \U0001f534 {e}")
166    else:
167        lines.append("\u2705 None")
168    lines.append("")
169
170    # Warnings
171    lines.append("### Warnings\n")
172    if warnings:
173        for w in warnings:
174            lines.append(f"- \U0001f7e1 {w}")
175    else:
176        lines.append("\u2705 None")
177    lines.append("")
178
179    # Meta Info
180    lines.append("### Meta Info\n")
181    now = datetime.now(timezone.utc)
182    timestamp = now.strftime("%H:%M UTC on %d %b %Y")
183    if pr_number:
184        lines.append(
185            f"This workflow run was triggered at {timestamp}"
186            f" for PR [#{pr_number}](https://github.com/Lissy93/awesome-privacy/pull/{pr_number})"
187            f" which was opened by @{user}\n"
188        )
189    else:
190        lines.append(
191            f"This workflow run was triggered at {timestamp} by @{user}\n"
192        )
193
194    if changes_summary:
195        lines.append("The PR introduces the following changes:\n")
196        lines.append(f"{changes_summary}\n")
197
198    if repo_stats:
199        lines.append("### Submission Info\n")
200        lines.append(f"{repo_stats}\n")
201
202    with open(summary_file, "a") as f:
203        f.write("\n".join(lines) + "\n")
204
205
206def main():
207    try:
208        user = os.environ.get("PR_USER", "contributor")
209        pr_number = os.environ.get("PR_NUMBER", "")
210        run_id = os.environ.get("RUN_ID", "")
211
212        os.makedirs(OUTPUT_DIR, exist_ok=True)
213
214        if pr_number:
215            with open(os.path.join(OUTPUT_DIR, "number.txt"), "w") as f:
216                f.write(pr_number)
217        if run_id:
218            with open(os.path.join(OUTPUT_DIR, "run-id.txt"), "w") as f:
219                f.write(run_id)
220
221        errors, warnings = collect_findings()
222        all_findings = errors + warnings
223        with open(os.path.join(OUTPUT_DIR, "findings-count.txt"), "w") as f:
224            f.write(str(len(all_findings)))
225        with open(os.path.join(OUTPUT_DIR, "error-count.txt"), "w") as f:
226            f.write(str(len(errors)))
227        changes_summary = load_diff_summary()
228        changes_bullets = _extract_changes_bullets(changes_summary)
229        repo_stats = load_repo_stats()
230        write_step_summary(errors, warnings, user, pr_number, run_id, changes_bullets,
231                           repo_stats)
232
233        comment = format_comment(all_findings, user, changes_summary, run_id, repo_stats)
234        with open(os.path.join(OUTPUT_DIR, "comment.md"), "w") as f:
235            f.write(comment)
236    except Exception as exc:
237        logging.error("Unhandled error in main: %s", exc, exc_info=True)
238
239    sys.exit(0)
240
241
242if __name__ == "__main__":
243    main()