#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Fetch the pinned documents, test programs 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, oracle tier and licence. Kinds ``document``, ``schematic``, ``hardware-capture`` and ``test-rom`` must match their hash exactly; a mismatch is an error and the file is not kept. Kinds ``live-page`` and ``live-forum`` are snapshots of things that change (wiki pages, forum threads); a mismatch there is a warning and the new bytes are kept, because the snapshot date is what the docs cite. Live HTML is also converted to plain text next to the file. - ``scripts/pinned_repos.json``: one entry per git repository, fetched shallow at the pinned revision (sparse where the entry lists gitignore-style patterns). AtariAge's forum refuses scripts (HTTP 403), so its threads are pinned as Wayback Machine ``id_`` snapshots; the Wayback Machine rate-limits, hence the retries and the pause before those requests. 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 Adding a pin (downloads, hashes, appends the entry; used while researching): python scripts/fetch_references.py --add URL reference/docs/name.pdf \ --kind document --tier specification --license "..." --note "..." """ from __future__ import annotations import argparse import hashlib import html import json import re import subprocess import sys import tempfile import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] FILES = ROOT / "scripts" / "pinned_files.json" REPOS = ROOT / "scripts" / "pinned_repos.json" LIVE = {"live-page", "live-forum"} SNAPSHOT_DATE = "2026-11-11" USER_AGENT = "Mozilla/5.0 (a7800-python reference fetch)" def sha256(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest() def download(url: str) -> bytes: command = [ "curl", "-sSfL", "--retry", "4", "--retry-delay", "10", "--max-time", "300", "-A", USER_AGENT, ] # fmt: skip if "web.archive.org" in url: time.sleep(3) result = subprocess.run([*command, url], capture_output=True, check=False) if result.returncode: lines = result.stderr.decode("utf-8", "replace").strip().splitlines() raise OSError(lines[-1] if lines else f"curl exit {result.returncode}") return result.stdout def page_text(raw: str) -> str: text = re.sub(r"|", "", raw, flags=re.DOTALL) text = html.unescape(re.sub(r"|

||||", "\n", text)) text = re.sub(r"<[^>]+>", " ", text) text = re.sub(r"[ \t]+", " ", text) return re.sub(r"(\s*\n\s*){2,}", "\n\n", text) def keep(path: Path, data: bytes, kind: str) -> None: path.parent.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as handle: handle.write(data) Path(handle.name).replace(path) if kind in LIVE and path.suffix == ".html": path.with_suffix(".txt").write_text( page_text(data.decode("utf-8", "replace")), encoding="utf-8" ) 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 try: data = download(entry["url"]) except OSError as error: print(f"ERROR: {entry['url']}: {error}") problems += 1 continue digest = hashlib.sha256(data).hexdigest() if digest != entry["sha256"] and not live: 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 {SNAPSHOT_DATE} snapshot") keep(path, data, entry["kind"]) print(f"fetched {entry['path']}") return problems def fetch_repos(verify_only: bool) -> int: problems = 0 for entry in json.loads(REPOS.read_text(encoding="utf-8")): 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() # fmt: skip 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"]: # gitignore-style patterns (/dir/, !/dir/), not cone directories. subprocess.run( [*git, "sparse-checkout", "set", "--no-cone", *entry["sparse"]], check=True ) fetched = subprocess.run( [*git, "fetch", "-q", "--depth", "1", "--filter=blob:none", "origin", entry["rev"]], check=False, ) if fetched.returncode: print(f"ERROR: {entry['url']}: could not fetch {entry['rev']}") problems += 1 continue subprocess.run([*git, "checkout", "-q", "FETCH_HEAD"], check=True) print(f"cloned {entry['path']} at {entry['rev'][:12]}") return problems def add_pin(args: argparse.Namespace) -> int: url, relative = args.add entries = json.loads(FILES.read_text(encoding="utf-8")) if FILES.exists() else [] if any(e["path"] == relative for e in entries): print(f"already pinned: {relative}") return 1 try: data = download(url) except OSError as error: print(f"ERROR: {url}: {error}") return 1 keep(ROOT / relative, data, args.kind) entries.append( { "path": relative, "url": url, "sha256": hashlib.sha256(data).hexdigest(), "size": len(data), "kind": args.kind, "tier": args.tier, "license": args.license, "note": args.note, } ) FILES.write_text(json.dumps(entries, indent=1) + "\n", encoding="utf-8") print(f"pinned {relative} ({len(data)} bytes)") return 0 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-repos", action="store_true", help="skip the git repositories") parser.add_argument("--add", nargs=2, metavar=("URL", "PATH"), help="pin one more file") parser.add_argument("--kind", default="document") parser.add_argument("--tier", default="specification") parser.add_argument("--license", default="not stated") parser.add_argument("--note", default="") args = parser.parse_args() if args.add: return add_pin(args) problems = fetch_files(args.verify) if not args.no_repos: problems += fetch_repos(args.verify) print("all pins satisfied" if not problems else f"{problems} problem(s)") return 1 if problems else 0 if __name__ == "__main__": sys.exit(main())