#!/usr/bin/env python3 """Fetch the references docs/phase0.md relies on into the git-ignored reference/. Every file is pinned by the SHA-256 of its bytes, and by the commit in its URL where the host has commits. The pins live in scripts/reference_pins.json. Nothing fetched here is committed or shipped. python scripts/fetch_references.py fetch what is missing, then verify python scripts/fetch_references.py --verify verify only: no network python scripts/fetch_references.py --local also check the files cited in place from megadrive-python, and extract the pinned members of its FMDocs.7z python scripts/fetch_references.py --pin print the SHA-256 of every file present, as pin entries (used once, when a source is first added) A file whose bytes do not match its pin is left where it is, reported, and the script exits 1. Nothing is ever deleted or overwritten: move a bad file into trash/ by hand and run again. Kinds of pin: "file" a fixed file (a repository file at a commit, a PDF, a recording). "live" a forum or wiki page. Its bytes change with every request (session tokens, view counts), so a fresh fetch will not match the pin. The pin records the bytes Phase 0 read. A mismatch on a fresh fetch is reported as a warning, not an error; --verify of the copy Phase 0 read is exact. "local" a file cited in place from /data/emu/megadrive-python (not copied). "member" a member of megadrive-python's reference/manuals/FMDocs.7z, extracted into reference/fmdocs/ with 7z. What is deliberately NOT fetched (docs/phase0.md, "Sources found and not read"): any Nuked model, YM2608-LLE, MAME's GPL FM cores, BlastEm, Genesis Plus GX, and anything by an author who objects to AI use of his work. Phase 0 fetched no reference model. The closed-box rung (docs/validation.md, rung 6) adds its own pin when the build session reaches it, under restart.md rule 8. """ from __future__ import annotations import argparse import hashlib import json import shutil import socket import subprocess import sys import time import urllib.request from pathlib import Path ROOT = Path(__file__).resolve().parents[1] REFERENCE = ROOT / "reference" PINS_FILE = Path(__file__).resolve().with_name("reference_pins.json") MEGADRIVE = Path("/data/emu/megadrive-python") FMDOCS = MEGADRIVE / "reference/manuals/FMDocs.7z" USER_AGENT = "reference-fetch" PAUSE_SECONDS = 1.0 # between requests to one host: these are small community sites def sha256_of(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 load_pins() -> list[dict]: return json.loads(PINS_FILE.read_text(encoding="utf-8")) def target_of(pin: dict) -> Path: if pin["kind"] == "local": return MEGADRIVE / pin["path"] return REFERENCE / pin["path"] def fetch(pin: dict) -> None: target = target_of(pin) target.parent.mkdir(parents=True, exist_ok=True) request = urllib.request.Request(pin["url"], headers={"User-Agent": USER_AGENT}) with urllib.request.urlopen(request, timeout=60) as response: data = response.read() partial = target.with_name(target.name + ".part") partial.write_bytes(data) partial.rename(target) time.sleep(PAUSE_SECONDS) def extract_member(pin: dict) -> None: """Extract one member of megadrive-python's FMDocs.7z to reference/fmdocs/.""" if shutil.which("7z") is None: raise RuntimeError("7z is not installed") out = REFERENCE / "fmdocs" out.mkdir(parents=True, exist_ok=True) subprocess.run( ["7z", "x", "-y", f"-o{out}", str(FMDOCS), pin["member"]], check=True, stdout=subprocess.DEVNULL, ) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--verify", action="store_true", help="verify only: no network") parser.add_argument("--local", action="store_true", help="also check megadrive-python's files") parser.add_argument("--pin", action="store_true", help="print hashes of the files present") args = parser.parse_args() socket.setdefaulttimeout(60) pins = load_pins() bad = 0 warned = 0 checked = 0 for pin in pins: kind = pin["kind"] if kind in ("local", "member") and not args.local: continue target = target_of(pin) fresh = False if not target.exists() and not args.verify and not args.pin: try: if kind == "member": extract_member(pin) elif kind == "local": pass # cited in place: megadrive-python's own script fetches it else: fetch(pin) fresh = True except Exception as error: # noqa: BLE001 (report, go on to the next file) print(f"FAILED {pin['path']}: {error}") bad += 1 continue if not target.exists(): print(f"MISSING {pin['path']}") bad += 1 continue actual = sha256_of(target) if args.pin: print(json.dumps({**pin, "sha256": actual})) continue checked += 1 if actual == pin["sha256"]: continue if kind == "live" and fresh: print(f"CHANGED {pin['path']}: a live page; not the bytes Phase 0 read") warned += 1 else: print(f"MISMATCH {pin['path']}: have {actual}, pinned {pin['sha256']}") bad += 1 if not args.pin: print(f"{checked} checked, {bad} bad, {warned} live pages changed") return 1 if bad else 0 if __name__ == "__main__": sys.exit(main())