#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Fetch the pinned documents and source trees into reference/. Nothing fetched here is committed (reference/ is git-ignored) and nothing fetched is executed. Two pin files drive it: - ``scripts/pinned_files.json``: one entry per file: URL, SHA-256, kind, licence, note. A mismatch is an error and the file is not kept. - ``scripts/pinned_repos.json``: one git repository per entry, fetched at the pinned commit (depth 1), sparse where the entry lists patterns. The User-Agent is curl's own: this script never presents itself as a browser (Phase 0 brief, 2026-11-26). bitsavers.org refuses plain curl, so its documents come from the UK Mirror Service's copy and are pinned by SHA-256. python3 -I scripts/fetch_references.py # everything missing python3 -I scripts/fetch_references.py --verify # hash what is present, fetch nothing python3 -I scripts/fetch_references.py --record # fill in empty SHA-256 pins (first fetch) python3 -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" def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for block in iter(lambda: handle.read(1 << 20), b""): digest.update(block) return digest.hexdigest() def download(url: str, target: Path) -> None: result = subprocess.run( ["curl", "-sSfL", "--max-time", "1800", "-o", str(target), url], capture_output=True, check=False, ) if result.returncode: raise OSError(result.stderr.decode("utf-8", "replace").strip()) def fetch_files(verify_only: bool, record: bool) -> int: entries = json.loads(FILES.read_text(encoding="utf-8")) problems = 0 changed = False for entry in entries: path = ROOT / entry["path"] if path.exists(): digest = sha256(path) if not entry["sha256"] and record: entry["sha256"] = digest changed = True print(f"recorded {entry['path']} {digest}") elif digest != entry["sha256"]: print(f"ERROR: {entry['path']} does not match its pin") problems += 1 else: print(f"ok {entry['path']}") continue if verify_only: print(f"missing: {entry['path']}") problems += 1 continue path.parent.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as handle: partial = Path(handle.name) try: download(entry["url"], partial) except OSError as error: partial.unlink(missing_ok=True) print(f"ERROR: {entry['url']}: {error}") problems += 1 continue digest = sha256(partial) if not entry["sha256"] and record: entry["sha256"] = digest changed = True print(f"recorded {entry['path']} {digest}") elif digest != entry["sha256"]: partial.unlink() print(f"ERROR: {entry['url']} has SHA-256 {digest}, pinned {entry['sha256']}; not kept") problems += 1 continue partial.replace(path) print(f"fetched {entry['path']}") if changed: FILES.write_text(json.dumps(entries, indent=1) + "\n", encoding="utf-8") return problems def git(*args: str, cwd: Path | None = None) -> subprocess.CompletedProcess[str]: return subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True, check=False) def fetch_repos(verify_only: bool) -> int: problems = 0 for entry in json.loads(REPOS.read_text(encoding="utf-8")): path = ROOT / entry["path"] if (path / ".git").exists(): head = git("rev-parse", "HEAD", cwd=path).stdout.strip() if head != entry["rev"]: print(f"ERROR: {entry['path']} is at {head}, pinned {entry['rev']}") problems += 1 else: print(f"ok {entry['path']} @ {head[:12]}") continue if verify_only: print(f"missing: {entry['path']}") problems += 1 continue path.mkdir(parents=True, exist_ok=True) steps = [("init", "-q"), ("remote", "add", "origin", entry["url"])] fetch = ["fetch", "-q", "--depth", "1"] if entry.get("sparse"): steps.append(("sparse-checkout", "set", "--no-cone", *entry["sparse"])) # A partial clone: only the blobs the sparse checkout needs are downloaded # (SingleStepTests/8088 is 2 GB of objects otherwise). fetch.append("--filter=blob:none") steps += [(*fetch, "origin", entry["rev"]), ("checkout", "-q", "FETCH_HEAD")] for step in steps: result = git(*step, cwd=path) if result.returncode: print(f"ERROR: {entry['url']}: git {' '.join(step)}: {result.stderr.strip()}") problems += 1 break else: print(f"fetched {entry['path']} @ {entry['rev'][:12]}") return problems def main() -> int: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--verify", action="store_true", help="hash what is present; fetch nothing") parser.add_argument("--record", action="store_true", help="fill in empty SHA-256 pins") parser.add_argument("--no-repos", action="store_true", help="files only") args = parser.parse_args() problems = fetch_files(args.verify, args.record) if not args.no_repos: problems += fetch_repos(args.verify) print("all pins verified" if not problems else f"{problems} problem(s)") return 1 if problems else 0 if __name__ == "__main__": sys.exit(main())