Commit 3e0466da7b
Unsigned
Layout: unified · split
lib/awesome-privacy-readme-gen.py +5 −1
| @@ -5,13 +5,17 @@ formats into markdown, and inserts into README.md | |||
| 5 | 5 | ||
| 6 | import os | 6 | import os |
| 7 | import re | 7 | import re |
| 8 | import sys | ||
| 8 | import yaml | 9 | import yaml |
| 9 | import logging | 10 | import logging |
| 10 | from urllib.parse import urlparse | 11 | from urllib.parse import urlparse |
| 11 | 12 | ||
| 13 | sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | ||
| 14 | import utils | ||
| 15 | |||
| 12 | # Configure Logging | 16 | # Configure Logging |
| 13 | LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper() | 17 | LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper() |
| 14 | logging.basicConfig(level=LOG_LEVEL) | 18 | utils.setup_logging(LOG_LEVEL) |
| 15 | logger = logging.getLogger(__name__) | 19 | logger = logging.getLogger(__name__) |
| 16 | 20 | ||
| 17 | # Determine the project root based on the script's location | 21 | # Determine the project root based on the script's location |
lib/checks/check-additions.py +35 −39
| @@ -7,11 +7,11 @@ import sys | |||
| 7 | 7 | ||
| 8 | import yaml | 8 | import yaml |
| 9 | 9 | ||
| 10 | logging.basicConfig( | 10 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 11 | level=logging.INFO, | 11 | import utils |
| 12 | format="%(levelname)s [%(filename)s] %(message)s", | 12 | |
| 13 | stream=sys.stderr, | 13 | utils.setup_logging() |
| 14 | ) | 14 | logger = logging.getLogger(__name__) |
| 15 | 15 | ||
| 16 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | 16 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 17 | DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml") | 17 | DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml") |
| @@ -278,51 +278,47 @@ def main(): | |||
| 278 | critical = False | 278 | critical = False |
| 279 | try: | 279 | try: |
| 280 | if os.environ.get("SCHEMA_OUTCOME") == "failure": | 280 | if os.environ.get("SCHEMA_OUTCOME") == "failure": |
| 281 | logger.warning("Schema validation failed upstream, surfacing schema errors") | ||
| 281 | findings.extend(schema_findings()) | 282 | findings.extend(schema_findings()) |
| 282 | 283 | ||
| 283 | diff = load_json(DIFF_PATH) | 284 | diff = load_json(DIFF_PATH) |
| 284 | head = load_yaml_data(DATA_PATH) | 285 | head = load_yaml_data(DATA_PATH) |
| 285 | 286 | ||
| 286 | if diff: | 287 | if not diff: |
| 287 | finding = check_single_entry(diff) | 288 | logger.info("No diff at %s, nothing to validate", DIFF_PATH) |
| 288 | if finding: | 289 | else: |
| 289 | findings.append(finding) | 290 | added = diff.get("services", {}).get("added", []) |
| 290 | 291 | modified = diff.get("services", {}).get("modified", []) | |
| 291 | finding = check_required_fields(diff, head) | 292 | logger.info("Validating additions: %d added, %d modified service(s)", |
| 292 | if finding: | 293 | len(added), len(modified)) |
| 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) | ||
| 303 | 294 | ||
| 304 | name_index = build_name_index(head, diff) | 295 | name_index = build_name_index(head, diff) |
| 305 | url_index = build_url_index(head, diff) | 296 | url_index = build_url_index(head, diff) |
| 306 | 297 | ||
| 307 | finding = check_duplicate_name(diff, name_index) | 298 | checks = [ |
| 308 | if finding: | 299 | ("single-entry", check_single_entry(diff), False), |
| 309 | findings.append(finding) | 300 | ("required-fields", check_required_fields(diff, head), True), |
| 310 | 301 | ("position", check_position(diff, head), False), | |
| 311 | finding = check_duplicate_url(diff, url_index) | 302 | ("open-source", check_open_source(diff), False), |
| 312 | if finding: | 303 | ("duplicate-name", check_duplicate_name(diff, name_index), False), |
| 313 | findings.append(finding) | 304 | ("duplicate-url", check_duplicate_url(diff, url_index), False), |
| 314 | 305 | ("description-length", check_description_length(diff), False), | |
| 315 | finding = check_description_length(diff) | 306 | ("opensource-repo", check_opensource_github(diff), False), |
| 316 | if finding: | 307 | ] |
| 317 | findings.append(finding) | 308 | for name, finding, is_error in checks: |
| 318 | 309 | if not finding: | |
| 319 | finding = check_opensource_github(diff) | 310 | continue |
| 320 | if finding: | 311 | logger.info("flagged: %s", name) |
| 321 | findings.append(finding) | 312 | if is_error: |
| 313 | findings.append({"msg": finding, "level": "error"}) | ||
| 314 | critical = True | ||
| 315 | else: | ||
| 316 | findings.append(finding) | ||
| 322 | except Exception as exc: | 317 | 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) |
| 324 | 319 | ||
| 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) | ||
| 326 | with open(FINDINGS_PATH, "w") as f: | 322 | with open(FINDINGS_PATH, "w") as f: |
| 327 | json.dump(findings, f) | 323 | json.dump(findings, f) |
| 328 | sys.exit(1 if critical else 0) | 324 | sys.exit(1 if critical else 0) |
lib/checks/check-pr-meta.py +11 −8
| @@ -7,11 +7,11 @@ import re | |||
| 7 | import subprocess | 7 | import subprocess |
| 8 | import sys | 8 | import sys |
| 9 | 9 | ||
| 10 | logging.basicConfig( | 10 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 11 | level=logging.INFO, | 11 | import utils |
| 12 | format="%(levelname)s [%(filename)s] %(message)s", | 12 | |
| 13 | stream=sys.stderr, | 13 | utils.setup_logging() |
| 14 | ) | 14 | logger = logging.getLogger(__name__) |
| 15 | 15 | ||
| 16 | FINDINGS_PATH = "/tmp/findings-compliance.json" | 16 | FINDINGS_PATH = "/tmp/findings-compliance.json" |
| 17 | 17 | ||
| @@ -135,7 +135,7 @@ def check_bot_coauthors(base_ref): | |||
| 135 | if _BOT_AUTHOR_RE.search(result.stdout): | 135 | if _BOT_AUTHOR_RE.search(result.stdout): |
| 136 | return BOT_MSG | 136 | return BOT_MSG |
| 137 | except Exception as exc: | 137 | except Exception as exc: |
| 138 | logging.warning("check_bot_coauthors error: %s", exc) | 138 | logger.warning("check_bot_coauthors error: %s", exc) |
| 139 | return None | 139 | return None |
| 140 | 140 | ||
| 141 | 141 | ||
| @@ -162,6 +162,8 @@ def main(): | |||
| 162 | readme_failed = os.environ.get("README_FAILED", "false") | 162 | readme_failed = os.environ.get("README_FAILED", "false") |
| 163 | base_ref = os.environ.get("BASE_REF", "") | 163 | base_ref = os.environ.get("BASE_REF", "") |
| 164 | 164 | ||
| 165 | logger.info("Checking PR metadata: title, draft, template, checkboxes, type, bot authors") | ||
| 166 | |||
| 165 | finding = check_bot_coauthors(base_ref) | 167 | finding = check_bot_coauthors(base_ref) |
| 166 | if finding: | 168 | if finding: |
| 167 | findings.append(finding) | 169 | findings.append(finding) |
| @@ -195,9 +197,10 @@ def main(): | |||
| 195 | if finding: | 197 | if finding: |
| 196 | findings.append({"msg": finding, "level": "error"}) | 198 | findings.append({"msg": finding, "level": "error"}) |
| 197 | except Exception as exc: | 199 | 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) |
| 199 | 201 | ||
| 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) | ||
| 201 | write_findings(findings) | 204 | write_findings(findings) |
| 202 | sys.exit(1 if critical else 0) | 205 | sys.exit(1 if critical else 0) |
| 203 | 206 | ||
lib/checks/check-project.py +13 −15
| @@ -12,11 +12,8 @@ import yaml | |||
| 12 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | 12 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 13 | import utils | 13 | import utils |
| 14 | 14 | ||
| 15 | logging.basicConfig( | 15 | utils.setup_logging() |
| 16 | level=logging.INFO, | 16 | logger = logging.getLogger(__name__) |
| 17 | format="%(levelname)s [%(filename)s] %(message)s", | ||
| 18 | stream=sys.stderr, | ||
| 19 | ) | ||
| 20 | 17 | ||
| 21 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | 18 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 22 | DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml") | 19 | DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml") |
| @@ -112,9 +109,9 @@ def check_url(url): | |||
| 112 | """Return True if the URL is reachable. Transport errors are treated as reachable.""" | 109 | """Return True if the URL is reachable. Transport errors are treated as reachable.""" |
| 113 | ok, status = utils.check_url(url, SESSION, TIMEOUT) | 110 | ok, status = utils.check_url(url, SESSION, TIMEOUT) |
| 114 | if not ok: | 111 | 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) |
| 116 | elif status is None: | 113 | elif status is None: |
| 117 | logging.warning("URL check error for %s (unreachable)", url) | 114 | logger.warning("URL check error for %s (unreachable)", url) |
| 118 | return ok | 115 | return ok |
| 119 | 116 | ||
| 120 | 117 | ||
| @@ -206,7 +203,7 @@ def check_security_alerts(owner, repo, token): | |||
| 206 | def check_spam_prs(pr_user, token): | 203 | def check_spam_prs(pr_user, token): |
| 207 | """Return list of spam findings based on recent PR activity.""" | 204 | """Return list of spam findings based on recent PR activity.""" |
| 208 | if not pr_user or not token: | 205 | 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") |
| 210 | return [] | 207 | return [] |
| 211 | try: | 208 | try: |
| 212 | since = (datetime.now(timezone.utc) - timedelta(days=SPAM_WINDOW_DAYS)).strftime("%Y-%m-%d") | 209 | 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): | |||
| 216 | if not data: | 213 | if not data: |
| 217 | return [] | 214 | return [] |
| 218 | items = data.get("items", []) | 215 | 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)", |
| 220 | data.get("total_count", 0), pr_user, len(items)) | 217 | data.get("total_count", 0), pr_user, len(items)) |
| 221 | this_repo = os.environ.get("GITHUB_REPOSITORY", "Lissy93/awesome-privacy").lower() | 218 | this_repo = os.environ.get("GITHUB_REPOSITORY", "Lissy93/awesome-privacy").lower() |
| 222 | awesome_count = 0 | 219 | awesome_count = 0 |
| @@ -231,7 +228,7 @@ def check_spam_prs(pr_user, token): | |||
| 231 | repo_name = repo_url.rstrip("/").split("/")[-1].lower() | 228 | repo_name = repo_url.rstrip("/").split("/")[-1].lower() |
| 232 | if repo_name.startswith("awesome-"): | 229 | if repo_name.startswith("awesome-"): |
| 233 | awesome_count += 1 | 230 | 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", |
| 235 | awesome_count, len(distinct_repos)) | 232 | awesome_count, len(distinct_repos)) |
| 236 | findings = [] | 233 | findings = [] |
| 237 | if awesome_count >= SPAM_AWESOME_THRESHOLD: | 234 | if awesome_count >= SPAM_AWESOME_THRESHOLD: |
| @@ -240,7 +237,7 @@ def check_spam_prs(pr_user, token): | |||
| 240 | findings.append(SPAM_MANY_MSG) | 237 | findings.append(SPAM_MANY_MSG) |
| 241 | return findings | 238 | return findings |
| 242 | except Exception as exc: | 239 | 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) |
| 244 | return [] | 241 | return [] |
| 245 | 242 | ||
| 246 | 243 | ||
| @@ -389,11 +386,12 @@ def main(): | |||
| 389 | try: | 386 | try: |
| 390 | pr_user = os.environ.get("PR_USER", "") | 387 | pr_user = os.environ.get("PR_USER", "") |
| 391 | token = os.environ.get("GITHUB_TOKEN", "") | 388 | 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") | ||
| 393 | 391 | ||
| 394 | diff = load_diff(DIFF_PATH) | 392 | diff = load_diff(DIFF_PATH) |
| 395 | if not diff: | 393 | 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) |
| 397 | with open(FINDINGS_PATH, "w") as f: | 395 | with open(FINDINGS_PATH, "w") as f: |
| 398 | json.dump(findings, f) | 396 | json.dump(findings, f) |
| 399 | sys.exit(0) | 397 | sys.exit(0) |
| @@ -421,9 +419,9 @@ def main(): | |||
| 421 | 419 | ||
| 422 | findings.extend(check_repo_signals(diff, pr_user, token, pr_body)) | 420 | findings.extend(check_repo_signals(diff, pr_user, token, pr_body)) |
| 423 | except Exception as exc: | 421 | 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) |
| 425 | 423 | ||
| 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) |
| 427 | with open(FINDINGS_PATH, "w") as f: | 425 | with open(FINDINGS_PATH, "w") as f: |
| 428 | json.dump(findings, f) | 426 | json.dump(findings, f) |
| 429 | sys.exit(0) | 427 | 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 | |||
| 4 | """ | 4 | """ |
| 5 | 5 | ||
| 6 | import argparse | 6 | import argparse |
| 7 | import logging | ||
| 7 | import os | 8 | import os |
| 8 | import re | 9 | import re |
| 9 | import subprocess | 10 | import subprocess |
| 10 | import sys | 11 | import sys |
| 11 | 12 | ||
| 13 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | ||
| 14 | import utils | ||
| 15 | |||
| 16 | utils.setup_logging() | ||
| 17 | logger = logging.getLogger(__name__) | ||
| 18 | |||
| 12 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | 19 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 13 | README_PATH = ".github/README.md" | 20 | README_PATH = ".github/README.md" |
| 14 | README_ABS = os.path.join(PROJECT_ROOT, README_PATH) | 21 | README_ABS = os.path.join(PROJECT_ROOT, README_PATH) |
| @@ -18,11 +25,6 @@ EXIT_PASS = 0 | |||
| 18 | EXIT_FAIL = 1 | 25 | EXIT_FAIL = 1 |
| 19 | EXIT_RUNTIME_ERROR = 2 | 26 | EXIT_RUNTIME_ERROR = 2 |
| 20 | 27 | ||
| 21 | # ANSI color helpers | ||
| 22 | _use_color = sys.stderr.isatty() and not os.environ.get("NO_COLOR") | ||
| 23 | red = (lambda s: f"\033[31m{s}\033[0m") if _use_color else (lambda s: s) | ||
| 24 | green = (lambda s: f"\033[32m{s}\033[0m") if _use_color else (lambda s: s) | ||
| 25 | |||
| 26 | 28 | ||
| 27 | def get_changed_files(base_ref): | 29 | def get_changed_files(base_ref): |
| 28 | result = subprocess.run( | 30 | result = subprocess.run( |
| @@ -77,27 +79,30 @@ def main(): | |||
| 77 | parser.add_argument("--base-ref", required=True, help="Base git ref to diff against") | 79 | parser.add_argument("--base-ref", required=True, help="Base git ref to diff against") |
| 78 | args = parser.parse_args() | 80 | args = parser.parse_args() |
| 79 | 81 | ||
| 82 | logger.info("Checking README for direct edits to the generated section") | ||
| 83 | |||
| 80 | # Skip if README wasn't changed | 84 | # Skip if README wasn't changed |
| 81 | changed_files = get_changed_files(args.base_ref) | 85 | changed_files = get_changed_files(args.base_ref) |
| 82 | if README_PATH not in changed_files: | 86 | if README_PATH not in changed_files: |
| 83 | print(green("README not modified, skipping.")) | 87 | logger.info("README not modified, skipping") |
| 84 | sys.exit(EXIT_PASS) | 88 | sys.exit(EXIT_PASS) |
| 85 | 89 | ||
| 86 | # Find marker lines | 90 | # Find marker lines |
| 87 | start_line, end_line = get_marker_lines() | 91 | start_line, end_line = get_marker_lines() |
| 88 | if start_line is None or end_line is None: | 92 | 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") |
| 90 | sys.exit(EXIT_PASS) | 94 | sys.exit(EXIT_PASS) |
| 91 | 95 | ||
| 92 | # Check if any changed lines fall within the generated section | 96 | # Check if any changed lines fall within the generated section |
| 93 | changed_lines = get_changed_line_numbers(args.base_ref) | 97 | 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) | ||
| 94 | for line_num in changed_lines: | 100 | for line_num in changed_lines: |
| 95 | if start_line <= line_num <= end_line: | 101 | 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) | 102 | logger.error("Edit to generated section at line %d: edit awesome-privacy.yml instead", line_num) |
| 97 | print(red("Edit awesome-privacy.yml instead and the README will be regenerated."), file=sys.stderr) | ||
| 98 | sys.exit(EXIT_FAIL) | 103 | sys.exit(EXIT_FAIL) |
| 99 | 104 | ||
| 100 | print(green("README changes are outside the generated section, OK.")) | 105 | logger.info("README edits are outside the generated section, OK") |
| 101 | sys.exit(EXIT_PASS) | 106 | sys.exit(EXIT_PASS) |
| 102 | 107 | ||
| 103 | 108 | ||
lib/checks/check-review-ready.py +14
| @@ -12,7 +12,15 @@ Writes: | |||
| 12 | """ | 12 | """ |
| 13 | 13 | ||
| 14 | import json | 14 | import json |
| 15 | import logging | ||
| 15 | import os | 16 | import os |
| 17 | import sys | ||
| 18 | |||
| 19 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | ||
| 20 | import utils | ||
| 21 | |||
| 22 | utils.setup_logging() | ||
| 23 | logger = logging.getLogger(__name__) | ||
| 16 | 24 | ||
| 17 | WORK_DIR = "pr-meta" | 25 | WORK_DIR = "pr-meta" |
| 18 | MAINTAINER = "Lissy93" | 26 | MAINTAINER = "Lissy93" |
| @@ -67,22 +75,28 @@ def write_action(action): | |||
| 67 | 75 | ||
| 68 | 76 | ||
| 69 | def main(): | 77 | def main(): |
| 78 | logger.info("Checking whether the PR is ready for maintainer review") | ||
| 70 | if already_notified(): | 79 | if already_notified(): |
| 80 | logger.info("Maintainer already notified, action=skip") | ||
| 71 | write_action("skip") | 81 | write_action("skip") |
| 72 | return | 82 | return |
| 73 | 83 | ||
| 74 | reviews = read_json("reviews.json") | 84 | reviews = read_json("reviews.json") |
| 75 | approvals = count_external_approvals(reviews) | 85 | approvals = count_external_approvals(reviews) |
| 86 | logger.info("%d external approval(s), need %d", approvals, REQUIRED_APPROVALS) | ||
| 76 | 87 | ||
| 77 | if approvals < REQUIRED_APPROVALS: | 88 | if approvals < REQUIRED_APPROVALS: |
| 89 | logger.info("Not enough approvals, action=skip") | ||
| 78 | write_action("skip") | 90 | write_action("skip") |
| 79 | return | 91 | return |
| 80 | 92 | ||
| 81 | check_runs = read_json("check-runs.json") | 93 | check_runs = read_json("check-runs.json") |
| 82 | if not all_checks_passing(check_runs): | 94 | if not all_checks_passing(check_runs): |
| 95 | logger.info("Not all %d check run(s) passing, action=skip", len(check_runs)) | ||
| 83 | write_action("skip") | 96 | write_action("skip") |
| 84 | return | 97 | return |
| 85 | 98 | ||
| 99 | logger.info("Approvals met and all checks passing, action=notify") | ||
| 86 | write_action("notify") | 100 | write_action("notify") |
| 87 | 101 | ||
| 88 | 102 | ||
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. | |||
| 4 | 4 | ||
| 5 | import argparse | 5 | import argparse |
| 6 | import json | 6 | import json |
| 7 | import logging | ||
| 7 | import os | 8 | import os |
| 8 | import sys | 9 | import sys |
| 9 | 10 | ||
| 10 | import yaml | 11 | import yaml |
| 11 | 12 | ||
| 12 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | 13 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 14 | import utils | ||
| 13 | from yaml_diff import build_index, diff_index, load_yaml_at_ref | 15 | from yaml_diff import build_index, diff_index, load_yaml_at_ref |
| 14 | 16 | ||
| 17 | utils.setup_logging() | ||
| 18 | logger = logging.getLogger(__name__) | ||
| 19 | |||
| 15 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | 20 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 16 | DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml") | 21 | DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml") |
| 17 | DIFF_OUTPUT_PATH = "/tmp/pr-diff.json" | 22 | DIFF_OUTPUT_PATH = "/tmp/pr-diff.json" |
| @@ -21,17 +26,12 @@ EXIT_PASS = 0 | |||
| 21 | EXIT_RULE_VIOLATION = 1 | 26 | EXIT_RULE_VIOLATION = 1 |
| 22 | EXIT_RUNTIME_ERROR = 2 | 27 | EXIT_RUNTIME_ERROR = 2 |
| 23 | 28 | ||
| 24 | _use_color = sys.stderr.isatty() and not os.environ.get("NO_COLOR") | ||
| 25 | red = (lambda s: f"\033[31m{s}\033[0m") if _use_color else (lambda s: s) | ||
| 26 | green = (lambda s: f"\033[32m{s}\033[0m") if _use_color else (lambda s: s) | ||
| 27 | yellow = (lambda s: f"\033[33m{s}\033[0m") if _use_color else (lambda s: s) | ||
| 28 | |||
| 29 | 29 | ||
| 30 | def load_base_yaml(base_ref): | 30 | def load_base_yaml(base_ref): |
| 31 | """Load the YAML from the base ref using git show.""" | 31 | """Load the YAML from the base ref using git show.""" |
| 32 | data = load_yaml_at_ref(base_ref, PROJECT_ROOT) | 32 | data = load_yaml_at_ref(base_ref, PROJECT_ROOT) |
| 33 | if data is None: | 33 | 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") |
| 35 | return {"categories": []} | 35 | return {"categories": []} |
| 36 | return data | 36 | return data |
| 37 | 37 | ||
| @@ -42,7 +42,7 @@ def load_head_yaml(): | |||
| 42 | with open(DATA_PATH) as f: | 42 | with open(DATA_PATH) as f: |
| 43 | return yaml.safe_load(f) | 43 | return yaml.safe_load(f) |
| 44 | except (FileNotFoundError, yaml.YAMLError) as e: | 44 | 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) |
| 46 | sys.exit(EXIT_RUNTIME_ERROR) | 46 | sys.exit(EXIT_RUNTIME_ERROR) |
| 47 | 47 | ||
| 48 | 48 | ||
| @@ -125,6 +125,7 @@ def main(): | |||
| 125 | parser.add_argument("--base-ref", required=True) | 125 | parser.add_argument("--base-ref", required=True) |
| 126 | args = parser.parse_args() | 126 | args = parser.parse_args() |
| 127 | 127 | ||
| 128 | logger.info("Diffing awesome-privacy.yml against base ref %s", args.base_ref) | ||
| 128 | base = load_base_yaml(args.base_ref) | 129 | base = load_base_yaml(args.base_ref) |
| 129 | head = load_head_yaml() | 130 | head = load_head_yaml() |
| 130 | 131 | ||
| @@ -176,24 +177,26 @@ def main(): | |||
| 176 | write_github_output("has_service_changes", str(bool(added or removed or modified)).lower()) | 177 | write_github_output("has_service_changes", str(bool(added or removed or modified)).lower()) |
| 177 | write_diff_summary(diff_result) | 178 | write_diff_summary(diff_result) |
| 178 | 179 | ||
| 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 | |||
| 179 | added_count = len(added) | 183 | added_count = len(added) |
| 180 | if added_count > 1: | 184 | 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) |
| 182 | sys.exit(EXIT_RULE_VIOLATION) | 186 | sys.exit(EXIT_RULE_VIOLATION) |
| 183 | added_sections = [s for s in sections if s["change_type"] == "added_section"] | 187 | added_sections = [s for s in sections if s["change_type"] == "added_section"] |
| 184 | if added_count == 0 and len(added_sections) > 1: | 188 | 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)) |
| 186 | sys.exit(EXIT_RULE_VIOLATION) | 190 | sys.exit(EXIT_RULE_VIOLATION) |
| 187 | 191 | ||
| 188 | if duplicates: | 192 | if duplicates: |
| 189 | names = ", ".join(f"{d[2]} (in {d[0]} → {d[1]})" for d in duplicates) | 193 | 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) |
| 191 | sys.exit(EXIT_RULE_VIOLATION) | 195 | sys.exit(EXIT_RULE_VIOLATION) |
| 192 | 196 | ||
| 193 | total = len(added) + len(removed) + len(modified) | 197 | total = len(added) + len(removed) + len(modified) |
| 194 | print(green(f"Single-entry rule passed. {total} service " | 198 | logger.info("Single-entry rule passed: %d service change(s) (%d added), %d section, %d category change(s)", |
| 195 | f"({added_count} added), {len(sections)} section, " | 199 | total, added_count, len(sections), len(categories)) |
| 196 | f"{len(categories)} category change(s).")) | ||
| 197 | sys.exit(EXIT_PASS) | 200 | sys.exit(EXIT_PASS) |
| 198 | 201 | ||
| 199 | 202 | ||
lib/checks/detect-changes.py +10 −3
| @@ -4,10 +4,17 @@ Sets GitHub Actions output: yaml_changed. | |||
| 4 | """ | 4 | """ |
| 5 | 5 | ||
| 6 | import argparse | 6 | import argparse |
| 7 | import logging | ||
| 7 | import os | 8 | import os |
| 8 | import subprocess | 9 | import subprocess |
| 9 | import sys | 10 | import sys |
| 10 | 11 | ||
| 12 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | ||
| 13 | import utils | ||
| 14 | |||
| 15 | utils.setup_logging() | ||
| 16 | logger = logging.getLogger(__name__) | ||
| 17 | |||
| 11 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | 18 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 12 | 19 | ||
| 13 | YAML_FILE = "awesome-privacy.yml" | 20 | YAML_FILE = "awesome-privacy.yml" |
| @@ -33,13 +40,13 @@ def main(): | |||
| 33 | 40 | ||
| 34 | changed_files = [f for f in result.stdout.strip().splitlines() if f] | 41 | changed_files = [f for f in result.stdout.strip().splitlines() if f] |
| 35 | 42 | ||
| 36 | print("Changed files:") | 43 | logger.info("Detected %d changed file(s) since %s", len(changed_files), args.base_ref) |
| 37 | for f in changed_files: | 44 | for f in changed_files: |
| 38 | print(f" {f}") | 45 | logger.debug(" %s", f) |
| 39 | 46 | ||
| 40 | yaml_changed = YAML_FILE in changed_files | 47 | yaml_changed = YAML_FILE in changed_files |
| 41 | write_github_output("yaml_changed", str(yaml_changed).lower()) | 48 | 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) |
| 43 | 50 | ||
| 44 | 51 | ||
| 45 | if __name__ == "__main__": | 52 | if __name__ == "__main__": |
lib/checks/format-comment.py +11 −7
| @@ -6,11 +6,11 @@ import os | |||
| 6 | import sys | 6 | import sys |
| 7 | from datetime import datetime, timezone | 7 | from datetime import datetime, timezone |
| 8 | 8 | ||
| 9 | logging.basicConfig( | 9 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 10 | level=logging.INFO, | 10 | import utils |
| 11 | format="%(levelname)s [%(filename)s] %(message)s", | 11 | |
| 12 | stream=sys.stderr, | 12 | utils.setup_logging() |
| 13 | ) | 13 | logger = logging.getLogger(__name__) |
| 14 | 14 | ||
| 15 | ARTIFACTS_DIR = "/tmp/artifacts" | 15 | ARTIFACTS_DIR = "/tmp/artifacts" |
| 16 | OUTPUT_DIR = "/tmp/pr-meta" | 16 | OUTPUT_DIR = "/tmp/pr-meta" |
| @@ -220,8 +220,10 @@ def main(): | |||
| 220 | with open(os.path.join(OUTPUT_DIR, "run-id.txt"), "w") as f: | 220 | with open(os.path.join(OUTPUT_DIR, "run-id.txt"), "w") as f: |
| 221 | f.write(run_id) | 221 | f.write(run_id) |
| 222 | 222 | ||
| 223 | logger.info("Aggregating findings from all check jobs in %s", ARTIFACTS_DIR) | ||
| 223 | errors, warnings = collect_findings() | 224 | errors, warnings = collect_findings() |
| 224 | all_findings = errors + warnings | 225 | all_findings = errors + warnings |
| 226 | logger.info("Collected %d error(s) and %d warning(s)", len(errors), len(warnings)) | ||
| 225 | with open(os.path.join(OUTPUT_DIR, "findings-count.txt"), "w") as f: | 227 | with open(os.path.join(OUTPUT_DIR, "findings-count.txt"), "w") as f: |
| 226 | f.write(str(len(all_findings))) | 228 | f.write(str(len(all_findings))) |
| 227 | with open(os.path.join(OUTPUT_DIR, "error-count.txt"), "w") as f: | 229 | with open(os.path.join(OUTPUT_DIR, "error-count.txt"), "w") as f: |
| @@ -233,10 +235,12 @@ def main(): | |||
| 233 | repo_stats) | 235 | repo_stats) |
| 234 | 236 | ||
| 235 | comment = format_comment(all_findings, user, changes_summary, run_id, repo_stats) | 237 | 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: | ||
| 237 | f.write(comment) | 240 | f.write(comment) |
| 241 | logger.info("Wrote PR comment to %s", comment_path) | ||
| 238 | except Exception as exc: | 242 | 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) |
| 240 | 244 | ||
| 241 | sys.exit(0) | 245 | sys.exit(0) |
| 242 | 246 | ||
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. | |||
| 20 | 20 | ||
| 21 | import argparse | 21 | import argparse |
| 22 | import json | 22 | import json |
| 23 | import logging | ||
| 23 | import os | 24 | import os |
| 24 | import sys | 25 | import sys |
| 25 | from datetime import datetime, timezone | 26 | from datetime import datetime, timezone |
| @@ -28,6 +29,9 @@ from urllib.parse import urlparse | |||
| 28 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | 29 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 29 | import utils | 30 | import utils |
| 30 | 31 | ||
| 32 | utils.setup_logging() | ||
| 33 | logger = logging.getLogger(__name__) | ||
| 34 | |||
| 31 | DIFF_PATH = "/tmp/pr-diff.json" | 35 | DIFF_PATH = "/tmp/pr-diff.json" |
| 32 | OUTPUT_PATH = "/tmp/repo-stats.md" | 36 | OUTPUT_PATH = "/tmp/repo-stats.md" |
| 33 | TIMEOUT = 10 | 37 | TIMEOUT = 10 |
| @@ -54,7 +58,7 @@ def _api_get(url, params=None, timeout=TIMEOUT, headers=None): | |||
| 54 | if resp.status_code == 200: | 58 | if resp.status_code == 200: |
| 55 | return resp.json() | 59 | return resp.json() |
| 56 | except Exception as e: | 60 | 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) |
| 58 | return None | 62 | return None |
| 59 | 63 | ||
| 60 | 64 | ||
| @@ -494,7 +498,7 @@ def _resolve_args(argv): | |||
| 494 | if args.repo: | 498 | if args.repo: |
| 495 | owner, repo = utils.parse_github_field(args.repo) | 499 | owner, repo = utils.parse_github_field(args.repo) |
| 496 | if not owner: | 500 | if not owner: |
| 497 | print(f"Invalid repo format: {args.repo}", file=sys.stderr) | 501 | logger.error("Invalid repo format: %s", args.repo) |
| 498 | sys.exit(1) | 502 | sys.exit(1) |
| 499 | result["owner"], result["repo"] = owner, repo | 503 | result["owner"], result["repo"] = owner, repo |
| 500 | return [result] | 504 | return [result] |
| @@ -504,7 +508,7 @@ def _resolve_args(argv): | |||
| 504 | with open(DIFF_PATH) as f: | 508 | with open(DIFF_PATH) as f: |
| 505 | diff = json.load(f) | 509 | diff = json.load(f) |
| 506 | except Exception: | 510 | 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") |
| 508 | sys.exit(0) | 512 | sys.exit(0) |
| 509 | 513 | ||
| 510 | field_map = {"github": "owner", "url": "url", "androidApp": "android", | 514 | field_map = {"github": "owner", "url": "url", "androidApp": "android", |
| @@ -524,9 +528,10 @@ def _resolve_args(argv): | |||
| 524 | services.append(result) | 528 | services.append(result) |
| 525 | 529 | ||
| 526 | if not services: | 530 | if not services: |
| 527 | print("No checkable fields found in diff", file=sys.stderr) | 531 | logger.info("No checkable fields found in diff") |
| 528 | sys.exit(0) | 532 | sys.exit(0) |
| 529 | 533 | ||
| 534 | logger.info("Found %d service(s) with checkable fields in diff", len(services)) | ||
| 530 | return services | 535 | return services |
| 531 | 536 | ||
| 532 | 537 | ||
| @@ -535,19 +540,21 @@ def _build_service_sections(args, token): | |||
| 535 | sections = [] | 540 | sections = [] |
| 536 | 541 | ||
| 537 | if args["owner"] and args["repo"]: | 542 | if args["owner"] and args["repo"]: |
| 543 | logger.info("Fetching repo stats for %s/%s", args["owner"], args["repo"]) | ||
| 538 | data = fetch_all_data(args["owner"], args["repo"], token) | 544 | data = fetch_all_data(args["owner"], args["repo"], token) |
| 539 | if data: | 545 | if data: |
| 540 | sections.append(("Repo Stats", format_markdown(grade_stats(data)))) | 546 | sections.append(("Repo Stats", format_markdown(grade_stats(data)))) |
| 541 | else: | 547 | 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"]) |
| 543 | 549 | ||
| 544 | if args["url"]: | 550 | if args["url"]: |
| 545 | parsed_url = urlparse(args["url"]) | 551 | parsed_url = urlparse(args["url"]) |
| 546 | if parsed_url.hostname and parsed_url.hostname.rstrip(".").endswith("github.com"): | 552 | 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"]) |
| 548 | sections.append(("Website Checks", | 554 | sections.append(("Website Checks", |
| 549 | f"- {ORANGE} **Skipped** web checks, since repo URL was submitted instead of a website")) | 555 | f"- {ORANGE} **Skipped** web checks, since repo URL was submitted instead of a website")) |
| 550 | else: | 556 | else: |
| 557 | logger.info("Fetching website checks for %s", args["url"]) | ||
| 551 | site_data = fetch_website_data(args["url"]) | 558 | site_data = fetch_website_data(args["url"]) |
| 552 | has_sec_txt = check_security_txt(args["url"]) | 559 | has_sec_txt = check_security_txt(args["url"]) |
| 553 | if site_data or has_sec_txt is not None: | 560 | if site_data or has_sec_txt is not None: |
| @@ -555,25 +562,28 @@ def _build_service_sections(args, token): | |||
| 555 | format_markdown(grade_website_stats(site_data, args["url"], has_sec_txt)))) | 562 | format_markdown(grade_website_stats(site_data, args["url"], has_sec_txt)))) |
| 556 | 563 | ||
| 557 | if args["android"]: | 564 | if args["android"]: |
| 565 | logger.info("Fetching Android app info for %s", args["android"]) | ||
| 558 | data = fetch_android_data(args["android"]) | 566 | data = fetch_android_data(args["android"]) |
| 559 | if data: | 567 | if data: |
| 560 | sections.append(("Android App", format_markdown(grade_android_stats(data)))) | 568 | sections.append(("Android App", format_markdown(grade_android_stats(data)))) |
| 561 | else: | 569 | 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"]) |
| 563 | 571 | ||
| 564 | if args["ios"]: | 572 | if args["ios"]: |
| 573 | logger.info("Fetching iOS app info for %s", args["ios"]) | ||
| 565 | data = fetch_ios_data(args["ios"]) | 574 | data = fetch_ios_data(args["ios"]) |
| 566 | if data: | 575 | if data: |
| 567 | sections.append(("iOS App", format_markdown(grade_ios_stats(data)))) | 576 | sections.append(("iOS App", format_markdown(grade_ios_stats(data)))) |
| 568 | else: | 577 | 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"]) |
| 570 | 579 | ||
| 571 | if args["tosdr"]: | 580 | if args["tosdr"]: |
| 581 | logger.info("Fetching ToS;DR privacy policy for %s", args["tosdr"]) | ||
| 572 | data = fetch_tosdr_data(args["tosdr"]) | 582 | data = fetch_tosdr_data(args["tosdr"]) |
| 573 | if data: | 583 | if data: |
| 574 | sections.append(("Privacy Policy", format_markdown(grade_tosdr_stats(data)))) | 584 | sections.append(("Privacy Policy", format_markdown(grade_tosdr_stats(data)))) |
| 575 | else: | 585 | 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"]) |
| 577 | 587 | ||
| 578 | return sections | 588 | return sections |
| 579 | 589 | ||
| @@ -587,6 +597,8 @@ def main(): | |||
| 587 | all_md_parts = [] | 597 | all_md_parts = [] |
| 588 | 598 | ||
| 589 | for svc_args in all_services: | 599 | for svc_args in all_services: |
| 600 | if svc_args.get("name"): | ||
| 601 | logger.info("Looking up submission info for %s", svc_args["name"]) | ||
| 590 | sections = _build_service_sections(svc_args, token) | 602 | sections = _build_service_sections(svc_args, token) |
| 591 | if not sections: | 603 | if not sections: |
| 592 | continue | 604 | continue |
| @@ -609,9 +621,9 @@ def main(): | |||
| 609 | else: | 621 | else: |
| 610 | with open(OUTPUT_PATH, "w") as f: | 622 | with open(OUTPUT_PATH, "w") as f: |
| 611 | f.write(md + "\n") | 623 | f.write(md + "\n") |
| 612 | print(f"Stats written to {OUTPUT_PATH}") | 624 | logger.info("Submission stats written to %s", OUTPUT_PATH) |
| 613 | except Exception as e: | 625 | 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) |
| 615 | 627 | ||
| 616 | sys.exit(0) | 628 | sys.exit(0) |
| 617 | 629 | ||
lib/checks/prepare-comment.py +16
| @@ -10,8 +10,16 @@ Writes: | |||
| 10 | pr-meta/final-comment.md — the body to post or update with | 10 | pr-meta/final-comment.md — the body to post or update with |
| 11 | """ | 11 | """ |
| 12 | 12 | ||
| 13 | import logging | ||
| 13 | import os | 14 | import os |
| 14 | import re | 15 | import re |
| 16 | import sys | ||
| 17 | |||
| 18 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | ||
| 19 | import utils | ||
| 20 | |||
| 21 | utils.setup_logging() | ||
| 22 | logger = logging.getLogger(__name__) | ||
| 15 | 23 | ||
| 16 | WORK_DIR = "pr-meta" | 24 | WORK_DIR = "pr-meta" |
| 17 | 25 | ||
| @@ -160,11 +168,13 @@ def write_output(action, body=""): | |||
| 160 | 168 | ||
| 161 | 169 | ||
| 162 | def main(): | 170 | def main(): |
| 171 | logger.info("Preparing PR bot comment (deciding create/update/skip)") | ||
| 163 | check_run_id = os.environ.get("CHECK_RUN_ID", "") | 172 | check_run_id = os.environ.get("CHECK_RUN_ID", "") |
| 164 | repo = os.environ.get("GITHUB_REPOSITORY", "") | 173 | repo = os.environ.get("GITHUB_REPOSITORY", "") |
| 165 | 174 | ||
| 166 | new_body = read_file(os.path.join(WORK_DIR, "comment.md")) | 175 | new_body = read_file(os.path.join(WORK_DIR, "comment.md")) |
| 167 | if not new_body: | 176 | if not new_body: |
| 177 | logger.info("No new comment.md to post, action=skip") | ||
| 168 | write_output("skip") | 178 | write_output("skip") |
| 169 | return | 179 | return |
| 170 | 180 | ||
| @@ -172,15 +182,18 @@ def main(): | |||
| 172 | 182 | ||
| 173 | # No existing comment — create a new one | 183 | # No existing comment — create a new one |
| 174 | if not existing_body: | 184 | if not existing_body: |
| 185 | logger.info("No existing bot comment, action=create") | ||
| 175 | write_output("create", new_body) | 186 | write_output("create", new_body) |
| 176 | return | 187 | return |
| 177 | 188 | ||
| 178 | # Existing comment — build an edit line to append | 189 | # Existing comment — build an edit line to append |
| 179 | if not check_run_id: | 190 | if not check_run_id: |
| 191 | logger.info("Existing comment but no CHECK_RUN_ID, action=skip") | ||
| 180 | write_output("skip") | 192 | write_output("skip") |
| 181 | return | 193 | return |
| 182 | 194 | ||
| 183 | findings_count = read_findings_count(new_body) | 195 | findings_count = read_findings_count(new_body) |
| 196 | logger.info("Existing comment found, new run reports %d finding(s)", findings_count) | ||
| 184 | edit_line = build_edit_line(existing_body, findings_count, check_run_id, repo) | 197 | edit_line = build_edit_line(existing_body, findings_count, check_run_id, repo) |
| 185 | 198 | ||
| 186 | # Refresh the Submission Info block even if findings haven't changed | 199 | # Refresh the Submission Info block even if findings haven't changed |
| @@ -188,6 +201,7 @@ def main(): | |||
| 188 | info_changed = refreshed_body != existing_body | 201 | info_changed = refreshed_body != existing_body |
| 189 | 202 | ||
| 190 | if not edit_line and not info_changed: | 203 | if not edit_line and not info_changed: |
| 204 | logger.info("State unchanged and submission info unchanged, action=skip") | ||
| 191 | write_output("skip") | 205 | write_output("skip") |
| 192 | return | 206 | return |
| 193 | 207 | ||
| @@ -197,6 +211,8 @@ def main(): | |||
| 197 | updated = updated.rstrip() + "\n" + edit_line | 211 | updated = updated.rstrip() + "\n" + edit_line |
| 198 | else: | 212 | else: |
| 199 | updated = updated.rstrip() + "\n\n---\n\n### Updates\n\n" + edit_line | 213 | 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) | ||
| 200 | write_output("update", updated) | 216 | write_output("update", updated) |
| 201 | 217 | ||
| 202 | 218 | ||
lib/generate-changelog.py +25 −21
| @@ -4,6 +4,7 @@ and enriches entries with GitHub PR metadata. | |||
| 4 | """ | 4 | """ |
| 5 | 5 | ||
| 6 | import json | 6 | import json |
| 7 | import logging | ||
| 7 | import os | 8 | import os |
| 8 | import re | 9 | import re |
| 9 | import subprocess | 10 | import subprocess |
| @@ -14,8 +15,12 @@ from typing import Any | |||
| 14 | import requests | 15 | import requests |
| 15 | 16 | ||
| 16 | sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | 17 | sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) |
| 18 | import utils | ||
| 17 | from yaml_diff import build_index, diff_index, load_yaml_at_ref | 19 | from yaml_diff import build_index, diff_index, load_yaml_at_ref |
| 18 | 20 | ||
| 21 | utils.setup_logging() | ||
| 22 | logger = logging.getLogger(__name__) | ||
| 23 | |||
| 19 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | 24 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 20 | OUTPUT_PATH = os.path.join(PROJECT_ROOT, ".github", "changelog.json") | 25 | OUTPUT_PATH = os.path.join(PROJECT_ROOT, ".github", "changelog.json") |
| 21 | REPO = "Lissy93/awesome-privacy" | 26 | REPO = "Lissy93/awesome-privacy" |
| @@ -49,7 +54,7 @@ def get_commits(): | |||
| 49 | continue | 54 | continue |
| 50 | lines = record.split("\n", 3) | 55 | lines = record.split("\n", 3) |
| 51 | if len(lines) != 4: | 56 | 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]) |
| 53 | continue | 58 | continue |
| 54 | sha, date, author, message = lines | 59 | sha, date, author, message = lines |
| 55 | commits.append({"sha": sha, "date": date, "author": author, "message": message}) | 60 | commits.append({"sha": sha, "date": date, "author": author, "message": message}) |
| @@ -216,7 +221,7 @@ def fetch_pr_metadata(pr_numbers): | |||
| 216 | if token: | 221 | if token: |
| 217 | headers["Authorization"] = f"token {token}" | 222 | headers["Authorization"] = f"token {token}" |
| 218 | else: | 223 | 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") |
| 220 | 225 | ||
| 221 | metadata = {} | 226 | metadata = {} |
| 222 | for i, pr_num in enumerate(sorted(pr_numbers)): | 227 | for i, pr_num in enumerate(sorted(pr_numbers)): |
| @@ -234,12 +239,12 @@ def fetch_pr_metadata(pr_numbers): | |||
| 234 | "authorAvatar": data.get("user", {}).get("avatar_url", ""), | 239 | "authorAvatar": data.get("user", {}).get("avatar_url", ""), |
| 235 | } | 240 | } |
| 236 | elif resp.status_code == 403: | 241 | 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) |
| 238 | break | 243 | break |
| 239 | elif resp.status_code != 404: | 244 | 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) |
| 241 | except requests.RequestException as e: | 246 | except requests.RequestException as e: |
| 242 | print(f" PR #{pr_num}: {e}", file=sys.stderr) | 247 | logger.warning("PR #%s: %s", pr_num, e) |
| 243 | if i < len(pr_numbers) - 1: | 248 | if i < len(pr_numbers) - 1: |
| 244 | time.sleep(0.1) | 249 | time.sleep(0.1) |
| 245 | 250 | ||
| @@ -265,8 +270,7 @@ def fetch_rejections(headers, cached_rejections, checked_prs): | |||
| 265 | "per_page": 100, "page": page}, | 270 | "per_page": 100, "page": page}, |
| 266 | ) | 271 | ) |
| 267 | if resp.status_code != 200: | 272 | if resp.status_code != 200: |
| 268 | print(f" Rejections page {page}: HTTP {resp.status_code} — keeping cache", | 273 | logger.warning("Rejections page %s: HTTP %s, keeping cache", page, resp.status_code) |
| 269 | file=sys.stderr) | ||
| 270 | return cached_rejections, checked_prs | 274 | return cached_rejections, checked_prs |
| 271 | prs = resp.json() | 275 | prs = resp.json() |
| 272 | if not prs: | 276 | if not prs: |
| @@ -274,7 +278,7 @@ def fetch_rejections(headers, cached_rejections, checked_prs): | |||
| 274 | 278 | ||
| 275 | for pr in prs: | 279 | for pr in prs: |
| 276 | if pr.get("created_at", "") < REJECTIONS_SINCE: | 280 | 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) |
| 278 | return rejections, checked | 282 | return rejections, checked |
| 279 | if pr.get("merged_at"): | 283 | if pr.get("merged_at"): |
| 280 | continue | 284 | continue |
| @@ -316,10 +320,10 @@ def fetch_rejections(headers, cached_rejections, checked_prs): | |||
| 316 | page += 1 | 320 | page += 1 |
| 317 | time.sleep(0.1) | 321 | time.sleep(0.1) |
| 318 | except requests.RequestException as e: | 322 | except requests.RequestException as e: |
| 319 | print(f" Rejections: {e} — keeping cache", file=sys.stderr) | 323 | logger.warning("Rejections: %s, keeping cache", e) |
| 320 | return cached_rejections, checked_prs | 324 | return cached_rejections, checked_prs |
| 321 | 325 | ||
| 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) |
| 323 | return rejections, checked | 327 | return rejections, checked |
| 324 | 328 | ||
| 325 | 329 | ||
| @@ -342,7 +346,7 @@ def load_existing(): | |||
| 342 | 346 | ||
| 343 | 347 | ||
| 344 | def main(): | 348 | def main(): |
| 345 | print("Generating changelog from git history...") | 349 | logger.info("Generating changelog from git history") |
| 346 | 350 | ||
| 347 | existing_entries, processed_shas, existing_rejections, checked_prs = load_existing() | 351 | existing_entries, processed_shas, existing_rejections, checked_prs = load_existing() |
| 348 | commits = get_commits() | 352 | commits = get_commits() |
| @@ -360,7 +364,7 @@ def main(): | |||
| 360 | new_processed = set() | 364 | new_processed = set() |
| 361 | 365 | ||
| 362 | if new_commits: | 366 | 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)) |
| 364 | 368 | ||
| 365 | all_shas = [c["sha"] for c in commits] | 369 | all_shas = [c["sha"] for c in commits] |
| 366 | sha_to_parent = {all_shas[i]: all_shas[i + 1] for i in range(len(all_shas) - 1)} | 370 | sha_to_parent = {all_shas[i]: all_shas[i + 1] for i in range(len(all_shas) - 1)} |
| @@ -387,9 +391,9 @@ def main(): | |||
| 387 | continue | 391 | continue |
| 388 | 392 | ||
| 389 | changes = diff_commits(c["sha"], parent) | 393 | changes = diff_commits(c["sha"], parent) |
| 390 | prefix = f" [{i}/{len(new_commits)}]" | 394 | prefix = f"[{i}/{len(new_commits)}]" |
| 391 | if changes is None: | 395 | 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]) |
| 393 | continue | 397 | continue |
| 394 | 398 | ||
| 395 | # Sync merges pull content in via their 2nd parent, so their own message | 399 | # Sync merges pull content in via their 2nd parent, so their own message |
| @@ -407,11 +411,11 @@ def main(): | |||
| 407 | continue | 411 | continue |
| 408 | new_processed.add(pm["sha"]) | 412 | new_processed.add(pm["sha"]) |
| 409 | counts = emit(pm["sha"], pm["date"], pm["message"], pm_changes) | 413 | 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]) |
| 411 | continue | 415 | continue |
| 412 | 416 | ||
| 413 | counts = emit(c["sha"], c["date"], c["message"], changes) | 417 | 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]) |
| 415 | 419 | ||
| 416 | # Enrich entries missing full avatar data | 420 | # Enrich entries missing full avatar data |
| 417 | for e in existing_entries: | 421 | for e in existing_entries: |
| @@ -420,14 +424,14 @@ def main(): | |||
| 420 | pr_numbers_to_fetch.add(pr["number"]) | 424 | pr_numbers_to_fetch.add(pr["number"]) |
| 421 | 425 | ||
| 422 | if pr_numbers_to_fetch: | 426 | 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)) |
| 424 | pr_meta = fetch_pr_metadata(pr_numbers_to_fetch) | 428 | pr_meta = fetch_pr_metadata(pr_numbers_to_fetch) |
| 425 | for entry in new_entries + existing_entries: | 429 | for entry in new_entries + existing_entries: |
| 426 | pr = entry.get("pr") | 430 | pr = entry.get("pr") |
| 427 | if pr and pr.get("number") and pr["number"] in pr_meta: | 431 | if pr and pr.get("number") and pr["number"] in pr_meta: |
| 428 | entry["pr"] = pr_meta[pr["number"]] | 432 | entry["pr"] = pr_meta[pr["number"]] |
| 429 | else: | 433 | 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)) |
| 431 | 435 | ||
| 432 | all_entries = sorted(new_entries + existing_entries, key=lambda e: e["date"], reverse=True) | 436 | all_entries = sorted(new_entries + existing_entries, key=lambda e: e["date"], reverse=True) |
| 433 | 437 | ||
| @@ -436,9 +440,9 @@ def main(): | |||
| 436 | api_headers = {"User-Agent": "awesome-privacy", "Accept": "application/vnd.github.v3+json"} | 440 | api_headers = {"User-Agent": "awesome-privacy", "Accept": "application/vnd.github.v3+json"} |
| 437 | if token: | 441 | if token: |
| 438 | api_headers["Authorization"] = f"token {token}" | 442 | api_headers["Authorization"] = f"token {token}" |
| 439 | print("Fetching rejected PRs...") | 443 | logger.info("Fetching rejected PRs") |
| 440 | rejections, checked_prs = fetch_rejections(api_headers, existing_rejections, checked_prs) | 444 | 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)) |
| 442 | 446 | ||
| 443 | os.makedirs(os.path.dirname(OUTPUT_PATH), exist_ok=True) | 447 | os.makedirs(os.path.dirname(OUTPUT_PATH), exist_ok=True) |
| 444 | with open(OUTPUT_PATH, "w") as f: | 448 | with open(OUTPUT_PATH, "w") as f: |
| @@ -450,7 +454,7 @@ def main(): | |||
| 450 | "rejections": rejections, | 454 | "rejections": rejections, |
| 451 | }, f, indent=2, ensure_ascii=False) | 455 | }, f, indent=2, ensure_ascii=False) |
| 452 | 456 | ||
| 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) |
| 454 | 458 | ||
| 455 | 459 | ||
| 456 | if __name__ == "__main__": | 460 | if __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 | ||
| 4 | submodules need `requests`/`yaml`; some CI jobs install no extra deps, so those | ||
| 5 | imports are skipped there, letting `setup_logging()` work without them. | ||
| 6 | """ | ||
| 2 | 7 | ||
| 3 | from .data import DATA_PATH, PROJECT_ROOT, iter_services, load_yaml, slugify | ||
| 4 | from .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 | ) | ||
| 17 | from .http import DEFAULT_TIMEOUT, DEFAULT_USER_AGENT, check_url, make_session | ||
| 18 | from .term import make_colors, setup_logging | 8 | from .term import make_colors, setup_logging |
| 19 | 9 | ||
| 10 | try: | ||
| 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 | ||
| 26 | except ImportError: | ||
| 27 | pass | ||
| 28 | |||
| 20 | __all__ = [ | 29 | __all__ = [ |
| 21 | "AI_BOT_AUTHORS", | 30 | "AI_BOT_AUTHORS", |
| 22 | "DATA_PATH", | 31 | "DATA_PATH", |
lib/utils/term.py +48 −4
| @@ -4,21 +4,65 @@ import logging | |||
| 4 | import os | 4 | import os |
| 5 | import sys | 5 | import sys |
| 6 | 6 | ||
| 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 | |||
| 18 | def _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 | |||
| 28 | def _paint(text, code): | ||
| 29 | return f"\033[{code}m{text}\033[0m" | ||
| 30 | |||
| 31 | |||
| 32 | class _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 | ||
| 8 | 50 | ||
| 9 | 51 | ||
| 10 | def setup_logging(level="INFO"): | 52 | def setup_logging(level="INFO"): |
| 53 | handler = logging.StreamHandler(sys.stderr) | ||
| 54 | handler.setFormatter(_ColorFormatter(_color_enabled())) | ||
| 11 | logging.basicConfig( | 55 | logging.basicConfig( |
| 12 | level=getattr(logging, str(level).upper(), logging.INFO), | 56 | level=getattr(logging, str(level).upper(), logging.INFO), |
| 13 | format="%(levelname)s [%(filename)s] %(message)s", | 57 | handlers=[handler], |
| 14 | stream=sys.stderr, | 58 | force=True, |
| 15 | ) | 59 | ) |
| 16 | 60 | ||
| 17 | 61 | ||
| 18 | def make_colors(enabled=None): | 62 | def make_colors(enabled=None): |
| 19 | """Return {name: callable(str) -> str}; no-ops when colors disabled.""" | 63 | """Return {name: callable(str) -> str}; no-ops when colors disabled.""" |
| 20 | if enabled is None: | 64 | if enabled is None: |
| 21 | enabled = sys.stderr.isatty() and not os.environ.get("NO_COLOR") | 65 | enabled = _color_enabled() |
| 22 | if not enabled: | 66 | if not enabled: |
| 23 | return {name: (lambda s: s) for name in _COLOR_CODES} | 67 | return {name: (lambda s: s) for name in _COLOR_CODES} |
| 24 | return {name: (lambda s, c=code: f"\033[{c}m{s}\033[0m") for name, code in _COLOR_CODES.items()} | 68 | 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 @@ | |||
| 1 | import json | 1 | import json |
| 2 | import logging | ||
| 2 | import os | 3 | import os |
| 3 | import sys | 4 | import sys |
| 4 | 5 | ||
| 5 | import yaml | 6 | import yaml |
| 6 | from jsonschema import Draft7Validator | 7 | from jsonschema import Draft7Validator |
| 7 | 8 | ||
| 9 | sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | ||
| 10 | import utils | ||
| 11 | |||
| 12 | utils.setup_logging() | ||
| 13 | logger = logging.getLogger(__name__) | ||
| 14 | |||
| 8 | # Paths (relative to project root) | 15 | # Paths (relative to project root) |
| 9 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | 16 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 10 | DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml") | 17 | DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml") |
| @@ -18,13 +25,6 @@ EXIT_RUNTIME_ERROR = 2 | |||
| 18 | 25 | ||
| 19 | MAX_ERRORS = 20 | 26 | MAX_ERRORS = 20 |
| 20 | 27 | ||
| 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") | ||
| 23 | red = (lambda s: f"\033[31m{s}\033[0m") if _use_color else (lambda s: s) | ||
| 24 | green = (lambda s: f"\033[32m{s}\033[0m") if _use_color else (lambda s: s) | ||
| 25 | yellow = (lambda s: f"\033[33m{s}\033[0m") if _use_color else (lambda s: s) | ||
| 26 | dim = (lambda s: f"\033[2m{s}\033[0m") if _use_color else (lambda s: s) | ||
| 27 | |||
| 28 | 28 | ||
| 29 | def _clean(v): | 29 | def _clean(v): |
| 30 | """Stringify a value for inline display: neutralise backticks, collapse newlines.""" | 30 | """Stringify a value for inline display: neutralise backticks, collapse newlines.""" |
| @@ -139,12 +139,12 @@ def load_yaml(path): | |||
| 139 | with open(path, "r") as f: | 139 | with open(path, "r") as f: |
| 140 | return yaml.safe_load(f) | 140 | return yaml.safe_load(f) |
| 141 | except FileNotFoundError: | 141 | except FileNotFoundError: |
| 142 | print(red(f"File not found: {path}"), file=sys.stderr) | 142 | logger.error("File not found: %s", path) |
| 143 | sys.exit(EXIT_RUNTIME_ERROR) | 143 | sys.exit(EXIT_RUNTIME_ERROR) |
| 144 | except yaml.YAMLError as e: | 144 | except yaml.YAMLError as e: |
| 145 | msg = format_yaml_error(e) | 145 | msg = format_yaml_error(e) |
| 146 | write_errors_file([msg]) | 146 | 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) |
| 148 | sys.exit(EXIT_RUNTIME_ERROR) | 148 | sys.exit(EXIT_RUNTIME_ERROR) |
| 149 | 149 | ||
| 150 | 150 | ||
| @@ -153,10 +153,10 @@ def load_schema(path): | |||
| 153 | with open(path, "r") as f: | 153 | with open(path, "r") as f: |
| 154 | return json.load(f) | 154 | return json.load(f) |
| 155 | except FileNotFoundError: | 155 | except FileNotFoundError: |
| 156 | print(red(f"File not found: {path}"), file=sys.stderr) | 156 | logger.error("File not found: %s", path) |
| 157 | sys.exit(EXIT_RUNTIME_ERROR) | 157 | sys.exit(EXIT_RUNTIME_ERROR) |
| 158 | except json.JSONDecodeError as e: | 158 | 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) |
| 160 | sys.exit(EXIT_RUNTIME_ERROR) | 160 | sys.exit(EXIT_RUNTIME_ERROR) |
| 161 | 161 | ||
| 162 | 162 | ||
| @@ -171,6 +171,7 @@ def validate(data, schema): | |||
| 171 | 171 | ||
| 172 | 172 | ||
| 173 | def main(): | 173 | def main(): |
| 174 | logger.info("Validating awesome-privacy.yml against schema") | ||
| 174 | data = load_yaml(DATA_PATH) | 175 | data = load_yaml(DATA_PATH) |
| 175 | schema = load_schema(SCHEMA_PATH) | 176 | schema = load_schema(SCHEMA_PATH) |
| 176 | errors = validate(data, schema) | 177 | errors = validate(data, schema) |
| @@ -179,10 +180,10 @@ def main(): | |||
| 179 | write_errors_file(errors) | 180 | write_errors_file(errors) |
| 180 | shown = errors[:MAX_ERRORS] | 181 | shown = errors[:MAX_ERRORS] |
| 181 | for msg in shown: | 182 | for msg in shown: |
| 182 | print(red("ERROR") + " " + msg, file=sys.stderr) | 183 | logger.error(msg) |
| 183 | if len(errors) > MAX_ERRORS: | 184 | if len(errors) > MAX_ERRORS: |
| 184 | print(dim(f"...and {len(errors) - MAX_ERRORS} more"), file=sys.stderr) | 185 | logger.warning("...and %d more", len(errors) - MAX_ERRORS) |
| 185 | print(red(f"Validation failed: {len(errors)} error(s)"), file=sys.stderr) | 186 | logger.error("Validation failed: %d error(s)", len(errors)) |
| 186 | sys.exit(EXIT_VALIDATION_ERRORS) | 187 | sys.exit(EXIT_VALIDATION_ERRORS) |
| 187 | 188 | ||
| 188 | # Gather stats | 189 | # Gather stats |
| @@ -195,7 +196,8 @@ def main(): | |||
| 195 | for s in c.get("sections", []) | 196 | for s in c.get("sections", []) |
| 196 | ) | 197 | ) |
| 197 | clear_errors_file() | 198 | 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) | ||
| 199 | sys.exit(EXIT_VALID) | 201 | sys.exit(EXIT_VALID) |
| 200 | 202 | ||
| 201 | 203 | ||