#!/usr/bin/env python3 """Download the pinned references into the git-ignored reference/ directory. Pins live in two JSON files beside this script: - ``pinned_files.json``: documents, each with URL, SHA-256, size, kind, tier, licence and a note. A download whose hash differs is refused, except for ``live-document`` entries (web pages that change between requests), which are kept with a warning. - ``pinned_repos.json``: git repositories, each checked out shallow at a full commit hash, sparse when the entry lists paths. Nothing fetched is executed or committed. Read it with ``python -I``. python -I scripts/fetch_references.py # fetch what is missing python -I scripts/fetch_references.py --verify # check what is there, fetch nothing """ from __future__ import annotations import argparse import hashlib import json import subprocess import sys from pathlib import Path HERE = Path(__file__).resolve().parent ROOT = HERE.parent 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 check_file(entry: dict, verify: bool) -> bool: """True when the file is present (or fetched) and matches its pin.""" target = ROOT / entry["path"] live = entry["kind"] == "live-document" if not target.exists(): if verify: print(f"missing {entry['path']}") return False target.parent.mkdir(parents=True, exist_ok=True) partial = target.with_name(target.name + ".part") # curl, because some hosts turn away Python's urllib. done = subprocess.run( ["curl", "-sSfL", "--max-time", "600", "-A", "Mozilla/5.0 (reference fetch)", "-o", str(partial), entry["url"]], check=False, ) # fmt: skip if done.returncode: print(f"FAILED {entry['url']}") return False if sha256(partial) != entry["sha256"] and not live: print(f"REFUSED {entry['path']}: hash {sha256(partial)} is not the pin") partial.rename(partial.with_name(partial.name + ".rejected")) return False partial.rename(target) print(f"fetched {entry['path']}") if sha256(target) != entry["sha256"]: print(f"{'changed ' if live else 'MISMATCH'} {entry['path']}" + (" (live page; kept)" if live else "")) return live return True def git(path: Path, *args: str) -> subprocess.CompletedProcess[str]: return subprocess.run(["git", "-C", str(path), *args], capture_output=True, text=True, check=False) def check_repo(entry: dict, verify: bool) -> bool: target = ROOT / entry["path"] if target.exists(): head = git(target, "rev-parse", "HEAD").stdout.strip() if head != entry["rev"]: print(f"MISMATCH {entry['path']} is at {head or '?'}, pinned {entry['rev']}") return False return True if verify: print(f"missing {entry['path']}") return False target.mkdir(parents=True) steps = [["init", "-q"], ["remote", "add", "origin", entry["url"]]] if entry["sparse"]: steps.append(["sparse-checkout", "set", "--no-cone", *entry["sparse"]]) steps += [ ["fetch", "-q", "--depth", "1", "--filter=blob:none", "origin", entry["rev"]], ["checkout", "-q", "FETCH_HEAD"], ] for step in steps: done = git(target, *step) if done.returncode: print(f"FAILED {entry['path']}: git {step[0]}: {done.stderr.strip()}") return False print(f"cloned {entry['path']} @ {entry['rev'][:12]}") return True def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--verify", action="store_true", help="check only; download nothing") args = parser.parse_args() files = json.loads((HERE / "pinned_files.json").read_text(encoding="utf-8")) repos = json.loads((HERE / "pinned_repos.json").read_text(encoding="utf-8")) good = sum(check_file(entry, args.verify) for entry in files) good += sum(check_repo(entry, args.verify) for entry in repos) total = len(files) + len(repos) print(f"{good}/{total} pins satisfied ({len(files)} files, {len(repos)} repositories)") return 0 if good == total else 1 if __name__ == "__main__": sys.exit(main())