lib/checks/format-comment.py
245 lines · 8503 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 disclaimer = "> <sup> 🤖 I am a bot, and sometimes make mistakes. "
99 disclaimer += "If you feel that any info here is incorrect or inaccurate, "
100 disclaimer += "feel free to add a comment below with any corrections or justifications. "
101 disclaimer += "This bot does <b>not</b> use AI, and just runs preliminary validation "
102 disclaimer += "checks against submission requirements. Human review is still needed.</sup>"
103
104 if findings:
105 bullet_list = "\n".join(f"- {f}" for f in findings)
106 parts.append(
107 f"Our automated checks detected some issues:\n\n{bullet_list}\n\n"
108 f"{disclaimer}\n"
109 )
110 else:
111 parts.append("> \u2705 All our automated checks have passed.")
112
113 if changes_summary:
114 parts.append(
115 f"<details><summary>Summary of Changes:</summary>\n\n"
116 f"{changes_summary}\n</details>"
117 )
118
119 if repo_stats:
120 parts.append(
121 f"<details><summary>Submission Info</summary>\n\n"
122 f"{repo_stats}\n</details>"
123 )
124
125 if run_id:
126 parts.append(
127 f'<sup>For full details, please see workflow run '
128 f'<a href="{REPO_URL}/actions/runs/{run_id}">{run_id}</a></sup>'
129 )
130
131 return "\n\n".join(parts) + "\n"
132
133
134def write_step_summary(errors, warnings, user, pr_number, run_id, changes_summary,
135 repo_stats=None):
136 """Creates a human-readable summary of all checks, and writes to GITHUB_STEP_SUMMARY."""
137 summary_file = os.environ.get("GITHUB_STEP_SUMMARY")
138 if not summary_file:
139 return
140
141 lines = ["## Status Check Results\n"]
142
143 # Summary sentence
144 ne, nw = len(errors), len(warnings)
145 lines.append("### Summary\n")
146 if ne and nw:
147 lines.append(
148 f"There are {ne} error(s) which must be resolved before this PR can be"
149 f" reviewed, as well as {nw} warning(s) which need to be addressed or"
150 f" justified.\n"
151 )
152 elif ne:
153 lines.append(
154 f"There are {ne} error(s) which must be resolved before this PR can be reviewed.\n"
155 )
156 elif nw:
157 lines.append(
158 f"There were no errors but {nw} warning(s) which should to be addressed"
159 f" or justified before the PR can be merged.\n"
160 )
161 else:
162 lines.append(
163 "All checks are passing, with no errors and no warnings \U0001f389\n"
164 "A maintainer has been notified, and will review the submission shortly.\n"
165 )
166
167 # Errors
168 lines.append("### Errors\n")
169 if errors:
170 for e in errors:
171 lines.append(f"- \U0001f534 {e}")
172 else:
173 lines.append("\u2705 None")
174 lines.append("")
175
176 # Warnings
177 lines.append("### Warnings\n")
178 if warnings:
179 for w in warnings:
180 lines.append(f"- \U0001f7e1 {w}")
181 else:
182 lines.append("\u2705 None")
183 lines.append("")
184
185 # Meta Info
186 lines.append("### Meta Info\n")
187 timestamp = datetime.now(timezone.utc).strftime("%H:%M UTC on %d %b %Y")
188 pr_ref = f" for PR [#{pr_number}](https://github.com/Lissy93/awesome-privacy/pull/{pr_number})" if pr_number else ""
189 attempt = os.environ.get("GITHUB_RUN_ATTEMPT", "")
190 attempt_ref = f" (Attempt {attempt})" if attempt and attempt != "1" else ""
191 lines.append(f"This workflow was triggered at {timestamp}{pr_ref} by @{user}{attempt_ref}\n")
192
193 # Summary of changes (what was added/removed/edited in which sections)
194 if changes_summary:
195 lines.append("The PR introduces the following changes:\n")
196 lines.append(f"{changes_summary}\n")
197
198 # Submission info (like the automated info looked up about repo, web, app, etc)
199 if repo_stats:
200 lines.append("### Submission Info\n")
201 lines.append(f"{repo_stats}\n")
202
203 # All done, write to file for outputting to workflow summary
204 with open(summary_file, "a") as f:
205 f.write("\n".join(lines) + "\n")
206
207
208def main():
209 try:
210 user = os.environ.get("PR_USER", "contributor")
211 pr_number = os.environ.get("PR_NUMBER", "")
212 run_id = os.environ.get("RUN_ID", "")
213
214 os.makedirs(OUTPUT_DIR, exist_ok=True)
215
216 if pr_number:
217 with open(os.path.join(OUTPUT_DIR, "number.txt"), "w") as f:
218 f.write(pr_number)
219 if run_id:
220 with open(os.path.join(OUTPUT_DIR, "run-id.txt"), "w") as f:
221 f.write(run_id)
222
223 errors, warnings = collect_findings()
224 all_findings = errors + warnings
225 with open(os.path.join(OUTPUT_DIR, "findings-count.txt"), "w") as f:
226 f.write(str(len(all_findings)))
227 with open(os.path.join(OUTPUT_DIR, "error-count.txt"), "w") as f:
228 f.write(str(len(errors)))
229 changes_summary = load_diff_summary()
230 changes_bullets = _extract_changes_bullets(changes_summary)
231 repo_stats = load_repo_stats()
232 write_step_summary(errors, warnings, user, pr_number, run_id, changes_bullets,
233 repo_stats)
234
235 comment = format_comment(all_findings, user, changes_summary, run_id, repo_stats)
236 with open(os.path.join(OUTPUT_DIR, "comment.md"), "w") as f:
237 f.write(comment)
238 except Exception as exc:
239 logging.error("Unhandled error in main: %s", exc, exc_info=True)
240
241 sys.exit(0)
242
243
244if __name__ == "__main__":
245 main()