#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Fetch the pinned documents into reference/ (git-ignored), or verify what is there. Every entry of scripts/pinned_files.json names a URL, the local path and a SHA-256. A download whose hash differs from its pin is refused and not kept. Wiki pages are pinned by their revision id (the URL carries `oldid=`), so the bytes do not move. Nothing fetched is executed or committed. Run Python that reads reference/ with -I. python -I scripts/fetch_references.py # fetch what is missing python -I scripts/fetch_references.py --verify # hash what is present, fetch nothing Before adding a site, read its robots.txt: a site that blocks AI crawlers (ClaudeBot, anthropic-ai, GPTBot and the like) or serves an anti-AI challenge is set aside, not worked around (docs/validation.md records the sites checked). """ 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] PINS = ROOT / "scripts" / "pinned_files.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: 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 main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--verify", action="store_true", help="hash what is present, fetch nothing") args = parser.parse_args() problems = checked = 0 for entry in json.loads(PINS.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 args.verify: 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']}") print(f"{checked} file(s) match their pins" if not problems else f"{problems} problem(s)") return 1 if problems else 0 if __name__ == "__main__": sys.exit(main())