#!/usr/bin/env python3 """Fetch the pinned documents, archives 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 and kind (``document``, ``archive``, ``test-rom``, ``tool``). A file must match its hash exactly; a mismatch is an error and the file is not kept. An entry with ``"copy_of"`` is not downloaded: it is copied out of a pinned repository already checked out under reference/src (the manuals that live inside the MiSTer repository), then hashed like any other. A ``.zip`` whose entry says ``"unpack": true`` is unpacked into a directory named after it. - ``scripts/pinned_repos.json``: one entry per git repository, cloned shallow at the pinned revision (sparse where the entry lists paths). 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 python -I scripts/fetch_references.py --skip mame # all but reference/src/mame Repositories are fetched before files, because some files are copies out of them. Building the Verilog referee from what this fetches is scripts/build_referee.py. """ from __future__ import annotations import argparse import hashlib import json import shutil import subprocess import sys import tempfile import zipfile 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 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: # curl rather than urllib: it follows redirects (the Wayback Machine's # included) 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 unpack(path: Path) -> None: target = path.with_suffix("") if target.exists(): return with zipfile.ZipFile(path) as archive: root = target.resolve() for member in archive.infolist(): # Refuse a member that would land outside the target directory. if not (root / member.filename).resolve().is_relative_to(root): raise OSError(f"{path.name}: unsafe member {member.filename!r}") archive.extractall(target) def fetch_files(verify_only: bool, tools: bool) -> int: problems = 0 for entry in json.loads(FILES.read_text(encoding="utf-8")): if entry["kind"] == "tool" and not tools: continue path = ROOT / entry["path"] if path.exists(): if sha256(path) != entry["sha256"]: print(f"ERROR: {entry['path']} does not match its pin") problems += 1 elif entry.get("unpack"): unpack(path) 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: if "copy_of" in entry: shutil.copyfile(ROOT / entry["copy_of"], partial) else: download(entry["url"], partial) except OSError as error: partial.unlink(missing_ok=True) print(f"ERROR: {entry.get('copy_of') or entry['url']}: {error}") problems += 1 continue digest = sha256(partial) if digest != entry["sha256"]: partial.unlink() print(f"ERROR: {entry['path']} has SHA-256 {digest}, pinned {entry['sha256']}; not kept") problems += 1 continue partial.replace(path) if entry.get("unpack"): unpack(path) print(f"fetched {entry['path']}") return problems def fetch_repos(verify_only: bool, skip: set[str]) -> int: problems = 0 for entry in json.loads(REPOS.read_text(encoding="utf-8")): if Path(entry["path"]).name in skip: continue 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() 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"]: # 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-tools", action="store_true", help="skip kind 'tool' downloads") parser.add_argument( "--skip", action="append", default=[], metavar="NAME", help="skip the repository checked out at reference/src/NAME (repeatable)", ) args = parser.parse_args() problems = 0 if not args.no_repos: problems += fetch_repos(args.verify, set(args.skip)) problems += fetch_files(args.verify, tools=not args.no_tools) print("all pins satisfied" if not problems else f"{problems} problem(s)") return 1 if problems else 0 if __name__ == "__main__": sys.exit(main())