Commit 0f9bfc992a

0f9bfc992a50d17514d9f40e82218f8245712c3f

parent: c88eafdb86

Unsigned

Alicia Sykes <alicia@omg.lol> · 2026-03-16 00:02 UTC

Improves efficiency and adds std err logs in workflow

Layout: unified · split

lib/checks/check-additions.py +10 −2
@@ -1,11 +1,18 @@
1"""Validates data quality for added/modified services using the diff JSON.""" 1"""Validates data quality for added/modified services using the diff JSON."""
2 2
3import json 3import json
4import logging
4import os 5import os
5import sys 6import sys
6 7
7import yaml 8import yaml
8 9
10logging.basicConfig(
11 level=logging.INFO,
12 format="%(levelname)s [%(filename)s] %(message)s",
13 stream=sys.stderr,
14)
15
9PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 16PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
10DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml") 17DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml")
11DIFF_PATH = "/tmp/pr-diff.json" 18DIFF_PATH = "/tmp/pr-diff.json"
@@ -281,9 +288,10 @@ def main():
281 finding = check_opensource_github(diff) 288 finding = check_opensource_github(diff)
282 if finding: 289 if finding:
283 findings.append(finding) 290 findings.append(finding)
284 except Exception: 291 except Exception as exc:
285 pass 292 logging.error("Unhandled error in main: %s", exc, exc_info=True)
286 293
294 logging.info("Writing %d finding(s) to %s", len(findings), FINDINGS_PATH)
287 with open(FINDINGS_PATH, "w") as f: 295 with open(FINDINGS_PATH, "w") as f:
288 json.dump(findings, f) 296 json.dump(findings, f)
289 sys.exit(1 if critical else 0) 297 sys.exit(1 if critical else 0)
lib/checks/check-pr-meta.py +12 −4
@@ -1,11 +1,18 @@
1"""Checks PR metadata: title format, draft status, template completeness, and checkboxes.""" 1"""Checks PR metadata: title format, draft status, template completeness, and checkboxes."""
2 2
3import json 3import json
4import logging
4import os 5import os
5import re 6import re
6import subprocess 7import subprocess
7import sys 8import sys
8 9
10logging.basicConfig(
11 level=logging.INFO,
12 format="%(levelname)s [%(filename)s] %(message)s",
13 stream=sys.stderr,
14)
15
9FINDINGS_PATH = "/tmp/findings-compliance.json" 16FINDINGS_PATH = "/tmp/findings-compliance.json"
10 17
11BAD_TITLES = {"update readme.md", "update awesome-privacy.yml"} 18BAD_TITLES = {"update readme.md", "update awesome-privacy.yml"}
@@ -106,8 +113,8 @@ def check_bot_coauthors(base_ref):
106 return None 113 return None
107 if _BOT_AUTHOR_RE.search(result.stdout): 114 if _BOT_AUTHOR_RE.search(result.stdout):
108 return BOT_MSG 115 return BOT_MSG
109 except Exception: 116 except Exception as exc:
110 pass 117 logging.warning("check_bot_coauthors error: %s", exc)
111 return None 118 return None
112 119
113 120
@@ -163,9 +170,10 @@ def main():
163 finding = check_readme(readme_failed) 170 finding = check_readme(readme_failed)
164 if finding: 171 if finding:
165 findings.append({"msg": finding, "level": "error"}) 172 findings.append({"msg": finding, "level": "error"})
166 except Exception: 173 except Exception as exc:
167 pass 174 logging.error("Unhandled error in main: %s", exc, exc_info=True)
168 175
176 logging.info("Writing %d finding(s) to %s", len(findings), FINDINGS_PATH)
169 write_findings(findings) 177 write_findings(findings)
170 sys.exit(1 if critical else 0) 178 sys.exit(1 if critical else 0)
171 179
lib/checks/check-project.py +73 −70
@@ -1,6 +1,7 @@
1"""Checks project health: URL reachability, GitHub repo stars, activity, and author match.""" 1"""Checks project health: URL reachability, GitHub repo stars, activity, and author match."""
2 2
3import json 3import json
4import logging
4import os 5import os
5import re 6import re
6import sys 7import sys
@@ -9,6 +10,12 @@ from datetime import datetime, timedelta, timezone
9import requests 10import requests
10import yaml 11import yaml
11 12
13logging.basicConfig(
14 level=logging.INFO,
15 format="%(levelname)s [%(filename)s] %(message)s",
16 stream=sys.stderr,
17)
18
12PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 19PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
13DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml") 20DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml")
14DIFF_PATH = "/tmp/pr-diff.json" 21DIFF_PATH = "/tmp/pr-diff.json"
@@ -112,8 +119,11 @@ def check_url(url):
112 headers={"User-Agent": USER_AGENT}, stream=True, 119 headers={"User-Agent": USER_AGENT}, stream=True,
113 ) 120 )
114 resp.close() 121 resp.close()
122 if resp.status_code >= 400:
123 logging.warning("URL check failed for %s (HTTP %d)", url, resp.status_code)
115 return resp.status_code < 400 124 return resp.status_code < 400
116 except Exception: 125 except Exception as exc:
126 logging.warning("URL check error for %s: %s", url, exc)
117 return True 127 return True
118 128
119 129
@@ -133,23 +143,37 @@ def parse_github_field(value):
133 return None, None 143 return None, None
134 144
135 145
136def fetch_repo(owner, repo, token): 146def _gh_get(path, token, params=None, label=""):
137 """Fetch GitHub repo metadata, returning None on any error.""" 147 """GET a GitHub API endpoint. Returns parsed JSON on 200, None otherwise."""
148 headers = {"Accept": "application/vnd.github.v3+json", "User-Agent": USER_AGENT}
149 if token:
150 headers["Authorization"] = f"token {token}"
138 try: 151 try:
139 headers = {"Accept": "application/vnd.github.v3+json", "User-Agent": USER_AGENT}
140 if token:
141 headers["Authorization"] = f"token {token}"
142 resp = requests.get( 152 resp = requests.get(
143 f"https://api.github.com/repos/{owner}/{repo}", 153 f"https://api.github.com{path}",
144 headers=headers, timeout=TIMEOUT, 154 headers=headers, timeout=TIMEOUT, params=params,
145 ) 155 )
156 remaining = resp.headers.get("X-RateLimit-Remaining")
157 if remaining is not None:
158 try:
159 if int(remaining) < 100:
160 logging.warning("[%s] GitHub rate limit low: %s/%s remaining",
161 label, remaining, resp.headers.get("X-RateLimit-Limit"))
162 except ValueError:
163 pass
146 if resp.status_code == 200: 164 if resp.status_code == 200:
147 return resp.json() 165 return resp.json()
148 except Exception: 166 logging.warning("[%s] HTTP %d from %s", label, resp.status_code, path)
149 pass 167 except Exception as exc:
168 logging.warning("[%s] request error for %s: %s", label, path, exc)
150 return None 169 return None
151 170
152 171
172def fetch_repo(owner, repo, token):
173 """Fetch GitHub repo metadata, returning None on any error."""
174 return _gh_get(f"/repos/{owner}/{repo}", token, label="repos")
175
176
153def load_yaml_data(): 177def load_yaml_data():
154 """Load the head YAML, returning None on any error.""" 178 """Load the head YAML, returning None on any error."""
155 try: 179 try:
@@ -224,65 +248,42 @@ def _commit_has_bot(commit, bot_set):
224 248
225def check_ai_commits(owner, repo, token): 249def check_ai_commits(owner, repo, token):
226 """Return AI_CODE_MSG if recent commits contain significant AI bot activity.""" 250 """Return AI_CODE_MSG if recent commits contain significant AI bot activity."""
227 try: 251 commits = _gh_get(f"/repos/{owner}/{repo}/commits", token,
228 headers = {"Accept": "application/vnd.github.v3+json", "User-Agent": USER_AGENT} 252 params={"per_page": 100}, label="commits")
229 if token: 253 if not commits:
230 headers["Authorization"] = f"token {token}" 254 return None
231 resp = requests.get( 255 bot_set = {a.lower() for a in AI_BOT_AUTHORS}
232 f"https://api.github.com/repos/{owner}/{repo}/commits", 256 count = sum(1 for c in commits if _commit_has_bot(c, bot_set))
233 headers=headers, timeout=TIMEOUT, params={"per_page": 100}, 257 if count / len(commits) >= AI_COMMIT_RATIO:
234 ) 258 return AI_CODE_MSG
235 if resp.status_code != 200:
236 return None
237 commits = resp.json()
238 if not commits:
239 return None
240 bot_set = {a.lower() for a in AI_BOT_AUTHORS}
241 count = sum(1 for c in commits if _commit_has_bot(c, bot_set))
242 if count / len(commits) >= AI_COMMIT_RATIO:
243 return AI_CODE_MSG
244 except Exception:
245 pass
246 return None 259 return None
247 260
248 261
249def check_security_alerts(owner, repo, token): 262def check_security_alerts(owner, repo, token):
250 """Return SECURITY_MSG if the repo has open critical/high Dependabot alerts.""" 263 """Return SECURITY_MSG if the repo has open critical/high Dependabot alerts."""
251 try: 264 alerts = _gh_get(f"/repos/{owner}/{repo}/dependabot/alerts", token,
252 headers = {"Accept": "application/vnd.github.v3+json", "User-Agent": USER_AGENT} 265 params={"state": "open", "severity": "critical,high", "per_page": 1},
253 if token: 266 label="dependabot")
254 headers["Authorization"] = f"token {token}" 267 if alerts:
255 resp = requests.get( 268 return SECURITY_MSG
256 f"https://api.github.com/repos/{owner}/{repo}/dependabot/alerts",
257 headers=headers, timeout=TIMEOUT,
258 params={"state": "open", "severity": "critical,high", "per_page": 1},
259 )
260 if resp.status_code == 200 and resp.json():
261 return SECURITY_MSG
262 except Exception:
263 pass
264 return None 269 return None
265 270
266 271
267def check_spam_prs(pr_user, token): 272def check_spam_prs(pr_user, token):
268 """Return list of spam findings based on recent PR activity.""" 273 """Return list of spam findings based on recent PR activity."""
269 if not pr_user or not token: 274 if not pr_user or not token:
275 logging.warning("check_spam_prs skipped: %s", "no PR_USER" if not pr_user else "no GITHUB_TOKEN")
270 return [] 276 return []
271 try: 277 try:
272 since = (datetime.now(timezone.utc) - timedelta(days=SPAM_WINDOW_DAYS)).strftime("%Y-%m-%d") 278 since = (datetime.now(timezone.utc) - timedelta(days=SPAM_WINDOW_DAYS)).strftime("%Y-%m-%d")
273 headers = { 279 data = _gh_get("/search/issues", token,
274 "Accept": "application/vnd.github.v3+json", 280 params={"q": f"type:pr author:{pr_user} created:>={since}", "per_page": 100},
275 "User-Agent": USER_AGENT, 281 label="spam")
276 "Authorization": f"token {token}", 282 if not data:
277 }
278 resp = requests.get(
279 "https://api.github.com/search/issues",
280 headers=headers, timeout=TIMEOUT,
281 params={"q": f"type:pr author:{pr_user} created:>={since}"},
282 )
283 if resp.status_code != 200:
284 return [] 283 return []
285 items = resp.json().get("items", []) 284 items = data.get("items", [])
285 logging.info("check_spam_prs: %d total PRs for %s (fetched %d)",
286 data.get("total_count", 0), pr_user, len(items))
286 this_repo = os.environ.get("GITHUB_REPOSITORY", "Lissy93/awesome-privacy").lower() 287 this_repo = os.environ.get("GITHUB_REPOSITORY", "Lissy93/awesome-privacy").lower()
287 awesome_count = 0 288 awesome_count = 0
288 distinct_repos = set() 289 distinct_repos = set()
@@ -296,13 +297,16 @@ def check_spam_prs(pr_user, token):
296 repo_name = repo_url.rstrip("/").split("/")[-1].lower() 297 repo_name = repo_url.rstrip("/").split("/")[-1].lower()
297 if repo_name.startswith("awesome-"): 298 if repo_name.startswith("awesome-"):
298 awesome_count += 1 299 awesome_count += 1
300 logging.info("check_spam_prs: %d awesome-* PRs, %d distinct repos",
301 awesome_count, len(distinct_repos))
299 findings = [] 302 findings = []
300 if awesome_count >= SPAM_AWESOME_THRESHOLD: 303 if awesome_count >= SPAM_AWESOME_THRESHOLD:
301 findings.append(SPAM_AWESOME_MSG) 304 findings.append(SPAM_AWESOME_MSG)
302 if len(distinct_repos) >= SPAM_DISTINCT_REPO_THRESHOLD: 305 if len(distinct_repos) >= SPAM_DISTINCT_REPO_THRESHOLD:
303 findings.append(SPAM_MANY_MSG) 306 findings.append(SPAM_MANY_MSG)
304 return findings 307 return findings
305 except Exception: 308 except Exception as exc:
309 logging.warning("check_spam_prs error for %s: %s", pr_user, exc)
306 return [] 310 return []
307 311
308 312
@@ -310,18 +314,13 @@ def check_new_account(pr_user, token):
310 """Return NEW_ACCOUNT_MSG if the PR author's GitHub account is very new.""" 314 """Return NEW_ACCOUNT_MSG if the PR author's GitHub account is very new."""
311 if not pr_user or not token: 315 if not pr_user or not token:
312 return None 316 return None
317 data = _gh_get(f"/users/{pr_user}", token, label="user")
318 if not data:
319 return None
320 created = data.get("created_at")
321 if not created:
322 return None
313 try: 323 try:
314 headers = {"Accept": "application/vnd.github.v3+json", "User-Agent": USER_AGENT}
315 headers["Authorization"] = f"token {token}"
316 resp = requests.get(
317 f"https://api.github.com/users/{pr_user}",
318 headers=headers, timeout=TIMEOUT,
319 )
320 if resp.status_code != 200:
321 return None
322 created = resp.json().get("created_at")
323 if not created:
324 return None
325 created_dt = datetime.fromisoformat(created.replace("Z", "+00:00")) 324 created_dt = datetime.fromisoformat(created.replace("Z", "+00:00"))
326 if (datetime.now(timezone.utc) - created_dt).days < NEW_ACCOUNT_DAYS: 325 if (datetime.now(timezone.utc) - created_dt).days < NEW_ACCOUNT_DAYS:
327 return NEW_ACCOUNT_MSG 326 return NEW_ACCOUNT_MSG
@@ -439,8 +438,13 @@ def check_repo_signals(diff, pr_user, token, pr_body=""):
439def main(): 438def main():
440 findings = [] 439 findings = []
441 try: 440 try:
441 pr_user = os.environ.get("PR_USER", "")
442 token = os.environ.get("GITHUB_TOKEN", "")
443 logging.info("PR_USER=%s, GITHUB_TOKEN=%s", pr_user or "(empty)", "present" if token else "MISSING")
444
442 diff = load_diff(DIFF_PATH) 445 diff = load_diff(DIFF_PATH)
443 if not diff: 446 if not diff:
447 logging.info("No diff file at %s, nothing to check", DIFF_PATH)
444 with open(FINDINGS_PATH, "w") as f: 448 with open(FINDINGS_PATH, "w") as f:
445 json.dump(findings, f) 449 json.dump(findings, f)
446 sys.exit(0) 450 sys.exit(0)
@@ -450,9 +454,7 @@ def main():
450 if finding: 454 if finding:
451 findings.append(finding) 455 findings.append(finding)
452 456
453 pr_user = os.environ.get("PR_USER", "")
454 pr_body = os.environ.get("PR_BODY", "") 457 pr_body = os.environ.get("PR_BODY", "")
455 token = os.environ.get("GITHUB_TOKEN", "")
456 458
457 findings.extend(check_spam_prs(pr_user, token)) 459 findings.extend(check_spam_prs(pr_user, token))
458 460
@@ -465,9 +467,10 @@ def main():
465 findings.append(finding) 467 findings.append(finding)
466 468
467 findings.extend(check_repo_signals(diff, pr_user, token, pr_body)) 469 findings.extend(check_repo_signals(diff, pr_user, token, pr_body))
468 except Exception: 470 except Exception as exc:
469 pass 471 logging.error("Unhandled error in main: %s", exc, exc_info=True)
470 472
473 logging.info("Writing %d finding(s) to %s", len(findings), FINDINGS_PATH)
471 with open(FINDINGS_PATH, "w") as f: 474 with open(FINDINGS_PATH, "w") as f:
472 json.dump(findings, f) 475 json.dump(findings, f)
473 sys.exit(0) 476 sys.exit(0)
lib/checks/format-comment.py +9 −2
@@ -1,10 +1,17 @@
1"""Aggregates findings from all check jobs into a formatted PR comment.""" 1"""Aggregates findings from all check jobs into a formatted PR comment."""
2 2
3import json 3import json
4import logging
4import os 5import os
5import sys 6import sys
6from datetime import datetime, timezone 7from datetime import datetime, timezone
7 8
9logging.basicConfig(
10 level=logging.INFO,
11 format="%(levelname)s [%(filename)s] %(message)s",
12 stream=sys.stderr,
13)
14
8ARTIFACTS_DIR = "/tmp/artifacts" 15ARTIFACTS_DIR = "/tmp/artifacts"
9OUTPUT_DIR = "/tmp/pr-meta" 16OUTPUT_DIR = "/tmp/pr-meta"
10 17
@@ -229,8 +236,8 @@ def main():
229 comment = format_comment(all_findings, user, changes_summary, run_id, repo_stats) 236 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: 237 with open(os.path.join(OUTPUT_DIR, "comment.md"), "w") as f:
231 f.write(comment) 238 f.write(comment)
232 except Exception: 239 except Exception as exc:
233 pass 240 logging.error("Unhandled error in main: %s", exc, exc_info=True)
234 241
235 sys.exit(0) 242 sys.exit(0)
236 243