#!/usr/bin/env python3 """Fetch the pinned references into reference/ (git-ignored, never committed). Two pin files drive it: - ``scripts/pinned_repos.json``: git repositories, each fetched shallow at a full commit hash, sparse where the entry lists paths. - ``scripts/pinned_files.json``: single files by URL and SHA-256. Kind ``document`` must match its hash or it is not kept. Kind ``live-document`` is a page that may change (a blog post, a wiki page): a mismatch is a warning and the new bytes are kept, because the docs cite the pinned revision. 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 # check what is present python -I scripts/fetch_references.py --no-repos # files only """ from __future__ import annotations import argparse import hashlib import json import subprocess import sys import tempfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] FILES = ROOT / "scripts" / "pinned_files.json" REPOS = ROOT / "scripts" / "pinned_repos.json" USER_AGENT = "Mozilla/5.0 (reference fetch)" def download(url: str) -> bytes: result = subprocess.run( ["curl", "-sSfL", "--max-time", "300", "-A", USER_AGENT, url], capture_output=True, check=False, ) if result.returncode: raise OSError(result.stderr.decode("utf-8", "replace").strip()) return result.stdout def fetch_files(verify_only: bool) -> int: problems = 0 for entry in json.loads(FILES.read_text(encoding="utf-8")): 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") problems += not live continue if verify_only: print(f"missing: {entry['path']}") problems += 1 continue try: data = download(entry["url"]) except OSError as error: print(f"ERROR: {entry['url']}: {error}") problems += 1 continue digest = hashlib.sha256(data).hexdigest() if digest != entry["sha256"]: if not live: print(f"ERROR: {entry['url']} has SHA-256 {digest}, not its pin; not kept") problems += 1 continue print(f"warning: {entry['path']} differs from the revision the docs cite ({digest})") path.parent.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as handle: handle.write(data) Path(handle.name).replace(path) print(f"fetched {entry['path']}") return problems def fetch_repos(verify_only: bool) -> int: problems = 0 for entry in json.loads(REPOS.read_text(encoding="utf-8")): path = ROOT / entry["path"] git = ["git", "-C", str(path)] if (path / ".git").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 or 'no commit'}, pinned {entry['rev']}") problems += 1 continue if verify_only: print(f"missing: {entry['path']}") problems += 1 continue path.mkdir(parents=True, exist_ok=True) subprocess.run([*git, "init", "-q"], check=True) subprocess.run([*git, "remote", "add", "origin", entry["url"]], check=True) fetch = [*git, "fetch", "-q", "--depth", "1"] if entry["sparse"]: subprocess.run( [*git, "sparse-checkout", "set", "--no-cone", *entry["sparse"]], check=True ) fetch.append("--filter=blob:none") subprocess.run([*fetch, "origin", entry["rev"]], check=True) subprocess.run([*git, "checkout", "-q", "FETCH_HEAD"], check=True) print(f"cloned {entry['path']} at {entry['rev'][:12]}") return problems def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--verify", action="store_true", help="check only; fetch nothing") parser.add_argument("--no-repos", action="store_true", help="skip the git repositories") args = parser.parse_args() problems = fetch_files(args.verify) if not args.no_repos: problems += fetch_repos(args.verify) print("all pins satisfied" if not problems else f"{problems} problem(s)") return 1 if problems else 0 if __name__ == "__main__": sys.exit(main())