|
|
| """One-off utility: redact GitHub PAT-like strings in Data/*.csv (in place)."""
|
| from __future__ import annotations
|
|
|
| import re
|
| import sys
|
| from pathlib import Path
|
|
|
| ROOT = Path(__file__).resolve().parents[1]
|
| DATA = ROOT / "Data"
|
| REDACTED = "[REDACTED_GITHUB_TOKEN]"
|
|
|
|
|
| _PATTERNS = [
|
| re.compile(r"github_pat_[A-Za-z0-9_]{20,}"),
|
| re.compile(r"ghp_[A-Za-z0-9]{36,}"),
|
| re.compile(r"gho_[A-Za-z0-9]{36,}"),
|
| re.compile(r"ghu_[A-Za-z0-9]{36,}"),
|
| re.compile(r"ghs_[A-Za-z0-9]{36,}"),
|
| re.compile(r"ghr_[A-Za-z0-9]{36,}"),
|
| ]
|
|
|
|
|
| def redact_text(text: str) -> tuple[str, int]:
|
| count = 0
|
| for pattern in _PATTERNS:
|
| text, n = pattern.subn(REDACTED, text)
|
| count += n
|
| return text, count
|
|
|
|
|
| def process_file(path: Path) -> int:
|
| tmp = path.with_suffix(path.suffix + ".redacting")
|
| total = 0
|
| with open(path, encoding="utf-8", errors="replace") as src, open(
|
| tmp, "w", encoding="utf-8", newline=""
|
| ) as dst:
|
| for line in src:
|
| new_line, n = redact_text(line)
|
| total += n
|
| dst.write(new_line)
|
| tmp.replace(path)
|
| return total
|
|
|
|
|
| def main() -> None:
|
| if not DATA.is_dir():
|
| print(f"Missing {DATA}", file=sys.stderr)
|
| sys.exit(1)
|
| csv_files = sorted(DATA.rglob("*.csv"))
|
| grand = 0
|
| for path in csv_files:
|
| n = process_file(path)
|
| if n:
|
| print(f" {path.relative_to(ROOT)}: {n} redaction(s)")
|
| grand += n
|
| print(f"Done. {grand} token-like string(s) redacted across {len(csv_files)} file(s).")
|
|
|
|
|
| if __name__ == "__main__":
|
| main()
|
|
|