#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Fetch the pinned manuals, documents and source trees into reference/. Nothing fetched here is committed (``reference/`` is git-ignored). Two pin files drive it: - ``scripts/pinned_files.json``: one entry per file: path, URL, SHA-256, licence, tier, and the date its host's robots.txt was read. A mismatch is an error and the file is not kept. - ``scripts/pinned_repos.json``: one entry per git repository, fetched at the pinned commit with ``--filter=blob:none`` and a sparse checkout of the listed paths only. Only permissively licensed trees are listed: GPL, LGPL, unlicensed and non-commercial emulator source is never fetched into this MIT repository (charter, licences point 3). python -I scripts/fetch_references.py # fetch what is missing python -I scripts/fetch_references.py --verify # check what is present, fetch nothing python -I scripts/fetch_references.py --no-repos # files only Fetched files are data: nothing here builds or runs them. Run every tool that reads ``reference/`` with ``python -I``. """ from __future__ import annotations import argparse import hashlib import json 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" USER_AGENT = "Mozilla/5.0 (emulator reference fetch)" 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 fetch_files(verify_only: bool) -> tuple[int, int]: problems = checked = 0 for entry in json.loads(FILES.read_text(encoding="utf-8")): path = ROOT / entry["path"] if path.exists(): checked += 1 if sha256(path) != entry["sha256"]: print(f"ERROR: {entry['path']} does not match its pin") problems += 1 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"]: partial.unlink() print(f"ERROR: {entry['url']} has SHA-256 {digest}, pinned {entry['sha256']}; not kept") problems += 1 continue partial.replace(path) checked += 1 print(f"fetched {entry['path']}") return problems, checked 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) -> tuple[int, int]: if not REPOS.exists(): return 0, 0 problems = checked = 0 for entry in json.loads(REPOS.read_text(encoding="utf-8")): path = ROOT / entry["path"] if path.exists(): head = git("rev-parse", "HEAD", cwd=path).stdout.strip() checked += 1 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", "pinned"), ("remote", "add", "origin", entry["url"]), ("sparse-checkout", "set", "--no-cone", *entry["sparse"]), ("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: checked += 1 print(f"fetched {entry['path']} at {entry['rev'][:12]}") return problems, checked def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--verify", action="store_true", help="check only, fetch nothing") parser.add_argument("--no-repos", action="store_true") args = parser.parse_args() problems, files = fetch_files(args.verify) repos = 0 if not args.no_repos: more, repos = fetch_repos(args.verify) problems += more print(f"{files} files and {repos} repositories match their pins; {problems} problems") return 1 if problems else 0 if __name__ == "__main__": sys.exit(main())