#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Fetch the pinned documents into the git-ignored reference/ directory. Every entry of ``scripts/pinned_files.json`` names a URL, a SHA-256, its terms and what it is for. A file whose hash does not match its pin is not kept. Nothing fetched is committed or executed. There is no source tree to fetch: every emulator met by this Phase 0 is a closed box (docs/sources.md). Sites were checked before use (2026-11-26): the UK Mirror Service (bitsavers' copy; no robots.txt), archive.org (robots.txt allows /download/), www.webtech.co.jp (robots.txt allows these pages), csclub.uwaterloo.ca (no robots.txt). The User-Agent is curl's own; this script never presents itself as a browser. python3 -I scripts/fetch_references.py # fetch what is missing python3 -I scripts/fetch_references.py --verify # hash what is present, fetch nothing python3 -I scripts/fetch_references.py --record # fill empty pins (first fetch only) PDFs get a text twin in reference/text/ (pdftotext -layout) for grepping, when poppler is installed. """ from __future__ import annotations import argparse import hashlib import json import shutil import subprocess import sys import tempfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] PINS = ROOT / "scripts" / "pinned_files.json" TEXT = ROOT / "reference" / "text" 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 text_twin(path: Path) -> None: if path.suffix.lower() != ".pdf" or not shutil.which("pdftotext"): return twin = TEXT / (path.stem + ".txt") if twin.exists(): return TEXT.mkdir(parents=True, exist_ok=True) subprocess.run(["pdftotext", "-layout", str(path), str(twin)], capture_output=True, check=False) 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") args = parser.parse_args() entries = json.loads(PINS.read_text(encoding="utf-8")) problems = 0 changed = False for entry in entries: path = ROOT / entry["path"] if not path.exists(): if args.verify: 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 partial.replace(path) print(f"fetched {entry['path']}") digest = sha256(path) if not entry["sha256"]: if args.record: entry["sha256"] = digest changed = True print(f"recorded {entry['path']} {digest}") else: print(f"ERROR: {entry['path']} has no pin (use --record on the first fetch)") problems += 1 continue elif digest != entry["sha256"]: print(f"ERROR: {entry['path']} has SHA-256 {digest}, pinned {entry['sha256']}") if not args.verify: path.replace(path.with_suffix(path.suffix + ".mismatch")) problems += 1 continue else: print(f"ok {entry['path']}") text_twin(path) if changed: PINS.write_text(json.dumps(entries, indent=1, ensure_ascii=False) + "\n", encoding="utf-8") print(f"{len(entries)} pins, " + ("all verified" if not problems else f"{problems} problem(s)")) return 1 if problems else 0 if __name__ == "__main__": sys.exit(main())