Commit 3e0466da7b

3e0466da7b5da445c9bc104a476f03cd8d83fe71

parent: 4bd889bf0e

Unsigned

Alicia Sykes <alicia@omg.lol> · 2026-06-05 20:39 UTC

Removes print statemnts, more standardised script logs

Layout: unified · split

lib/awesome-privacy-readme-gen.py +5 −1
@@ -5,13 +5,17 @@ formats into markdown, and inserts into README.md
55
66import os
77import re
8import sys
89import yaml
910import logging
1011from urllib.parse import urlparse
1112
13sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
14import utils
15
1216# Configure Logging
1317LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()
14logging.basicConfig(level=LOG_LEVEL)
18utils.setup_logging(LOG_LEVEL)
1519logger = logging.getLogger(__name__)
1620
1721# Determine the project root based on the script's location
lib/checks/check-additions.py +35 −39
@@ -7,11 +7,11 @@ import sys
77
88import yaml
99
10logging.basicConfig(
11 level=logging.INFO,
12 format="%(levelname)s [%(filename)s] %(message)s",
13 stream=sys.stderr,
14)
10sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11import utils
12
13utils.setup_logging()
14logger = logging.getLogger(__name__)
1515
1616PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
1717DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml")
@@ -278,51 +278,47 @@ def main():
278278 critical = False
279279 try:
280280 if os.environ.get("SCHEMA_OUTCOME") == "failure":
281 logger.warning("Schema validation failed upstream, surfacing schema errors")
281282 findings.extend(schema_findings())
282283
283284 diff = load_json(DIFF_PATH)
284285 head = load_yaml_data(DATA_PATH)
285286
286 if diff:
287 finding = check_single_entry(diff)
288 if finding:
289 findings.append(finding)
290
291 finding = check_required_fields(diff, head)
292 if finding:
293 findings.append({"msg": finding, "level": "error"})
294 critical = True
295
296 finding = check_position(diff, head)
297 if finding:
298 findings.append(finding)
299
300 finding = check_open_source(diff)
301 if finding:
302 findings.append(finding)
287 if not diff:
288 logger.info("No diff at %s, nothing to validate", DIFF_PATH)
289 else:
290 added = diff.get("services", {}).get("added", [])
291 modified = diff.get("services", {}).get("modified", [])
292 logger.info("Validating additions: %d added, %d modified service(s)",
293 len(added), len(modified))
303294
304295 name_index = build_name_index(head, diff)
305296 url_index = build_url_index(head, diff)
306297
307 finding = check_duplicate_name(diff, name_index)
308 if finding:
309 findings.append(finding)
310
311 finding = check_duplicate_url(diff, url_index)
312 if finding:
313 findings.append(finding)
314
315 finding = check_description_length(diff)
316 if finding:
317 findings.append(finding)
318
319 finding = check_opensource_github(diff)
320 if finding:
321 findings.append(finding)
298 checks = [
299 ("single-entry", check_single_entry(diff), False),
300 ("required-fields", check_required_fields(diff, head), True),
301 ("position", check_position(diff, head), False),
302 ("open-source", check_open_source(diff), False),
303 ("duplicate-name", check_duplicate_name(diff, name_index), False),
304 ("duplicate-url", check_duplicate_url(diff, url_index), False),
305 ("description-length", check_description_length(diff), False),
306 ("opensource-repo", check_opensource_github(diff), False),
307 ]
308 for name, finding, is_error in checks:
309 if not finding:
310 continue
311 logger.info("flagged: %s", name)
312 if is_error:
313 findings.append({"msg": finding, "level": "error"})
314 critical = True
315 else:
316 findings.append(finding)
322317 except Exception as exc:
323 logging.error("Unhandled error in main: %s", exc, exc_info=True)
318 logger.error("Unhandled error in main: %s", exc, exc_info=True)
324319
325 logging.info("Writing %d finding(s) to %s", len(findings), FINDINGS_PATH)
320 logger.info("Additions check: %d finding(s)%s, writing to %s",
321 len(findings), " (critical)" if critical else "", FINDINGS_PATH)
326322 with open(FINDINGS_PATH, "w") as f:
327323 json.dump(findings, f)
328324 sys.exit(1 if critical else 0)
lib/checks/check-pr-meta.py +11 −8
@@ -7,11 +7,11 @@ import re
77import subprocess
88import sys
99
10logging.basicConfig(
11 level=logging.INFO,
12 format="%(levelname)s [%(filename)s] %(message)s",
13 stream=sys.stderr,
14)
10sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11import utils
12
13utils.setup_logging()
14logger = logging.getLogger(__name__)
1515
1616FINDINGS_PATH = "/tmp/findings-compliance.json"
1717
@@ -135,7 +135,7 @@ def check_bot_coauthors(base_ref):
135135 if _BOT_AUTHOR_RE.search(result.stdout):
136136 return BOT_MSG
137137 except Exception as exc:
138 logging.warning("check_bot_coauthors error: %s", exc)
138 logger.warning("check_bot_coauthors error: %s", exc)
139139 return None
140140
141141
@@ -162,6 +162,8 @@ def main():
162162 readme_failed = os.environ.get("README_FAILED", "false")
163163 base_ref = os.environ.get("BASE_REF", "")
164164
165 logger.info("Checking PR metadata: title, draft, template, checkboxes, type, bot authors")
166
165167 finding = check_bot_coauthors(base_ref)
166168 if finding:
167169 findings.append(finding)
@@ -195,9 +197,10 @@ def main():
195197 if finding:
196198 findings.append({"msg": finding, "level": "error"})
197199 except Exception as exc:
198 logging.error("Unhandled error in main: %s", exc, exc_info=True)
200 logger.error("Unhandled error in main: %s", exc, exc_info=True)
199201
200 logging.info("Writing %d finding(s) to %s", len(findings), FINDINGS_PATH)
202 logger.info("PR metadata: %d finding(s)%s, writing to %s",
203 len(findings), " (critical)" if critical else "", FINDINGS_PATH)
201204 write_findings(findings)
202205 sys.exit(1 if critical else 0)
203206
lib/checks/check-project.py +13 −15
@@ -12,11 +12,8 @@ import yaml
1212sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
1313import utils
1414
15logging.basicConfig(
16 level=logging.INFO,
17 format="%(levelname)s [%(filename)s] %(message)s",
18 stream=sys.stderr,
19)
15utils.setup_logging()
16logger = logging.getLogger(__name__)
2017
2118PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
2219DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml")
@@ -112,9 +109,9 @@ def check_url(url):
112109 """Return True if the URL is reachable. Transport errors are treated as reachable."""
113110 ok, status = utils.check_url(url, SESSION, TIMEOUT)
114111 if not ok:
115 logging.warning("URL check failed for %s (HTTP %d)", url, status)
112 logger.warning("URL check failed for %s (HTTP %d)", url, status)
116113 elif status is None:
117 logging.warning("URL check error for %s (unreachable)", url)
114 logger.warning("URL check error for %s (unreachable)", url)
118115 return ok
119116
120117
@@ -206,7 +203,7 @@ def check_security_alerts(owner, repo, token):
206203def check_spam_prs(pr_user, token):
207204 """Return list of spam findings based on recent PR activity."""
208205 if not pr_user or not token:
209 logging.warning("check_spam_prs skipped: %s", "no PR_USER" if not pr_user else "no GITHUB_TOKEN")
206 logger.warning("check_spam_prs skipped: %s", "no PR_USER" if not pr_user else "no GITHUB_TOKEN")
210207 return []
211208 try:
212209 since = (datetime.now(timezone.utc) - timedelta(days=SPAM_WINDOW_DAYS)).strftime("%Y-%m-%d")
@@ -216,7 +213,7 @@ def check_spam_prs(pr_user, token):
216213 if not data:
217214 return []
218215 items = data.get("items", [])
219 logging.info("check_spam_prs: %d total PRs for %s (fetched %d)",
216 logger.info("check_spam_prs: %d total PRs for %s (fetched %d)",
220217 data.get("total_count", 0), pr_user, len(items))
221218 this_repo = os.environ.get("GITHUB_REPOSITORY", "Lissy93/awesome-privacy").lower()
222219 awesome_count = 0
@@ -231,7 +228,7 @@ def check_spam_prs(pr_user, token):
231228 repo_name = repo_url.rstrip("/").split("/")[-1].lower()
232229 if repo_name.startswith("awesome-"):
233230 awesome_count += 1
234 logging.info("check_spam_prs: %d awesome-* PRs, %d distinct repos",
231 logger.info("check_spam_prs: %d awesome-* PRs, %d distinct repos",
235232 awesome_count, len(distinct_repos))
236233 findings = []
237234 if awesome_count >= SPAM_AWESOME_THRESHOLD:
@@ -240,7 +237,7 @@ def check_spam_prs(pr_user, token):
240237 findings.append(SPAM_MANY_MSG)
241238 return findings
242239 except Exception as exc:
243 logging.warning("check_spam_prs error for %s: %s", pr_user, exc)
240 logger.warning("check_spam_prs error for %s: %s", pr_user, exc)
244241 return []
245242
246243
@@ -389,11 +386,12 @@ def main():
389386 try:
390387 pr_user = os.environ.get("PR_USER", "")
391388 token = os.environ.get("GITHUB_TOKEN", "")
392 logging.info("PR_USER=%s, GITHUB_TOKEN=%s", pr_user or "(empty)", "present" if token else "MISSING")
389 logger.info("Checking project health: links, spam, account age, duplicate URLs, repo signals")
390 logger.info("PR_USER=%s, GITHUB_TOKEN=%s", pr_user or "(empty)", "present" if token else "MISSING")
393391
394392 diff = load_diff(DIFF_PATH)
395393 if not diff:
396 logging.info("No diff file at %s, nothing to check", DIFF_PATH)
394 logger.info("No diff file at %s, nothing to check", DIFF_PATH)
397395 with open(FINDINGS_PATH, "w") as f:
398396 json.dump(findings, f)
399397 sys.exit(0)
@@ -421,9 +419,9 @@ def main():
421419
422420 findings.extend(check_repo_signals(diff, pr_user, token, pr_body))
423421 except Exception as exc:
424 logging.error("Unhandled error in main: %s", exc, exc_info=True)
422 logger.error("Unhandled error in main: %s", exc, exc_info=True)
425423
426 logging.info("Writing %d finding(s) to %s", len(findings), FINDINGS_PATH)
424 logger.info("Project health: %d finding(s), writing to %s", len(findings), FINDINGS_PATH)
427425 with open(FINDINGS_PATH, "w") as f:
428426 json.dump(findings, f)
429427 sys.exit(0)
lib/checks/check-readme-edits.py +15 −10
@@ -4,11 +4,18 @@ The generated section is between <!-- awesome-privacy-start --> and <!-- awesome
44"""
55
66import argparse
7import logging
78import os
89import re
910import subprocess
1011import sys
1112
13sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
14import utils
15
16utils.setup_logging()
17logger = logging.getLogger(__name__)
18
1219PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
1320README_PATH = ".github/README.md"
1421README_ABS = os.path.join(PROJECT_ROOT, README_PATH)
@@ -18,11 +25,6 @@ EXIT_PASS = 0
1825EXIT_FAIL = 1
1926EXIT_RUNTIME_ERROR = 2
2027
21# ANSI color helpers
22_use_color = sys.stderr.isatty() and not os.environ.get("NO_COLOR")
23red = (lambda s: f"\033[31m{s}\033[0m") if _use_color else (lambda s: s)
24green = (lambda s: f"\033[32m{s}\033[0m") if _use_color else (lambda s: s)
25
2628
2729def get_changed_files(base_ref):
2830 result = subprocess.run(
@@ -77,27 +79,30 @@ def main():
7779 parser.add_argument("--base-ref", required=True, help="Base git ref to diff against")
7880 args = parser.parse_args()
7981
82 logger.info("Checking README for direct edits to the generated section")
83
8084 # Skip if README wasn't changed
8185 changed_files = get_changed_files(args.base_ref)
8286 if README_PATH not in changed_files:
83 print(green("README not modified, skipping."))
87 logger.info("README not modified, skipping")
8488 sys.exit(EXIT_PASS)
8589
8690 # Find marker lines
8791 start_line, end_line = get_marker_lines()
8892 if start_line is None or end_line is None:
89 print("Could not find generated-section markers in README, skipping check.")
93 logger.warning("Generated-section markers not found in README, skipping check")
9094 sys.exit(EXIT_PASS)
9195
9296 # Check if any changed lines fall within the generated section
9397 changed_lines = get_changed_line_numbers(args.base_ref)
98 logger.info("README edited (%d line(s)); generated section spans lines %d-%d",
99 len(changed_lines), start_line, end_line)
94100 for line_num in changed_lines:
95101 if start_line <= line_num <= end_line:
96 print(red("Direct edits to the generated section of the README are not allowed."), file=sys.stderr)
97 print(red("Edit awesome-privacy.yml instead and the README will be regenerated."), file=sys.stderr)
102 logger.error("Edit to generated section at line %d: edit awesome-privacy.yml instead", line_num)
98103 sys.exit(EXIT_FAIL)
99104
100 print(green("README changes are outside the generated section, OK."))
105 logger.info("README edits are outside the generated section, OK")
101106 sys.exit(EXIT_PASS)
102107
103108
lib/checks/check-review-ready.py +14
@@ -12,7 +12,15 @@ Writes:
1212"""
1313
1414import json
15import logging
1516import os
17import sys
18
19sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
20import utils
21
22utils.setup_logging()
23logger = logging.getLogger(__name__)
1624
1725WORK_DIR = "pr-meta"
1826MAINTAINER = "Lissy93"
@@ -67,22 +75,28 @@ def write_action(action):
6775
6876
6977def main():
78 logger.info("Checking whether the PR is ready for maintainer review")
7079 if already_notified():
80 logger.info("Maintainer already notified, action=skip")
7181 write_action("skip")
7282 return
7383
7484 reviews = read_json("reviews.json")
7585 approvals = count_external_approvals(reviews)
86 logger.info("%d external approval(s), need %d", approvals, REQUIRED_APPROVALS)
7687
7788 if approvals < REQUIRED_APPROVALS:
89 logger.info("Not enough approvals, action=skip")
7890 write_action("skip")
7991 return
8092
8193 check_runs = read_json("check-runs.json")
8294 if not all_checks_passing(check_runs):
95 logger.info("Not all %d check run(s) passing, action=skip", len(check_runs))
8396 write_action("skip")
8497 return
8598
99 logger.info("Approvals met and all checks passing, action=notify")
86100 write_action("notify")
87101
88102
lib/checks/check-yaml-diff.py +16 −13
@@ -4,14 +4,19 @@ Enforces the single-entry rule and outputs a JSON diff to /tmp/pr-diff.json.
44
55import argparse
66import json
7import logging
78import os
89import sys
910
1011import yaml
1112
1213sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
14import utils
1315from yaml_diff import build_index, diff_index, load_yaml_at_ref
1416
17utils.setup_logging()
18logger = logging.getLogger(__name__)
19
1520PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
1621DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml")
1722DIFF_OUTPUT_PATH = "/tmp/pr-diff.json"
@@ -21,17 +26,12 @@ EXIT_PASS = 0
2126EXIT_RULE_VIOLATION = 1
2227EXIT_RUNTIME_ERROR = 2
2328
24_use_color = sys.stderr.isatty() and not os.environ.get("NO_COLOR")
25red = (lambda s: f"\033[31m{s}\033[0m") if _use_color else (lambda s: s)
26green = (lambda s: f"\033[32m{s}\033[0m") if _use_color else (lambda s: s)
27yellow = (lambda s: f"\033[33m{s}\033[0m") if _use_color else (lambda s: s)
28
2929
3030def load_base_yaml(base_ref):
3131 """Load the YAML from the base ref using git show."""
3232 data = load_yaml_at_ref(base_ref, PROJECT_ROOT)
3333 if data is None:
34 print(yellow("awesome-privacy.yml not found in base ref, treating as empty"), file=sys.stderr)
34 logger.warning("awesome-privacy.yml not found in base ref, treating as empty")
3535 return {"categories": []}
3636 return data
3737
@@ -42,7 +42,7 @@ def load_head_yaml():
4242 with open(DATA_PATH) as f:
4343 return yaml.safe_load(f)
4444 except (FileNotFoundError, yaml.YAMLError) as e:
45 print(red(f"Failed to load head YAML: {e}"), file=sys.stderr)
45 logger.error("Failed to load head YAML: %s", e)
4646 sys.exit(EXIT_RUNTIME_ERROR)
4747
4848
@@ -125,6 +125,7 @@ def main():
125125 parser.add_argument("--base-ref", required=True)
126126 args = parser.parse_args()
127127
128 logger.info("Diffing awesome-privacy.yml against base ref %s", args.base_ref)
128129 base = load_base_yaml(args.base_ref)
129130 head = load_head_yaml()
130131
@@ -176,24 +177,26 @@ def main():
176177 write_github_output("has_service_changes", str(bool(added or removed or modified)).lower())
177178 write_diff_summary(diff_result)
178179
180 logger.info("Diff: services +%d/-%d/~%d, sections %d, categories %d, duplicates %d",
181 len(added), len(removed), len(modified), len(sections), len(categories), len(dup_entries))
182
179183 added_count = len(added)
180184 if added_count > 1:
181 print(red(f"Single-entry rule violation: {added_count} service additions found."), file=sys.stderr)
185 logger.error("Single-entry rule violation: %d service additions found", added_count)
182186 sys.exit(EXIT_RULE_VIOLATION)
183187 added_sections = [s for s in sections if s["change_type"] == "added_section"]
184188 if added_count == 0 and len(added_sections) > 1:
185 print(red(f"Single-entry rule violation: {len(added_sections)} section additions found."), file=sys.stderr)
189 logger.error("Single-entry rule violation: %d section additions found", len(added_sections))
186190 sys.exit(EXIT_RULE_VIOLATION)
187191
188192 if duplicates:
189193 names = ", ".join(f"{d[2]} (in {d[0]} → {d[1]})" for d in duplicates)
190 print(red(f"Duplicate service names found: {names}"), file=sys.stderr)
194 logger.error("Duplicate service names found: %s", names)
191195 sys.exit(EXIT_RULE_VIOLATION)
192196
193197 total = len(added) + len(removed) + len(modified)
194 print(green(f"Single-entry rule passed. {total} service "
195 f"({added_count} added), {len(sections)} section, "
196 f"{len(categories)} category change(s)."))
198 logger.info("Single-entry rule passed: %d service change(s) (%d added), %d section, %d category change(s)",
199 total, added_count, len(sections), len(categories))
197200 sys.exit(EXIT_PASS)
198201
199202
lib/checks/detect-changes.py +10 −3
@@ -4,10 +4,17 @@ Sets GitHub Actions output: yaml_changed.
44"""
55
66import argparse
7import logging
78import os
89import subprocess
910import sys
1011
12sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
13import utils
14
15utils.setup_logging()
16logger = logging.getLogger(__name__)
17
1118PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
1219
1320YAML_FILE = "awesome-privacy.yml"
@@ -33,13 +40,13 @@ def main():
3340
3441 changed_files = [f for f in result.stdout.strip().splitlines() if f]
3542
36 print("Changed files:")
43 logger.info("Detected %d changed file(s) since %s", len(changed_files), args.base_ref)
3744 for f in changed_files:
38 print(f" {f}")
45 logger.debug(" %s", f)
3946
4047 yaml_changed = YAML_FILE in changed_files
4148 write_github_output("yaml_changed", str(yaml_changed).lower())
42 print(f"yaml_changed={yaml_changed}")
49 logger.info("%s changed: %s", YAML_FILE, yaml_changed)
4350
4451
4552if __name__ == "__main__":
lib/checks/format-comment.py +11 −7
@@ -6,11 +6,11 @@ import os
66import sys
77from datetime import datetime, timezone
88
9logging.basicConfig(
10 level=logging.INFO,
11 format="%(levelname)s [%(filename)s] %(message)s",
12 stream=sys.stderr,
13)
9sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
10import utils
11
12utils.setup_logging()
13logger = logging.getLogger(__name__)
1414
1515ARTIFACTS_DIR = "/tmp/artifacts"
1616OUTPUT_DIR = "/tmp/pr-meta"
@@ -220,8 +220,10 @@ def main():
220220 with open(os.path.join(OUTPUT_DIR, "run-id.txt"), "w") as f:
221221 f.write(run_id)
222222
223 logger.info("Aggregating findings from all check jobs in %s", ARTIFACTS_DIR)
223224 errors, warnings = collect_findings()
224225 all_findings = errors + warnings
226 logger.info("Collected %d error(s) and %d warning(s)", len(errors), len(warnings))
225227 with open(os.path.join(OUTPUT_DIR, "findings-count.txt"), "w") as f:
226228 f.write(str(len(all_findings)))
227229 with open(os.path.join(OUTPUT_DIR, "error-count.txt"), "w") as f:
@@ -233,10 +235,12 @@ def main():
233235 repo_stats)
234236
235237 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:
238 comment_path = os.path.join(OUTPUT_DIR, "comment.md")
239 with open(comment_path, "w") as f:
237240 f.write(comment)
241 logger.info("Wrote PR comment to %s", comment_path)
238242 except Exception as exc:
239 logging.error("Unhandled error in main: %s", exc, exc_info=True)
243 logger.error("Unhandled error in main: %s", exc, exc_info=True)
240244
241245 sys.exit(0)
242246
lib/checks/make-info-stats.py +23 −11
@@ -20,6 +20,7 @@ Excuse the code, it's a bit scrappy! But it's never used in the prod app.
2020
2121import argparse
2222import json
23import logging
2324import os
2425import sys
2526from datetime import datetime, timezone
@@ -28,6 +29,9 @@ from urllib.parse import urlparse
2829sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
2930import utils
3031
32utils.setup_logging()
33logger = logging.getLogger(__name__)
34
3135DIFF_PATH = "/tmp/pr-diff.json"
3236OUTPUT_PATH = "/tmp/repo-stats.md"
3337TIMEOUT = 10
@@ -54,7 +58,7 @@ def _api_get(url, params=None, timeout=TIMEOUT, headers=None):
5458 if resp.status_code == 200:
5559 return resp.json()
5660 except Exception as e:
57 print(f"Fetch failed for {url}: {e}", file=sys.stderr)
61 logger.warning("Fetch failed for %s: %s", url, e)
5862 return None
5963
6064
@@ -494,7 +498,7 @@ def _resolve_args(argv):
494498 if args.repo:
495499 owner, repo = utils.parse_github_field(args.repo)
496500 if not owner:
497 print(f"Invalid repo format: {args.repo}", file=sys.stderr)
501 logger.error("Invalid repo format: %s", args.repo)
498502 sys.exit(1)
499503 result["owner"], result["repo"] = owner, repo
500504 return [result]
@@ -504,7 +508,7 @@ def _resolve_args(argv):
504508 with open(DIFF_PATH) as f:
505509 diff = json.load(f)
506510 except Exception:
507 print("No arguments and no diff file found", file=sys.stderr)
511 logger.info("No arguments and no diff file found, nothing to look up")
508512 sys.exit(0)
509513
510514 field_map = {"github": "owner", "url": "url", "androidApp": "android",
@@ -524,9 +528,10 @@ def _resolve_args(argv):
524528 services.append(result)
525529
526530 if not services:
527 print("No checkable fields found in diff", file=sys.stderr)
531 logger.info("No checkable fields found in diff")
528532 sys.exit(0)
529533
534 logger.info("Found %d service(s) with checkable fields in diff", len(services))
530535 return services
531536
532537
@@ -535,19 +540,21 @@ def _build_service_sections(args, token):
535540 sections = []
536541
537542 if args["owner"] and args["repo"]:
543 logger.info("Fetching repo stats for %s/%s", args["owner"], args["repo"])
538544 data = fetch_all_data(args["owner"], args["repo"], token)
539545 if data:
540546 sections.append(("Repo Stats", format_markdown(grade_stats(data))))
541547 else:
542 print(f"Failed to fetch repo data for {args['owner']}/{args['repo']}", file=sys.stderr)
548 logger.warning("Failed to fetch repo data for %s/%s", args["owner"], args["repo"])
543549
544550 if args["url"]:
545551 parsed_url = urlparse(args["url"])
546552 if parsed_url.hostname and parsed_url.hostname.rstrip(".").endswith("github.com"):
547 print(f"Skipped website checks, since github repo was specified: {args['url']}", file=sys.stderr)
553 logger.info("Skipped website checks, github repo was specified: %s", args["url"])
548554 sections.append(("Website Checks",
549555 f"- {ORANGE} **Skipped** web checks, since repo URL was submitted instead of a website"))
550556 else:
557 logger.info("Fetching website checks for %s", args["url"])
551558 site_data = fetch_website_data(args["url"])
552559 has_sec_txt = check_security_txt(args["url"])
553560 if site_data or has_sec_txt is not None:
@@ -555,25 +562,28 @@ def _build_service_sections(args, token):
555562 format_markdown(grade_website_stats(site_data, args["url"], has_sec_txt))))
556563
557564 if args["android"]:
565 logger.info("Fetching Android app info for %s", args["android"])
558566 data = fetch_android_data(args["android"])
559567 if data:
560568 sections.append(("Android App", format_markdown(grade_android_stats(data))))
561569 else:
562 print(f"Failed to fetch Android data for {args['android']}", file=sys.stderr)
570 logger.warning("Failed to fetch Android data for %s", args["android"])
563571
564572 if args["ios"]:
573 logger.info("Fetching iOS app info for %s", args["ios"])
565574 data = fetch_ios_data(args["ios"])
566575 if data:
567576 sections.append(("iOS App", format_markdown(grade_ios_stats(data))))
568577 else:
569 print(f"Failed to fetch iOS data for {args['ios']}", file=sys.stderr)
578 logger.warning("Failed to fetch iOS data for %s", args["ios"])
570579
571580 if args["tosdr"]:
581 logger.info("Fetching ToS;DR privacy policy for %s", args["tosdr"])
572582 data = fetch_tosdr_data(args["tosdr"])
573583 if data:
574584 sections.append(("Privacy Policy", format_markdown(grade_tosdr_stats(data))))
575585 else:
576 print(f"Failed to fetch ToS;DR data for {args['tosdr']}", file=sys.stderr)
586 logger.warning("Failed to fetch ToS;DR data for %s", args["tosdr"])
577587
578588 return sections
579589
@@ -587,6 +597,8 @@ def main():
587597 all_md_parts = []
588598
589599 for svc_args in all_services:
600 if svc_args.get("name"):
601 logger.info("Looking up submission info for %s", svc_args["name"])
590602 sections = _build_service_sections(svc_args, token)
591603 if not sections:
592604 continue
@@ -609,9 +621,9 @@ def main():
609621 else:
610622 with open(OUTPUT_PATH, "w") as f:
611623 f.write(md + "\n")
612 print(f"Stats written to {OUTPUT_PATH}")
624 logger.info("Submission stats written to %s", OUTPUT_PATH)
613625 except Exception as e:
614 print(f"make-info-stats failed: {e}", file=sys.stderr)
626 logger.error("make-info-stats failed: %s", e, exc_info=True)
615627
616628 sys.exit(0)
617629
lib/checks/prepare-comment.py +16
@@ -10,8 +10,16 @@ Writes:
1010 pr-meta/final-comment.md — the body to post or update with
1111"""
1212
13import logging
1314import os
1415import re
16import sys
17
18sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
19import utils
20
21utils.setup_logging()
22logger = logging.getLogger(__name__)
1523
1624WORK_DIR = "pr-meta"
1725
@@ -160,11 +168,13 @@ def write_output(action, body=""):
160168
161169
162170def main():
171 logger.info("Preparing PR bot comment (deciding create/update/skip)")
163172 check_run_id = os.environ.get("CHECK_RUN_ID", "")
164173 repo = os.environ.get("GITHUB_REPOSITORY", "")
165174
166175 new_body = read_file(os.path.join(WORK_DIR, "comment.md"))
167176 if not new_body:
177 logger.info("No new comment.md to post, action=skip")
168178 write_output("skip")
169179 return
170180
@@ -172,15 +182,18 @@ def main():
172182
173183 # No existing comment — create a new one
174184 if not existing_body:
185 logger.info("No existing bot comment, action=create")
175186 write_output("create", new_body)
176187 return
177188
178189 # Existing comment — build an edit line to append
179190 if not check_run_id:
191 logger.info("Existing comment but no CHECK_RUN_ID, action=skip")
180192 write_output("skip")
181193 return
182194
183195 findings_count = read_findings_count(new_body)
196 logger.info("Existing comment found, new run reports %d finding(s)", findings_count)
184197 edit_line = build_edit_line(existing_body, findings_count, check_run_id, repo)
185198
186199 # Refresh the Submission Info block even if findings haven't changed
@@ -188,6 +201,7 @@ def main():
188201 info_changed = refreshed_body != existing_body
189202
190203 if not edit_line and not info_changed:
204 logger.info("State unchanged and submission info unchanged, action=skip")
191205 write_output("skip")
192206 return
193207
@@ -197,6 +211,8 @@ def main():
197211 updated = updated.rstrip() + "\n" + edit_line
198212 else:
199213 updated = updated.rstrip() + "\n\n---\n\n### Updates\n\n" + edit_line
214 logger.info("Updating comment (new edit=%s, submission info changed=%s), action=update",
215 bool(edit_line), info_changed)
200216 write_output("update", updated)
201217
202218
lib/generate-changelog.py +25 −21
@@ -4,6 +4,7 @@ and enriches entries with GitHub PR metadata.
44"""
55
66import json
7import logging
78import os
89import re
910import subprocess
@@ -14,8 +15,12 @@ from typing import Any
1415import requests
1516
1617sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
18import utils
1719from yaml_diff import build_index, diff_index, load_yaml_at_ref
1820
21utils.setup_logging()
22logger = logging.getLogger(__name__)
23
1924PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
2025OUTPUT_PATH = os.path.join(PROJECT_ROOT, ".github", "changelog.json")
2126REPO = "Lissy93/awesome-privacy"
@@ -49,7 +54,7 @@ def get_commits():
4954 continue
5055 lines = record.split("\n", 3)
5156 if len(lines) != 4:
52 print(f" Skipping malformed log record: {record[:80]}", file=sys.stderr)
57 logger.warning("Skipping malformed log record: %s", record[:80])
5358 continue
5459 sha, date, author, message = lines
5560 commits.append({"sha": sha, "date": date, "author": author, "message": message})
@@ -216,7 +221,7 @@ def fetch_pr_metadata(pr_numbers):
216221 if token:
217222 headers["Authorization"] = f"token {token}"
218223 else:
219 print(" No GITHUB_TOKEN set, API rate limit will be low", file=sys.stderr)
224 logger.warning("No GITHUB_TOKEN set, API rate limit will be low")
220225
221226 metadata = {}
222227 for i, pr_num in enumerate(sorted(pr_numbers)):
@@ -234,12 +239,12 @@ def fetch_pr_metadata(pr_numbers):
234239 "authorAvatar": data.get("user", {}).get("avatar_url", ""),
235240 }
236241 elif resp.status_code == 403:
237 print(f" Rate limited at PR #{pr_num}, stopping API calls", file=sys.stderr)
242 logger.warning("Rate limited at PR #%s, stopping API calls", pr_num)
238243 break
239244 elif resp.status_code != 404:
240 print(f" PR #{pr_num}: HTTP {resp.status_code}", file=sys.stderr)
245 logger.warning("PR #%s: HTTP %s", pr_num, resp.status_code)
241246 except requests.RequestException as e:
242 print(f" PR #{pr_num}: {e}", file=sys.stderr)
247 logger.warning("PR #%s: %s", pr_num, e)
243248 if i < len(pr_numbers) - 1:
244249 time.sleep(0.1)
245250
@@ -265,8 +270,7 @@ def fetch_rejections(headers, cached_rejections, checked_prs):
265270 "per_page": 100, "page": page},
266271 )
267272 if resp.status_code != 200:
268 print(f" Rejections page {page}: HTTP {resp.status_code} — keeping cache",
269 file=sys.stderr)
273 logger.warning("Rejections page %s: HTTP %s, keeping cache", page, resp.status_code)
270274 return cached_rejections, checked_prs
271275 prs = resp.json()
272276 if not prs:
@@ -274,7 +278,7 @@ def fetch_rejections(headers, cached_rejections, checked_prs):
274278
275279 for pr in prs:
276280 if pr.get("created_at", "") < REJECTIONS_SINCE:
277 print(f" Reused {reused} cached, checked {new_calls} new PR(s)")
281 logger.info("Reused %d cached, checked %d new PR(s)", reused, new_calls)
278282 return rejections, checked
279283 if pr.get("merged_at"):
280284 continue
@@ -316,10 +320,10 @@ def fetch_rejections(headers, cached_rejections, checked_prs):
316320 page += 1
317321 time.sleep(0.1)
318322 except requests.RequestException as e:
319 print(f" Rejections: {e} — keeping cache", file=sys.stderr)
323 logger.warning("Rejections: %s, keeping cache", e)
320324 return cached_rejections, checked_prs
321325
322 print(f" Reused {reused} cached, checked {new_calls} new PR(s)")
326 logger.info("Reused %d cached, checked %d new PR(s)", reused, new_calls)
323327 return rejections, checked
324328
325329
@@ -342,7 +346,7 @@ def load_existing():
342346
343347
344348def main():
345 print("Generating changelog from git history...")
349 logger.info("Generating changelog from git history")
346350
347351 existing_entries, processed_shas, existing_rejections, checked_prs = load_existing()
348352 commits = get_commits()
@@ -360,7 +364,7 @@ def main():
360364 new_processed = set()
361365
362366 if new_commits:
363 print(f"Processing {len(new_commits)} new commit(s) ({len(existing_entries)} existing)...")
367 logger.info("Processing %d new commit(s) (%d existing)", len(new_commits), len(existing_entries))
364368
365369 all_shas = [c["sha"] for c in commits]
366370 sha_to_parent = {all_shas[i]: all_shas[i + 1] for i in range(len(all_shas) - 1)}
@@ -387,9 +391,9 @@ def main():
387391 continue
388392
389393 changes = diff_commits(c["sha"], parent)
390 prefix = f" [{i}/{len(new_commits)}]"
394 prefix = f"[{i}/{len(new_commits)}]"
391395 if changes is None:
392 print(f"{prefix} {c['date'][:10]} (no data changes)", flush=True)
396 logger.debug("%s %s (no data changes)", prefix, c["date"][:10])
393397 continue
394398
395399 # Sync merges pull content in via their 2nd parent, so their own message
@@ -407,11 +411,11 @@ def main():
407411 continue
408412 new_processed.add(pm["sha"])
409413 counts = emit(pm["sha"], pm["date"], pm["message"], pm_changes)
410 print(f"{prefix} {pm['date'][:10]} {counts} (via sync) {pm['message'][:50]}", flush=True)
414 logger.debug("%s %s %s (via sync) %s", prefix, pm["date"][:10], counts, pm["message"][:50])
411415 continue
412416
413417 counts = emit(c["sha"], c["date"], c["message"], changes)
414 print(f"{prefix} {c['date'][:10]} {counts} {c['message'][:60]}", flush=True)
418 logger.debug("%s %s %s %s", prefix, c["date"][:10], counts, c["message"][:60])
415419
416420 # Enrich entries missing full avatar data
417421 for e in existing_entries:
@@ -420,14 +424,14 @@ def main():
420424 pr_numbers_to_fetch.add(pr["number"])
421425
422426 if pr_numbers_to_fetch:
423 print(f"Fetching metadata for {len(pr_numbers_to_fetch)} PR(s)...")
427 logger.info("Fetching metadata for %d PR(s)", len(pr_numbers_to_fetch))
424428 pr_meta = fetch_pr_metadata(pr_numbers_to_fetch)
425429 for entry in new_entries + existing_entries:
426430 pr = entry.get("pr")
427431 if pr and pr.get("number") and pr["number"] in pr_meta:
428432 entry["pr"] = pr_meta[pr["number"]]
429433 else:
430 print(f"No new commits. {len(existing_entries)} entries up to date.")
434 logger.info("No new commits, %d entries up to date", len(existing_entries))
431435
432436 all_entries = sorted(new_entries + existing_entries, key=lambda e: e["date"], reverse=True)
433437
@@ -436,9 +440,9 @@ def main():
436440 api_headers = {"User-Agent": "awesome-privacy", "Accept": "application/vnd.github.v3+json"}
437441 if token:
438442 api_headers["Authorization"] = f"token {token}"
439 print("Fetching rejected PRs...")
443 logger.info("Fetching rejected PRs")
440444 rejections, checked_prs = fetch_rejections(api_headers, existing_rejections, checked_prs)
441 print(f" Found {len(rejections)} rejection(s)")
445 logger.info("Found %d rejection(s)", len(rejections))
442446
443447 os.makedirs(os.path.dirname(OUTPUT_PATH), exist_ok=True)
444448 with open(OUTPUT_PATH, "w") as f:
@@ -450,7 +454,7 @@ def main():
450454 "rejections": rejections,
451455 }, f, indent=2, ensure_ascii=False)
452456
453 print(f"Wrote {len(all_entries)} entries + {len(rejections)} rejections to {OUTPUT_PATH}")
457 logger.info("Wrote %d entries + %d rejections to %s", len(all_entries), len(rejections), OUTPUT_PATH)
454458
455459
456460if __name__ == "__main__":
lib/utils/__init__.py +25 −16
@@ -1,22 +1,31 @@
1"""Shared helpers for lib/ scripts. Re-exports the public API of each submodule."""
1"""Shared helpers for lib/ scripts. Re-exports the public API of each submodule.
2
3`.term` (logging/colors) is stdlib-only and always importable. The other
4submodules need `requests`/`yaml`; some CI jobs install no extra deps, so those
5imports are skipped there, letting `setup_logging()` work without them.
6"""
27
3from .data import DATA_PATH, PROJECT_ROOT, iter_services, load_yaml, slugify
4from .github import (
5 AI_BOT_AUTHORS,
6 commit_has_bot,
7 fetch_repo,
8 gh_get,
9 parse_github_field,
10 repo_age_days,
11 repo_has_license,
12 repo_is_archived,
13 repo_is_fork,
14 repo_pushed_days_ago,
15 repo_status,
16)
17from .http import DEFAULT_TIMEOUT, DEFAULT_USER_AGENT, check_url, make_session
188from .term import make_colors, setup_logging
199
10try:
11 from .data import DATA_PATH, PROJECT_ROOT, iter_services, load_yaml, slugify
12 from .github import (
13 AI_BOT_AUTHORS,
14 commit_has_bot,
15 fetch_repo,
16 gh_get,
17 parse_github_field,
18 repo_age_days,
19 repo_has_license,
20 repo_is_archived,
21 repo_is_fork,
22 repo_pushed_days_ago,
23 repo_status,
24 )
25 from .http import DEFAULT_TIMEOUT, DEFAULT_USER_AGENT, check_url, make_session
26except ImportError:
27 pass
28
2029__all__ = [
2130 "AI_BOT_AUTHORS",
2231 "DATA_PATH",
lib/utils/term.py +48 −4
@@ -4,21 +4,65 @@ import logging
44import os
55import sys
66
7_COLOR_CODES = {"red": 31, "green": 32, "yellow": 33, "cyan": 36, "bold": 1, "dim": 2}
7_COLOR_CODES = {"red": 31, "green": 32, "yellow": 33, "blue": 34, "cyan": 36, "bold": 1, "dim": 2}
8
9_LEVEL_COLORS = {
10 "DEBUG": _COLOR_CODES["dim"],
11 "INFO": _COLOR_CODES["cyan"],
12 "WARNING": _COLOR_CODES["yellow"],
13 "ERROR": _COLOR_CODES["red"],
14 "CRITICAL": _COLOR_CODES["red"],
15}
16
17
18def _color_enabled(stream=None):
19 """Decide whether ANSI colors should be emitted (respects NO_COLOR, enables in CI)."""
20 if os.environ.get("NO_COLOR"):
21 return False
22 if os.environ.get("FORCE_COLOR") or os.environ.get("GITHUB_ACTIONS") or os.environ.get("CI"):
23 return True
24 stream = stream or sys.stderr
25 return bool(getattr(stream, "isatty", lambda: False)())
26
27
28def _paint(text, code):
29 return f"\033[{code}m{text}\033[0m"
30
31
32class _ColorFormatter(logging.Formatter):
33 """Renders records as `LEVEL [file] message`, colored by level when enabled."""
34
35 def __init__(self, color):
36 super().__init__()
37 self.color = color
38
39 def format(self, record):
40 level = f"{record.levelname:<7}"
41 location = f"[{record.filename}]"
42 message = record.getMessage()
43 if self.color:
44 level = _paint(level, _LEVEL_COLORS.get(record.levelname, 0))
45 location = _paint(location, _COLOR_CODES["dim"])
46 text = f"{level} {location} {message}"
47 if record.exc_info:
48 text += "\n" + self.formatException(record.exc_info)
49 return text
850
951
1052def setup_logging(level="INFO"):
53 handler = logging.StreamHandler(sys.stderr)
54 handler.setFormatter(_ColorFormatter(_color_enabled()))
1155 logging.basicConfig(
1256 level=getattr(logging, str(level).upper(), logging.INFO),
13 format="%(levelname)s [%(filename)s] %(message)s",
14 stream=sys.stderr,
57 handlers=[handler],
58 force=True,
1559 )
1660
1761
1862def make_colors(enabled=None):
1963 """Return {name: callable(str) -> str}; no-ops when colors disabled."""
2064 if enabled is None:
21 enabled = sys.stderr.isatty() and not os.environ.get("NO_COLOR")
65 enabled = _color_enabled()
2266 if not enabled:
2367 return {name: (lambda s: s) for name in _COLOR_CODES}
2468 return {name: (lambda s, c=code: f"\033[{c}m{s}\033[0m") for name, code in _COLOR_CODES.items()}
lib/validate-awesome-privacy.py +17 −15
@@ -1,10 +1,17 @@
11import json
2import logging
23import os
34import sys
45
56import yaml
67from jsonschema import Draft7Validator
78
9sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
10import utils
11
12utils.setup_logging()
13logger = logging.getLogger(__name__)
14
815# Paths (relative to project root)
916PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
1017DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml")
@@ -18,13 +25,6 @@ EXIT_RUNTIME_ERROR = 2
1825
1926MAX_ERRORS = 20
2027
21# ANSI color helpers (disabled when NO_COLOR is set or stderr is not a TTY)
22_use_color = sys.stderr.isatty() and not os.environ.get("NO_COLOR")
23red = (lambda s: f"\033[31m{s}\033[0m") if _use_color else (lambda s: s)
24green = (lambda s: f"\033[32m{s}\033[0m") if _use_color else (lambda s: s)
25yellow = (lambda s: f"\033[33m{s}\033[0m") if _use_color else (lambda s: s)
26dim = (lambda s: f"\033[2m{s}\033[0m") if _use_color else (lambda s: s)
27
2828
2929def _clean(v):
3030 """Stringify a value for inline display: neutralise backticks, collapse newlines."""
@@ -139,12 +139,12 @@ def load_yaml(path):
139139 with open(path, "r") as f:
140140 return yaml.safe_load(f)
141141 except FileNotFoundError:
142 print(red(f"File not found: {path}"), file=sys.stderr)
142 logger.error("File not found: %s", path)
143143 sys.exit(EXIT_RUNTIME_ERROR)
144144 except yaml.YAMLError as e:
145145 msg = format_yaml_error(e)
146146 write_errors_file([msg])
147 print(red(f"Failed to parse YAML: {msg}"), file=sys.stderr)
147 logger.error("Failed to parse YAML: %s", msg)
148148 sys.exit(EXIT_RUNTIME_ERROR)
149149
150150
@@ -153,10 +153,10 @@ def load_schema(path):
153153 with open(path, "r") as f:
154154 return json.load(f)
155155 except FileNotFoundError:
156 print(red(f"File not found: {path}"), file=sys.stderr)
156 logger.error("File not found: %s", path)
157157 sys.exit(EXIT_RUNTIME_ERROR)
158158 except json.JSONDecodeError as e:
159 print(red(f"Failed to parse JSON schema: {e}"), file=sys.stderr)
159 logger.error("Failed to parse JSON schema: %s", e)
160160 sys.exit(EXIT_RUNTIME_ERROR)
161161
162162
@@ -171,6 +171,7 @@ def validate(data, schema):
171171
172172
173173def main():
174 logger.info("Validating awesome-privacy.yml against schema")
174175 data = load_yaml(DATA_PATH)
175176 schema = load_schema(SCHEMA_PATH)
176177 errors = validate(data, schema)
@@ -179,10 +180,10 @@ def main():
179180 write_errors_file(errors)
180181 shown = errors[:MAX_ERRORS]
181182 for msg in shown:
182 print(red("ERROR") + " " + msg, file=sys.stderr)
183 logger.error(msg)
183184 if len(errors) > MAX_ERRORS:
184 print(dim(f"...and {len(errors) - MAX_ERRORS} more"), file=sys.stderr)
185 print(red(f"Validation failed: {len(errors)} error(s)"), file=sys.stderr)
185 logger.warning("...and %d more", len(errors) - MAX_ERRORS)
186 logger.error("Validation failed: %d error(s)", len(errors))
186187 sys.exit(EXIT_VALIDATION_ERRORS)
187188
188189 # Gather stats
@@ -195,7 +196,8 @@ def main():
195196 for s in c.get("sections", [])
196197 )
197198 clear_errors_file()
198 print(green(f"Valid! {num_categories} categories, {num_sections} sections, {num_services} services"))
199 logger.info("Valid! %d categories, %d sections, %d services",
200 num_categories, num_sections, num_services)
199201 sys.exit(EXIT_VALID)
200202
201203