# SPDX-License-Identifier: MIT """Fetch the pinned references into reference/ (git-ignored), or check them. python -I scripts/fetch_references.py # download what is missing python -I scripts/fetch_references.py --verify # check sizes and SHA-256s only Every entry of scripts/pinned_files.json names a URL, a SHA-256 and a size. A file is kept only if its hash matches; a mismatch is moved to trash/ (never deleted) and reported. Nothing fetched is executed. curl is run with its own User-Agent (never a browser's). After a download the PDFs are turned into text (`pdftotext -layout`) under reference/text/ for grepping. There are no pinned repositories: no source tree is needed (docs/sources.md says why each closed box stays closed). """ from __future__ import annotations import argparse import hashlib import json import shutil import subprocess import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] PINS = ROOT / "scripts" / "pinned_files.json" 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 check(entry: dict) -> str: path = ROOT / entry["path"] if not path.exists(): return "missing" if path.stat().st_size != entry["size"] or sha256(path) != entry["sha256"]: return "mismatch" return "ok" def set_aside(path: Path) -> None: trash = ROOT / "trash" / time.strftime("%Y%m%d-%H%M%S") trash.mkdir(parents=True, exist_ok=True) shutil.move(str(path), trash / path.name) def fetch(entry: dict) -> str: path = ROOT / entry["path"] path.parent.mkdir(parents=True, exist_ok=True) part = path.with_suffix(path.suffix + ".part") subprocess.run( ["curl", "-sS", "-L", "--fail", "-m", "900", "-o", str(part), entry["url"]], check=True, ) part.replace(path) status = check(entry) if status != "ok": set_aside(path) elif path.suffix == ".pdf": text = ROOT / "reference" / "text" / (path.stem + ".txt") text.parent.mkdir(parents=True, exist_ok=True) subprocess.run(["pdftotext", "-layout", str(path), str(text)], check=False) return status def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--verify", action="store_true", help="check only, fetch nothing") args = parser.parse_args() entries = json.loads(PINS.read_text()) counts: dict[str, int] = {} for entry in entries: status = check(entry) if status == "mismatch" and not args.verify: set_aside(ROOT / entry["path"]) status = "missing" if status == "missing" and not args.verify: status = fetch(entry) counts[status] = counts.get(status, 0) + 1 print(f"{status:8} {entry['path']}") print(", ".join(f"{k}: {v}" for k, v in sorted(counts.items())), f"of {len(entries)}") sys.exit(0 if counts.get("ok", 0) == len(entries) else 1) if __name__ == "__main__": main()