#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Fetch the pinned documents and software lists into reference/. Nothing fetched here is committed (reference/ is git-ignored) and nothing fetched is executed. ``scripts/pinned_files.json`` holds one entry per file: path, URL, SHA-256, kind, licence and a note. - Kind ``document`` must match its SHA-256 exactly; a mismatch is an error and the download is not kept. - Kind ``live-document`` is a page that its author edits in place; a mismatch is a warning and the new bytes are kept, because the docs cite the version named in the entry's note. - ``--pin`` downloads entries that have no ``sha256`` yet and writes their hash into the pin file (used once, when a source is added; review the diff before committing). Every site in the pin file had its robots.txt read before the first fetch (docs/sources.md). The client sends its own name as the User-Agent and never a browser's; a site that refuses it is recorded, not worked around. 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 --pin # fetch and pin new entries """ 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" LIVE = {"live-document"} # Our own name, not a browser's (the Phase 0 brief's User-Agent rule). USER_AGENT = "emu-family-reference-fetch/1.0" 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(entry: dict, pin: bool) -> tuple[int, bool]: """Fetch one entry; return (problems, pin file changed).""" path = ROOT / entry["path"] 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}") return 1, False digest = sha256(partial) pinned = entry.get("sha256") if pinned is None: if not pin: partial.unlink() print(f"ERROR: {entry['path']} has no pin; run with --pin to add one") return 1, False entry["sha256"] = digest entry["bytes"] = partial.stat().st_size partial.replace(path) print(f"pinned {entry['path']} {digest}") return 0, True if digest != pinned and entry["kind"] not in LIVE: partial.unlink() print(f"ERROR: {entry['url']} has SHA-256 {digest}, pinned {pinned}; not kept") return 1, False if digest != pinned: print(f"warning: {entry['path']} changed since the pinned version ({digest})") partial.replace(path) print(f"fetched {entry['path']}") return 0, False def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--verify", action="store_true", help="hash what is present, fetch nothing") parser.add_argument("--pin", action="store_true", help="fetch and pin entries without a hash") args = parser.parse_args() entries = json.loads(FILES.read_text(encoding="utf-8")) problems = 0 changed = False present = 0 for entry in entries: path = ROOT / entry["path"] if path.exists() and "sha256" in entry: present += 1 if sha256(path) != entry["sha256"]: live = entry["kind"] in LIVE print(f"{'warning' if live else 'ERROR'}: {entry['path']} does not match its pin") problems += not live continue if args.verify: print(f"missing: {entry['path']}") problems += 1 continue bad, pinned = fetch(entry, args.pin) problems += bad changed |= pinned if changed: FILES.write_text(json.dumps(entries, indent=1, ensure_ascii=False) + "\n", encoding="utf-8") print(f"{len(entries)} pinned, {present} present and checked") print("ok" if not problems else f"{problems} problem(s)") return 1 if problems else 0 if __name__ == "__main__": sys.exit(main())