|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Fail if local-only or generated paths are tracked in git.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import re |
| 7 | +import subprocess |
| 8 | +import sys |
| 9 | +from pathlib import Path |
| 10 | + |
| 11 | +ROOT = Path(__file__).resolve().parent.parent |
| 12 | + |
| 13 | +FORBIDDEN_TRACKED_PATHS = ( |
| 14 | + "research/", |
| 15 | + "site/", |
| 16 | + "docs/CONTRIBUTING.md", |
| 17 | +) |
| 18 | + |
| 19 | +FORBIDDEN_TRACKED_SUFFIXES = ( |
| 20 | + ".env", |
| 21 | + ".pem", |
| 22 | + ".key", |
| 23 | + ".p12", |
| 24 | + ".pfx", |
| 25 | +) |
| 26 | + |
| 27 | +SENSITIVE_CONTENT_PATTERNS = ( |
| 28 | + re.compile(r"-----BEGIN (?:RSA |OPENSSH |EC )?PRIVATE KEY-----"), |
| 29 | + re.compile(r"\bAKIA[0-9A-Z]{16}\b"), |
| 30 | + re.compile(r"\bghp_[A-Za-z0-9]{20,}\b"), |
| 31 | + re.compile(r"\bgithub_pat_[A-Za-z0-9_]{20,}\b"), |
| 32 | + re.compile(r"\bsk_(?:live|test)_[A-Za-z0-9]{10,}\b"), |
| 33 | +) |
| 34 | + |
| 35 | + |
| 36 | +def tracked_files() -> list[str]: |
| 37 | + result = subprocess.run( |
| 38 | + ["git", "ls-files", "-z"], |
| 39 | + cwd=ROOT, |
| 40 | + check=True, |
| 41 | + capture_output=True, |
| 42 | + ) |
| 43 | + return [entry for entry in result.stdout.decode("utf-8").split("\0") if entry] |
| 44 | + |
| 45 | + |
| 46 | +def main() -> int: |
| 47 | + errors: list[str] = [] |
| 48 | + |
| 49 | + for path in tracked_files(): |
| 50 | + if path.startswith(FORBIDDEN_TRACKED_PATHS) or path in FORBIDDEN_TRACKED_PATHS: |
| 51 | + errors.append(f"Tracked local-only path must not be committed: {path}") |
| 52 | + continue |
| 53 | + |
| 54 | + if path.endswith(FORBIDDEN_TRACKED_SUFFIXES): |
| 55 | + errors.append(f"Tracked secret-like file must not be committed: {path}") |
| 56 | + continue |
| 57 | + |
| 58 | + file_path = ROOT / path |
| 59 | + if not file_path.is_file(): |
| 60 | + continue |
| 61 | + |
| 62 | + try: |
| 63 | + content = file_path.read_text(encoding="utf-8") |
| 64 | + except UnicodeDecodeError: |
| 65 | + continue |
| 66 | + |
| 67 | + for pattern in SENSITIVE_CONTENT_PATTERNS: |
| 68 | + if pattern.search(content): |
| 69 | + errors.append( |
| 70 | + f"Possible secret pattern in tracked file: {path} ({pattern.pattern})" |
| 71 | + ) |
| 72 | + break |
| 73 | + |
| 74 | + if errors: |
| 75 | + print("Public repo hygiene check failed:\n", file=sys.stderr) |
| 76 | + for error in errors: |
| 77 | + print(f" - {error}", file=sys.stderr) |
| 78 | + return 1 |
| 79 | + |
| 80 | + print("Public repo hygiene check passed.") |
| 81 | + return 0 |
| 82 | + |
| 83 | + |
| 84 | +if __name__ == "__main__": |
| 85 | + raise SystemExit(main()) |
0 commit comments