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 @@
11"""Validates data quality for added/modified services using the diff JSON."""
22
33import json
4import logging
45import os
56import sys
67
78import yaml
89
10logging.basicConfig(
11 level=logging.INFO,
12 format="%(levelname)s [%(filename)s] %(message)s",
13 stream=sys.stderr,
14)
15
916PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
1017DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml")
1118DIFF_PATH = "/tmp/pr-diff.json"
@@ -281,9 +288,10 @@ def main():
281288 finding = check_opensource_github(diff)
282289 if finding:
283290 findings.append(finding)
284 except Exception:
285 pass
291 except Exception as exc:
292 logging.error("Unhandled error in main: %s", exc, exc_info=True)
286293
294 logging.info("Writing %d finding(s) to %s", len(findings), FINDINGS_PATH)
287295 with open(FINDINGS_PATH, "w") as f:
288296 json.dump(findings, f)
289297 sys.exit(1 if critical else 0)
lib/checks/check-pr-meta.py +12 −4
@@ -1,11 +1,18 @@
11"""Checks PR metadata: title format, draft status, template completeness, and checkboxes."""
22
33import json
4import logging
45import os
56import re
67import subprocess
78import sys
89
10logging.basicConfig(
11 level=logging.INFO,
12 format="%(levelname)s [%(filename)s] %(message)s",
13 stream=sys.stderr,
14)
15
916FINDINGS_PATH = "/tmp/findings-compliance.json"
1017
1118BAD_TITLES = {"update readme.md", "update awesome-privacy.yml"}
@@ -106,8 +113,8 @@ def check_bot_coauthors(base_ref):
106113 return None
107114 if _BOT_AUTHOR_RE.search(result.stdout):
108115 return BOT_MSG
109 except Exception:
110 pass
116 except Exception as exc:
117 logging.warning("check_bot_coauthors error: %s", exc)
111118 return None
112119
113120
@@ -163,9 +170,10 @@ def main():
163170 finding = check_readme(readme_failed)
164171 if finding:
165172 findings.append({"msg": finding, "level": "error"})
166 except Exception:
167 pass
173 except Exception as exc:
174 logging.error("Unhandled error in main: %s", exc, exc_info=True)
168175
176 logging.info("Writing %d finding(s) to %s", len(findings), FINDINGS_PATH)
169177 write_findings(findings)
170178 sys.exit(1 if critical else 0)
171179
lib/checks/check-project.py +73 −70
@@ -1,6 +1,7 @@
11"""Checks project health: URL reachability, GitHub repo stars, activity, and author match."""
22
33import json
4import logging
45import os
56import re
67import sys
@@ -9,6 +10,12 @@ from datetime import datetime, timedelta, timezone
910import requests
1011import yaml
1112
13logging.basicConfig(
14 level=logging.INFO,
15 format="%(levelname)s [%(filename)s] %(message)s",
16 stream=sys.stderr,
17)
18
1219PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
1320DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml")
1421DIFF_PATH = "/tmp/pr-diff.json"
@@ -112,8 +119,11 @@ def check_url(url):
112119 headers={"User-Agent": USER_AGENT}, stream=True,
113120 )
114121 resp.close()
122 if resp.status_code >= 400:
123 logging.warning("URL check failed for %s (HTTP %d)", url, resp.status_code)
115124 return resp.status_code < 400
116 except Exception:
125 except Exception as exc:
126 logging.warning("URL check error for %s: %s", url, exc)
117127 return True
118128
119129
@@ -133,23 +143,37 @@ def parse_github_field(value):
133143 return None, None
134144
135145
136def fetch_repo(owner, repo, token):
137 """Fetch GitHub repo metadata, returning None on any error."""
146def _gh_get(path, token, params=None, label=""):
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}"
138151 try:
139 headers = {"Accept": "application/vnd.github.v3+json", "User-Agent": USER_AGENT}
140 if token:
141 headers["Authorization"] = f"token {token}"
142152 resp = requests.get(
143 f"https://api.github.com/repos/{owner}/{repo}",
144 headers=headers, timeout=TIMEOUT,
153 f"https://api.github.com{path}",
154 headers=headers, timeout=TIMEOUT, params=params,
145155 )
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
146164 if resp.status_code == 200:
147165 return resp.json()
148 except Exception:
149 pass
166 logging.warning("[%s] HTTP %d from %s", label, resp.status_code, path)
167 except Exception as exc:
168 logging.warning("[%s] request error for %s: %s", label, path, exc)
150169 return None
151170
152171
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
153177def load_yaml_data():
154178 """Load the head YAML, returning None on any error."""
155179 try:
@@ -224,65 +248,42 @@ def _commit_has_bot(commit, bot_set):
224248
225249def check_ai_commits(owner, repo, token):
226250 """Return AI_CODE_MSG if recent commits contain significant AI bot activity."""
227 try:
228 headers = {"Accept": "application/vnd.github.v3+json", "User-Agent": USER_AGENT}
229 if token:
230 headers["Authorization"] = f"token {token}"
231 resp = requests.get(
232 f"https://api.github.com/repos/{owner}/{repo}/commits",
233 headers=headers, timeout=TIMEOUT, params={"per_page": 100},
234 )
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
251 commits = _gh_get(f"/repos/{owner}/{repo}/commits", token,
252 params={"per_page": 100}, label="commits")
253 if not commits:
254 return None
255 bot_set = {a.lower() for a in AI_BOT_AUTHORS}
256 count = sum(1 for c in commits if _commit_has_bot(c, bot_set))
257 if count / len(commits) >= AI_COMMIT_RATIO:
258 return AI_CODE_MSG
246259 return None
247260
248261
249262def check_security_alerts(owner, repo, token):
250263 """Return SECURITY_MSG if the repo has open critical/high Dependabot alerts."""
251 try:
252 headers = {"Accept": "application/vnd.github.v3+json", "User-Agent": USER_AGENT}
253 if token:
254 headers["Authorization"] = f"token {token}"
255 resp = requests.get(
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 alerts = _gh_get(f"/repos/{owner}/{repo}/dependabot/alerts", token,
265 params={"state": "open", "severity": "critical,high", "per_page": 1},
266 label="dependabot")
267 if alerts:
268 return SECURITY_MSG
264269 return None
265270
266271
267272def check_spam_prs(pr_user, token):
268273 """Return list of spam findings based on recent PR activity."""
269274 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")
270276 return []
271277 try:
272278 since = (datetime.now(timezone.utc) - timedelta(days=SPAM_WINDOW_DAYS)).strftime("%Y-%m-%d")
273 headers = {
274 "Accept": "application/vnd.github.v3+json",
275 "User-Agent": USER_AGENT,
276 "Authorization": f"token {token}",
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:
279 data = _gh_get("/search/issues", token,
280 params={"q": f"type:pr author:{pr_user} created:>={since}", "per_page": 100},
281 label="spam")
282 if not data:
284283 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))
286287 this_repo = os.environ.get("GITHUB_REPOSITORY", "Lissy93/awesome-privacy").lower()
287288 awesome_count = 0
288289 distinct_repos = set()
@@ -296,13 +297,16 @@ def check_spam_prs(pr_user, token):
296297 repo_name = repo_url.rstrip("/").split("/")[-1].lower()
297298 if repo_name.startswith("awesome-"):
298299 awesome_count += 1
300 logging.info("check_spam_prs: %d awesome-* PRs, %d distinct repos",
301 awesome_count, len(distinct_repos))
299302 findings = []
300303 if awesome_count >= SPAM_AWESOME_THRESHOLD:
301304 findings.append(SPAM_AWESOME_MSG)
302305 if len(distinct_repos) >= SPAM_DISTINCT_REPO_THRESHOLD:
303306 findings.append(SPAM_MANY_MSG)
304307 return findings
305 except Exception:
308 except Exception as exc:
309 logging.warning("check_spam_prs error for %s: %s", pr_user, exc)
306310 return []
307311
308312
@@ -310,18 +314,13 @@ def check_new_account(pr_user, token):
310314 """Return NEW_ACCOUNT_MSG if the PR author's GitHub account is very new."""
311315 if not pr_user or not token:
312316 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
313323 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
325324 created_dt = datetime.fromisoformat(created.replace("Z", "+00:00"))
326325 if (datetime.now(timezone.utc) - created_dt).days < NEW_ACCOUNT_DAYS:
327326 return NEW_ACCOUNT_MSG
@@ -439,8 +438,13 @@ def check_repo_signals(diff, pr_user, token, pr_body=""):
439438def main():
440439 findings = []
441440 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
442445 diff = load_diff(DIFF_PATH)
443446 if not diff:
447 logging.info("No diff file at %s, nothing to check", DIFF_PATH)
444448 with open(FINDINGS_PATH, "w") as f:
445449 json.dump(findings, f)
446450 sys.exit(0)
@@ -450,9 +454,7 @@ def main():
450454 if finding:
451455 findings.append(finding)
452456
453 pr_user = os.environ.get("PR_USER", "")
454457 pr_body = os.environ.get("PR_BODY", "")
455 token = os.environ.get("GITHUB_TOKEN", "")
456458
457459 findings.extend(check_spam_prs(pr_user, token))
458460
@@ -465,9 +467,10 @@ def main():
465467 findings.append(finding)
466468
467469 findings.extend(check_repo_signals(diff, pr_user, token, pr_body))
468 except Exception:
469 pass
470 except Exception as exc:
471 logging.error("Unhandled error in main: %s", exc, exc_info=True)
470472
473 logging.info("Writing %d finding(s) to %s", len(findings), FINDINGS_PATH)
471474 with open(FINDINGS_PATH, "w") as f:
472475 json.dump(findings, f)
473476 sys.exit(0)
lib/checks/format-comment.py +9 −2
@@ -1,10 +1,17 @@
11"""Aggregates findings from all check jobs into a formatted PR comment."""
22
33import json
4import logging
45import os
56import sys
67from datetime import datetime, timezone
78
9logging.basicConfig(
10 level=logging.INFO,
11 format="%(levelname)s [%(filename)s] %(message)s",
12 stream=sys.stderr,
13)
14
815ARTIFACTS_DIR = "/tmp/artifacts"
916OUTPUT_DIR = "/tmp/pr-meta"
1017
@@ -229,8 +236,8 @@ def main():
229236 comment = format_comment(all_findings, user, changes_summary, run_id, repo_stats)
230237 with open(os.path.join(OUTPUT_DIR, "comment.md"), "w") as f:
231238 f.write(comment)
232 except Exception:
233 pass
239 except Exception as exc:
240 logging.error("Unhandled error in main: %s", exc, exc_info=True)
234241
235242 sys.exit(0)
236243