# SPDX-License-Identifier: MIT """Fetch the pinned references into the git-ignored reference/ directory. python -I scripts/fetch_references.py # download what is missing, check every pin python -I scripts/fetch_references.py --verify # check what is on disk, download nothing python -I scripts/fetch_references.py --record # (maintainer) fill empty sha256/size pins Files come from scripts/pinned_files.json (each pinned by SHA-256 and size), repositories from scripts/pinned_repos.json (each pinned by commit, sparse). Fetched material is third-party: it is never committed and never executed by this script. Site rules honoured here (docs/sources.md): each host's robots.txt was read before its first pin; zimmers.net asks for a 10 s crawl delay and disallows PDFs and archives (only its GIF scans and text files are pinned); funet.fi's /pub/cbm now redirects to zimmers and is not used; bitsavers is reached through the UK Mirror Service. The User-Agent names this script; it is never a browser's. """ from __future__ import annotations import argparse import hashlib import json import pathlib import subprocess import sys import time import urllib.parse import urllib.request ROOT = pathlib.Path(__file__).resolve().parent.parent FILES = ROOT / "scripts" / "pinned_files.json" REPOS = ROOT / "scripts" / "pinned_repos.json" USER_AGENT = "pet-python-fetch/0.1 (reference pinning script)" # Seconds between requests to one host: the host's Crawl-delay where it states one. HOST_DELAY = {"www.zimmers.net": 11.0, "archive.org": 2.0} _last_request: dict[str, float] = {} def sha256_of(path: pathlib.Path) -> str: digest = hashlib.sha256() with path.open("rb") as fh: for block in iter(lambda: fh.read(1 << 20), b""): digest.update(block) return digest.hexdigest() def download(url: str, dest: pathlib.Path) -> None: host = urllib.parse.urlsplit(url).hostname or "" wait = HOST_DELAY.get(host, 1.0) - (time.monotonic() - _last_request.get(host, -1e9)) if wait > 0: time.sleep(wait) dest.parent.mkdir(parents=True, exist_ok=True) partial = dest.with_name(dest.name + ".part") request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) with urllib.request.urlopen(request, timeout=120) as response, partial.open("wb") as out: final_host = urllib.parse.urlsplit(response.geturl()).hostname if final_host != host and not (host == "archive.org" and final_host and final_host.endswith(".archive.org")): raise RuntimeError(f"{url} redirected to {response.geturl()}: re-check that host's rules") while block := response.read(1 << 20): out.write(block) _last_request[host] = time.monotonic() partial.replace(dest) def do_files(verify: bool, record: bool) -> int: pins = json.loads(FILES.read_text(encoding="utf-8")) bad = 0 changed = False for pin in pins: dest = ROOT / pin["path"] if not dest.exists(): if verify: print(f"MISSING {pin['path']}") bad += 1 continue print(f"fetch {pin['url']}") download(pin["url"], dest) digest, size = sha256_of(dest), dest.stat().st_size if not pin.get("sha256"): if record: pin["sha256"], pin["size"] = digest, size changed = True print(f"recorded {pin['path']} {digest}") continue print(f"UNPINNED {pin['path']} (run --record)") bad += 1 elif digest != pin["sha256"] or size != pin["size"]: print(f"MISMATCH {pin['path']}: {digest} {size}") bad += 1 else: print(f"ok {pin['path']}") if changed: FILES.write_text(json.dumps(pins, indent=1, ensure_ascii=False) + "\n", encoding="utf-8") return bad def git(*args: str, cwd: pathlib.Path | None = None) -> str: return subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True).stdout.strip() def do_repos(verify: bool) -> int: bad = 0 for pin in json.loads(REPOS.read_text(encoding="utf-8")): dest = ROOT / pin["path"] if not dest.exists(): if verify: print(f"MISSING {pin['path']}") bad += 1 continue print(f"clone {pin['url']} @ {pin['commit'][:12]}") dest.mkdir(parents=True) git("init", "-q", cwd=dest) git("remote", "add", "origin", pin["url"], cwd=dest) git("sparse-checkout", "set", "--no-cone", *pin["sparse"], cwd=dest) git("fetch", "-q", "--depth", "1", "--filter=blob:none", "origin", pin["commit"], cwd=dest) git("checkout", "-q", "FETCH_HEAD", cwd=dest) head = git("rev-parse", "HEAD", cwd=dest) if head != pin["commit"]: print(f"MISMATCH {pin['path']}: HEAD {head}") bad += 1 else: print(f"ok {pin['path']} @ {head[:12]}") return bad def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--verify", action="store_true", help="check pins only, download nothing") parser.add_argument("--record", action="store_true", help="fill empty sha256/size pins") args = parser.parse_args() bad = do_files(args.verify, args.record) + do_repos(args.verify) print("all pins verified" if not bad else f"{bad} problem(s)") return 1 if bad else 0 if __name__ == "__main__": sys.exit(main())