# 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 python -I scripts/fetch_references.py --record # first pinning: fill in empty pins 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. A zip is unpacked beside itself (reference///) once it verifies, and PDFs are turned into text (`pdftotext -layout`) under reference/text/. Every entry of scripts/pinned_repos.json is a partial clone (`--filter=blob:none`) at its full commit with a sparse checkout of the listed paths only, so blobs outside them are never downloaded. Nothing fetched is executed. """ from __future__ import annotations import argparse import hashlib import json import shutil import subprocess import sys import time import zipfile 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 not entry.get("sha256"): return "unpinned" 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 download(entry: dict) -> None: 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", "-A", "Mozilla/5.0 (reference fetch)", "-o", str(part), entry["url"]], check=True, ) # fmt: skip part.replace(path) def unpack(entry: dict) -> None: """Unpack a verified zip into a folder named after it; text-convert every PDF.""" path = ROOT / entry["path"] pdfs = [path] if path.suffix == ".pdf" else [] if path.suffix == ".zip": folder = path.with_suffix("") if not folder.exists(): with zipfile.ZipFile(path) as archive: for member in archive.infolist(): if Path(member.filename).name in entry.get("skip", ()): continue # firmware or programs of the maker's: never unpacked target = (folder / member.filename).resolve() if folder.resolve() not in target.parents and target != folder.resolve(): continue # a member escaping its folder is skipped, never written archive.extract(member, folder) pdfs = sorted(folder.rglob("*.pdf")) + sorted(folder.rglob("*.PDF")) if shutil.which("pdftotext") is None: return for pdf in pdfs: text = ROOT / "reference" / "text" / (pdf.stem + ".txt") if not text.exists(): text.parent.mkdir(parents=True, exist_ok=True) subprocess.run(["pdftotext", "-layout", str(pdf), str(text)], check=False) 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 blobless partial clone of exactly the pinned commit, sparse to the listed paths.""" path = ROOT / entry["path"] path.mkdir(parents=True, exist_ok=True) git = ["git", "-C", str(path)] subprocess.run([*git, "init", "-q"], check=True) subprocess.run([*git, "remote", "add", "origin", entry["url"]], check=True) subprocess.run([*git, "config", "remote.origin.promisor", "true"], check=True) subprocess.run([*git, "config", "remote.origin.partialclonefilter", "blob:none"], check=True) subprocess.run([*git, "sparse-checkout", "set", "--no-cone", *entry["sparse"]], check=True) subprocess.run([*git, "fetch", "-q", "--depth", "1", "--filter=blob:none", "origin", entry["commit"]], check=True) # fmt: skip subprocess.run([*git, "checkout", "-q", "FETCH_HEAD"], check=True) return repo_state(entry) def repos(verify: bool) -> int: if not REPOS.exists(): return 0 bad = 0 for entry in json.loads(REPOS.read_text(encoding="utf-8")): state = repo_state(entry) if state == "missing" and not verify: state = fetch_repo(entry) bad += state != "ok" print(f"{state:8} {entry['path']} @ {entry['commit'][:12]}") return bad def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--verify", action="store_true", help="check only, download nothing") parser.add_argument("--record", action="store_true", help="fill in empty pins after download") args = parser.parse_args() entries = json.loads(PINS.read_text(encoding="utf-8")) bad = repos(args.verify) recorded = 0 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: download(entry) state = check(entry) if state == "mismatch": set_aside(ROOT / entry["path"]) if state == "unpinned" and args.record: path = ROOT / entry["path"] entry["sha256"], entry["size"] = sha256(path), path.stat().st_size recorded += 1 state = "ok" if state == "ok": unpack(entry) else: bad += 1 print(f"{state:8} {entry['path']}") if recorded: PINS.write_text(json.dumps(entries, indent=1, ensure_ascii=False) + "\n", encoding="utf-8") print(f"recorded {recorded} new pin(s) in {PINS.relative_to(ROOT)}") 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())