|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Write remote main branch protection snapshot for audit trail.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import argparse |
| 7 | +import json |
| 8 | +import os |
| 9 | +import sys |
| 10 | +from datetime import UTC, datetime |
| 11 | +from pathlib import Path |
| 12 | + |
| 13 | +_SCRIPTS = Path(__file__).resolve().parent |
| 14 | +if str(_SCRIPTS) not in sys.path: |
| 15 | + sys.path.insert(0, str(_SCRIPTS)) |
| 16 | +from audit_branch_protection_api import _fetch_protection, _github_repo, _required_contexts # noqa: E402 |
| 17 | + |
| 18 | + |
| 19 | +def _repo_root() -> Path: |
| 20 | + return Path(__file__).resolve().parents[1] |
| 21 | + |
| 22 | + |
| 23 | +def main() -> int: |
| 24 | + p = argparse.ArgumentParser(description=__doc__) |
| 25 | + p.add_argument( |
| 26 | + "--out", |
| 27 | + type=Path, |
| 28 | + default=None, |
| 29 | + help="Default: benchmarks/reports/branch_protection_remote_snapshot.json", |
| 30 | + ) |
| 31 | + args = p.parse_args() |
| 32 | + token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN") |
| 33 | + if not token: |
| 34 | + print("No GITHUB_TOKEN", file=sys.stderr) |
| 35 | + return 2 |
| 36 | + owner, repo = _github_repo() |
| 37 | + if not owner: |
| 38 | + print("GITHUB_REPOSITORY not set", file=sys.stderr) |
| 39 | + return 2 |
| 40 | + protection = _fetch_protection(owner=owner, repo=repo, token=token) |
| 41 | + root = _repo_root() |
| 42 | + out = args.out or (root / "benchmarks" / "reports" / "branch_protection_remote_snapshot.json") |
| 43 | + payload = { |
| 44 | + "schema_version": "conicshield_branch_protection_remote_snapshot/v1", |
| 45 | + "generated_at_utc": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"), |
| 46 | + "repository": f"{owner}/{repo}", |
| 47 | + "branch": "main", |
| 48 | + "configured": protection is not None, |
| 49 | + "required_contexts": sorted(_required_contexts(protection)) if protection else [], |
| 50 | + "raw": protection, |
| 51 | + } |
| 52 | + out.parent.mkdir(parents=True, exist_ok=True) |
| 53 | + out.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") |
| 54 | + print(out) |
| 55 | + return 0 if protection else 1 |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + raise SystemExit(main()) |
0 commit comments