#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Fetch the pinned documents, test programs, tools and source trees into reference/. Nothing fetched here is committed (see .gitignore). Two pin files drive it: - ``scripts/pinned_files.json``: one entry per file, with its URL, SHA-256, kind, tier and why it is pinned. Kinds ``manual``, ``document``, ``test-rom`` and ``tool`` must match their hash exactly; a mismatch is an error and the file is not kept. Kind ``live-forum`` is a snapshot of a page that changes (a forum thread, a mirror); a mismatch there is a warning and the new bytes are kept, because the docs cite the snapshot date. Forum pages are also written out as plain text next to their HTML. A ``nointro:SET/FILE`` URL names a file in a local copy of No-Intro's sets under ``$NO_INTRO_DIR`` (Sega's diagnostic and sample programs), copied, not downloaded. - ``scripts/pinned_repos.json``: one entry per git repository, fetched shallow and blob-filtered at the pinned revision, sparse where the entry lists gitignore-style patterns in ``sparse`` (``!`` patterns leave files out). **Boot ROMs are never fetched**, and ``--verify`` fails if any file under ``reference/`` hashes to one of Sega's three (``BIOS_SHA1`` below). **No closed-box emulator's source is fetched** (Aubrey, 2026-11-24): PicoDrive, BlastEm, jgenesis, the MiSTer core and Gens run as shipped programs or not at all; their pins left this file's list, and the trees fetched before were moved out of the repository unopened (docs/provenance.md, "Emulator sources removed"). Entries marked ``large`` (over 50 MB) are fetched only with ``--large``. python scripts/fetch_references.py # everything missing python scripts/fetch_references.py --verify # hash what is present, fetch nothing python scripts/fetch_references.py --no-repos # files only python scripts/fetch_references.py --large # also the marsdev toolchain (103 MB) python scripts/fetch_references.py --no-files --repo ares Building the referees from what this fetches is scripts/build_referees.py. """ from __future__ import annotations import argparse import hashlib import html import json import os import re 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" LIVE = {"live-forum"} USER_AGENT = "Mozilla/5.0 (sega32x-python reference fetch)" # SHA-1 of Sega's 32X boot ROMs (No-Intro "[BIOS] 32X M68000 / SH-2 Master / SH-2 # Slave (USA)", the same as MAME's 32x_g/m/s_bios.bin). Used only to refuse them. BIOS_SHA1 = { "dbebd76a448447cb6e524ac3cb0fd19fc065d944": "68000 (256 bytes)", "1e5b0b2441a4979b6966d942b20cc76c413b8c5e": "SH-2 master (2,048 bytes)", "4103668c1bbd66c5e24558e73d4f3f92061a109a": "SH-2 slave (1,024 bytes)", } BIOS_SIZES = {256, 1024, 2048} 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: if url.startswith("nointro:"): base = os.environ.get("NO_INTRO_DIR") if not base: raise OSError("set NO_INTRO_DIR to the No-Intro romset folder") target.write_bytes((Path(base) / url[len("nointro:") :]).read_bytes()) return 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 forum_text(page: str) -> str: """The posts of a phpBB thread as plain text, for grep.""" page = re.sub(r"(?is)<(script|style)\b.*?", "", page) page = re.sub(r"(?i)|", "\n", page) text = html.unescape(re.sub(r"<[^>]+>", "", page)) text = re.sub(r"[ \t]+", " ", text) return re.sub(r"(\s*\n\s*){2,}", "\n\n", text) def fetch_files(verify_only: bool, large: bool) -> int: problems = 0 for entry in json.loads(FILES.read_text(encoding="utf-8")): path = ROOT / entry["path"] if entry.get("large") and not large and not path.exists(): continue 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 its {entry['date']} snapshot") partial.replace(path) if live: path.with_suffix(".txt").write_text( forum_text(path.read_text(encoding="utf-8", errors="replace")), encoding="utf-8" ) print(f"fetched {entry['path']}") return problems def fetch_repos(verify_only: bool, only: list[str] | None) -> int: problems = 0 for entry in json.loads(REPOS.read_text(encoding="utf-8")): if only and Path(entry["path"]).name not in only: continue path = ROOT / entry["path"] if path.exists(): head = subprocess.run( ["git", "-C", str(path), "rev-parse", "HEAD"], capture_output=True, text=True, check=False, ).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) git = ["git", "-C", str(path)] subprocess.run([*git, "init", "-q"], check=True) subprocess.run([*git, "remote", "add", "origin", entry["url"]], check=True) if entry["sparse"]: subprocess.run( [*git, "sparse-checkout", "set", "--no-cone", *entry["sparse"]], check=True ) subprocess.run( [*git, "fetch", "-q", "--depth", "1", "--filter=blob:none", "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 no_boot_roms() -> int: """Refuse any file under reference/ that is one of Sega's boot ROMs.""" found = 0 for path in (ROOT / "reference").rglob("*"): if not path.is_file() or path.is_symlink() or ".git" in path.parts: continue if path.stat().st_size not in BIOS_SIZES: continue digest = hashlib.sha1(path.read_bytes()).hexdigest() if digest in BIOS_SHA1: print(f"ERROR: {path.relative_to(ROOT)} is Sega's {BIOS_SHA1[digest]} boot ROM") found += 1 return found def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument( "--verify", action="store_true", help="check what is present; fetch nothing" ) parser.add_argument("--no-files", action="store_true", help="skip the single files") parser.add_argument("--no-repos", action="store_true", help="skip the git repositories") parser.add_argument("--large", action="store_true", help="also fetch entries marked large") parser.add_argument("--repo", action="append", help="only this repository (its directory name)") args = parser.parse_args() problems = 0 if not args.no_files: problems += fetch_files(args.verify, args.large) if not args.no_repos: problems += fetch_repos(args.verify, args.repo) problems += no_boot_roms() print("all pins satisfied" if not problems else f"{problems} problem(s)") return 1 if problems else 0 if __name__ == "__main__": sys.exit(main())