# 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 scripts/pinned_files.json lists documents by URL, SHA-256 and size; scripts/pinned_repos.json lists repositories by full commit, checked out shallow (and sparse when the entry names `paths`). A file whose hash does not match is moved to trash/ (never deleted) and reported. Nothing fetched is executed. PDFs are turned into text (`pdftotext -layout`) under reference/text/ for grepping (scans without a text layer are marked `"totext": false` and have an OCR'd `.text.pdf` sibling); zip archives are unpacked beside themselves, read only. """ 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" REPOS = ROOT / "scripts" / "pinned_repos.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_name(path.name + ".part") done = subprocess.run(["curl", "-sS", "-L", "--fail", "-m", "900", "-o", str(part), entry["url"]], check=False) # fmt: skip if done.returncode != 0: part.unlink(missing_ok=True) return "failed" part.replace(path) state = check(entry) if state != "ok": set_aside(path) return state def unpack(entry: dict) -> None: path = ROOT / entry["path"] if path.suffix == ".pdf" and entry.get("totext", True) and shutil.which("pdftotext"): text = ROOT / "reference" / "text" / (path.name.removesuffix(".pdf").removesuffix(".text") + ".txt") if not text.exists(): text.parent.mkdir(parents=True, exist_ok=True) subprocess.run(["pdftotext", "-layout", str(path), str(text)], check=False) elif path.suffix == ".zip": target = path.with_suffix("") if not target.exists() and shutil.which("unzip"): # Info-ZIP's unzip, not zipfile: the ASIC archive's local and central names # differ (backslashes), which zipfile refuses. unzip strips "../" and leading "/". subprocess.run(["unzip", "-q", "-o", str(path), "-d", str(target)], check=False, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # fmt: skip def repo_state(entry: dict) -> str: path = ROOT / entry["path"] if not (path / ".git").exists(): return "missing" head = subprocess.run(["git", "-C", str(path), "rev-parse", "HEAD"], capture_output=True, text=True, check=False).stdout.strip() # fmt: skip return "ok" if head == entry["commit"] else "mismatch" def fetch_repo(entry: dict) -> str: """A shallow (and, with `paths`, sparse) checkout of exactly the pinned commit.""" path = ROOT / entry["path"] path.mkdir(parents=True, exist_ok=True) git = ["git", "-C", str(path)] subprocess.run([*git, "init", "-q"], check=True) if entry.get("paths"): subprocess.run([*git, "sparse-checkout", "set", "--no-cone", *entry["paths"]], check=True) subprocess.run([*git, "fetch", "-q", "--depth", "1", "--filter=blob:none", entry["url"], entry["commit"]], check=True) # fmt: skip subprocess.run([*git, "checkout", "-q", "FETCH_HEAD"], check=True) return repo_state(entry) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--verify", action="store_true", help="check only, download nothing") args = parser.parse_args() bad = 0 for entry in json.loads(REPOS.read_text(encoding="utf-8")): state = repo_state(entry) if state == "missing" and not args.verify: state = fetch_repo(entry) bad += state != "ok" print(f"{state:8} {entry['path']} @ {entry['commit'][:12]}") entries = json.loads(PINS.read_text(encoding="utf-8")) for entry in entries: state = check(entry) if state == "mismatch" and not args.verify: set_aside(ROOT / entry["path"]) state = "missing" if state == "missing" and not args.verify: state = fetch(entry) if state == "ok" and not args.verify: unpack(entry) bad += state != "ok" print(f"{state:8} {entry['path']}") print(f"{bad} problem(s) among {len(entries)} pinned files and the pinned repositories") return 1 if bad else 0 if __name__ == "__main__": sys.exit(main())