#!/usr/bin/env python3 """Fetch the pinned documents, test programs and source trees into reference/. Nothing fetched is committed (see .gitignore). Two pin files drive this: - ``scripts/pinned_files.json``: one entry per file: path, URL, SHA-256, size, kind, licence, note. Kind ``live-document`` is a page whose bytes change between requests or revisions (a blog post); a mismatch there is a warning and the new bytes are kept. Every other kind must match its hash or the download is refused. - ``scripts/pinned_repos.json``: one entry per git repository, fetched shallow at the full commit hash, sparse where the entry lists paths. Nothing here runs what it fetches. Building Gearcoleco's libretro core is a separate, named step in docs/validation.md. Read fetched files with ``python -I``. python -I scripts/fetch_references.py # everything missing python -I scripts/fetch_references.py --verify # hash what is present, fetch nothing python -I scripts/fetch_references.py --no-repos # files only Needs ``curl`` (some hosts refuse urllib whatever its User-Agent) and ``git``. """ from __future__ import annotations import argparse import hashlib import json import subprocess import sys 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 (reference fetch)" def digest_of(data: bytes) -> str: return hashlib.sha256(data).hexdigest() def download(url: str) -> bytes: done = subprocess.run( ["curl", "-sSfL", "--max-time", "300", "-A", USER_AGENT, url], capture_output=True, check=False, ) if done.returncode: raise OSError(done.stderr.decode("utf-8", "replace").strip()) return done.stdout 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"] == "live-document" if path.exists(): if digest_of(path.read_bytes()) != 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 try: data = download(entry["url"]) except OSError as error: print(f"ERROR: {entry['url']}: {error}") problems += 1 continue if digest_of(data) != entry["sha256"]: if not live: print(f"ERROR: {entry['url']} is {digest_of(data)}, pinned {entry['sha256']}") problems += 1 continue print(f"warning: {entry['path']} differs from the revision the docs cite") path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(data) print(f"fetched {entry['path']}") return problems def git(path: Path, *args: str) -> subprocess.CompletedProcess[str]: return subprocess.run(["git", "-C", str(path), *args], capture_output=True, text=True) 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 = git(path, "rev-parse", "HEAD").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) steps = [("init", "-q"), ("remote", "add", "origin", entry["url"])] if entry.get("sparse"): steps.append(("sparse-checkout", "set", "--no-cone", *entry["sparse"])) steps.append(("fetch", "-q", "--depth", "1", "--filter=blob:none", "origin", entry["rev"])) steps.append(("checkout", "-q", "FETCH_HEAD")) for step in steps: done = git(path, *step) if done.returncode: print(f"ERROR: {entry['path']}: git {step[0]}: {done.stderr.strip()}") problems += 1 break else: 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") args = parser.parse_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())