#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Fetch, or find in place, the pinned documents and source trees under reference/. Nothing fetched is committed (.gitignore has reference/). Two pin files drive it: - ``scripts/pinned_files.json``: one entry per file, with URL, SHA-256 and kind. ``document`` must match its hash (a mismatch is an error and the download is not kept); ``live-document`` is a URL that serves the newest text, so a mismatch is a warning and the docs cite the version in the entry's note. - ``scripts/pinned_repos.json``: one entry per repository at a full commit SHA, cloned shallow and sparse. An entry may name a ``local`` copy (a path relative to this repository, e.g. a sibling snes-python checkout's ``reference/``). An entry with ``"fetch": false`` is a closed box or an unopened source recorded for lineage only: it is never fetched (Wave 2). When that copy is at the pinned revision or hash, and (for a repository) every pinned sparse path exists in it, the pin is **satisfied in place**: nothing is cloned, copied or linked, and the docs cite the local path. Pass ``--no-local`` to fetch anyway. python -I scripts/fetch_references.py # what is missing python -I scripts/fetch_references.py --verify # check, fetch nothing """ 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" LARGE = 20_000_000 # bytes; files above this need --all USER_AGENT = "Mozilla/5.0 (hg51b-python 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 git_head(path: Path) -> str: result = subprocess.run( ["git", "-C", str(path), "rev-parse", "HEAD"], capture_output=True, text=True, check=False ) return result.stdout.strip() def download(url: str, target: Path) -> None: # curl follows redirects and streams to disk. 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 has_sparse(path: Path, patterns: list[str]) -> list[str]: """The pinned sparse patterns (``/dir/``, ``/file``) missing from a local copy.""" # "!" patterns exclude (a GPL file inside a BSD directory): nothing to find for them. return [p for p in patterns if not p.startswith("!") and not (path / p.strip("/")).exists()] def fetch_files(verify_only: bool, use_local: bool, everything: bool) -> int: problems = 0 for entry in json.loads(FILES.read_text(encoding="utf-8")): live = entry["kind"] == "live-document" local = ROOT / entry["local"] if use_local and entry.get("local") else None if local and local.exists() and sha256(local) == entry["sha256"]: print(f"in place: {entry['path']} = {local}") continue path = ROOT / entry["path"] if path.exists(): if sha256(path) != entry["sha256"]: print(f"{'warning' if live else 'ERROR'}: {entry['path']} does not match its pin") problems += not live continue if verify_only: print(f"missing: {entry['path']}") problems += 1 continue if entry["size"] > LARGE and not everything: print(f"skipped (large, --all): {entry['path']}") 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") partial.replace(path) print(f"fetched {entry['path']}") return problems def fetch_repos(verify_only: bool, use_local: bool) -> int: problems = 0 for entry in json.loads(REPOS.read_text(encoding="utf-8")): if entry.get("fetch") is False: print(f"closed box, not fetched: {entry['path']} ({entry['license']})") continue local = ROOT / entry["local"] if use_local and entry.get("local") else None if local and local.exists(): head = git_head(local) missing = has_sparse(local, entry["sparse"]) if head == entry["rev"] and not missing: print(f"in place: {entry['path']} = {local} at {head[:12]}") continue if missing: print(f"note: {local} lacks {', '.join(missing)}; fetching here") else: print(f"note: {local} is at {head[:12]}, pinned {entry['rev'][:12]}; fetching here") path = ROOT / entry["path"] if path.exists(): head = git_head(path) 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) # The pins are gitignore-style patterns (/dir/, /file), not cone directories. 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 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("--no-local", action="store_true", help="ignore local copies; fetch here") parser.add_argument("--all", action="store_true", help="include files over 20 MB") args = parser.parse_args() use_local = not args.no_local problems = fetch_files(args.verify, use_local, args.all) if not args.no_repos: problems += fetch_repos(args.verify, use_local) print("all pins satisfied" if not problems else f"{problems} problem(s)") return 1 if problems else 0 if __name__ == "__main__": sys.exit(main())