#!/usr/bin/env python3 """Fetch the pinned references into reference/ (git-ignored, never committed). ``scripts/pinned_files.json`` lists single files (URL, SHA-256, size, kind); ``scripts/pinned_repos.json`` lists git repositories at full commit hashes, sparse where the entry names paths. A file of kind ``live-document`` comes from a URL that serves the newest revision: a hash mismatch is a warning and the new bytes are kept. Every other kind must match its pin or it is not kept. Nothing fetched is executed. Read fetched files with ``python -I``. python -I scripts/fetch_references.py # everything missing python -I scripts/fetch_references.py --verify # hash what is present, fetch nothing """ from __future__ import annotations import argparse import hashlib import json import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] AGENT = "Mozilla/5.0 (reference fetch)" def load(name: str) -> list[dict]: return json.loads((ROOT / "scripts" / name).read_text(encoding="utf-8")) def curl(url: str) -> bytes: done = subprocess.run( ["curl", "-sSfL", "--max-time", "300", "-A", AGENT, url], capture_output=True, check=False ) if done.returncode: raise OSError(done.stderr.decode("utf-8", "replace").strip()) return done.stdout def files(verify: bool) -> int: bad = 0 for entry in load("pinned_files.json"): path = ROOT / entry["path"] live = entry["kind"] == "live-document" if path.exists(): if hashlib.sha256(path.read_bytes()).hexdigest() != entry["sha256"]: print(f"{'warning' if live else 'ERROR'}: {entry['path']} does not match its pin") bad += not live continue if verify: print(f"missing: {entry['path']}") bad += 1 continue try: data = curl(entry["url"]) except OSError as error: print(f"ERROR: {entry['url']}: {error}") bad += 1 continue digest = hashlib.sha256(data).hexdigest() if digest != entry["sha256"]: if not live: print(f"ERROR: {entry['url']} has SHA-256 {digest}; not kept") bad += 1 continue print(f"warning: {entry['path']} is a newer revision than the pin ({digest})") path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(data) print(f"fetched {entry['path']} ({len(data)} bytes)") return bad def repos(verify: bool) -> int: bad = 0 for entry in load("pinned_repos.json"): path = ROOT / entry["path"] git = ["git", "-C", str(path)] if path.exists(): head = subprocess.run( [*git, "rev-parse", "HEAD"], capture_output=True, text=True, check=False ).stdout.strip() if head != entry["rev"]: print(f"ERROR: {entry['path']} is at {head}, pinned {entry['rev']}") bad += 1 continue if verify: print(f"missing: {entry['path']}") bad += 1 continue path.mkdir(parents=True) subprocess.run([*git, "init", "-q"], check=True) subprocess.run([*git, "remote", "add", "origin", entry["url"]], check=True) if entry["sparse"]: subprocess.run( [*git, "sparse-checkout", "set", "--no-cone", *entry["sparse"]], check=True ) subprocess.run( [*git, "fetch", "-q", "--depth", "1", "--filter=blob:none", "origin", entry["rev"]], check=True, ) subprocess.run([*git, "checkout", "-q", "FETCH_HEAD"], check=True) print(f"cloned {entry['path']} at {entry['rev'][:12]}") return bad def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--verify", action="store_true", help="check only, fetch nothing") parser.add_argument("--no-repos", action="store_true", help="files only") args = parser.parse_args() bad = files(args.verify) if not args.no_repos: bad += repos(args.verify) print("ok" if not bad else f"{bad} problem(s)") return 1 if bad else 0 if __name__ == "__main__": sys.exit(main())