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