#!/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 by this script. Two pin files drive it: - ``scripts/pinned_files.json``: one entry per file, with its URL, SHA-256 and kind. Kinds ``document`` and ``test-rom`` must match their hash exactly; a mismatch is an error and the file is not kept. Kind ``live-document`` is a URL that always serves the newest version (a web page); a mismatch is a warning and the new bytes are kept, because the docs cite the version fetched on the entry's date. A ``.zip`` test-rom is unpacked into a directory beside it. - ``scripts/pinned_repos.json``: one git repository per entry, fetched at the pinned revision (depth 1), sparse where the entry lists paths. python -I scripts/fetch_references.py # everything missing python -I scripts/fetch_references.py --verify # hash what is present, fetch nothing python -I scripts/fetch_references.py --no-repos # files only python -I scripts/fetch_references.py --skip # leave one repository out """ from __future__ import annotations import argparse import hashlib import json import subprocess import sys import tempfile import zipfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] FILES = ROOT / "scripts" / "pinned_files.json" REPOS = ROOT / "scripts" / "pinned_repos.json" LIVE = {"live-document"} # A plain, honest client name: never a browser string (the family brief, 2026-11-26). USER_AGENT = "emu-family-reference-fetch/1.0" 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", "-A", USER_AGENT, "-o", str(target), url], capture_output=True, check=False, ) if result.returncode: raise OSError(result.stderr.decode("utf-8", "replace").strip()) def unpack(path: Path) -> None: target = path.with_suffix("") target.mkdir(exist_ok=True) with zipfile.ZipFile(path) as archive: for member in archive.infolist(): # Refuse absolute paths and parent references: the archive is untrusted data. name = Path(member.filename) if name.is_absolute() or ".." in name.parts: raise OSError(f"{path.name}: unsafe member {member.filename}") archive.extractall(target) 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"] in LIVE if path.exists(): if sha256(path) != entry["sha256"]: level = "warning" if live else "ERROR" print(f"{level}: {entry['path']} does not match its pin") problems += not live 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 digest != entry["sha256"] and not live: partial.unlink() print(f"ERROR: {entry['url']} has SHA-256 {digest}, pinned {entry['sha256']}; not kept") problems += 1 continue if digest != entry["sha256"]: print(f"warning: {entry['path']} changed since the pinned version ({digest})") partial.replace(path) if entry["kind"] == "test-rom" and path.suffix == ".zip": unpack(path) print(f"fetched {entry['path']}") 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, skip: set[str]) -> int: problems = 0 for entry in json.loads(REPOS.read_text(encoding="utf-8")): if Path(entry["path"]).name in skip: continue path = ROOT / entry["path"] if path.exists(): head = git("-C", str(path), "rev-parse", "HEAD").stdout.strip() if head != entry["rev"]: print(f"ERROR: {entry['path']} is at {head}, pinned {entry['rev']}") problems += 1 continue if verify_only: print(f"missing: {entry['path']}") problems += 1 continue path.mkdir(parents=True) steps = [ ("init", "-q", "-b", "main"), ("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: result = git(*step, cwd=path) if result.returncode: print(f"ERROR: {entry['url']}: git {step[0]}: {result.stderr.strip()}") problems += 1 break else: print(f"fetched {entry['path']} at {entry['rev'][:10]}") return problems def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--verify", action="store_true", help="hash what is present, fetch nothing") parser.add_argument("--no-repos", action="store_true", help="files only") parser.add_argument("--skip", action="append", default=[], help="repository directory name to skip") args = parser.parse_args() problems = fetch_files(args.verify) if not args.no_repos: problems += fetch_repos(args.verify, set(args.skip)) print("ok" if not problems else f"{problems} problem(s)") return 1 if problems else 0 if __name__ == "__main__": sys.exit(main())