# 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, SHA-256s and commits only scripts/pinned_files.json names, per file, a URL, a SHA-256 and a size; a file is kept only if both match, and a mismatch is moved to trash/ (never deleted). scripts/pinned_repos.json names, per repository, a full commit SHA and an optional sparse-checkout pattern list; the checkout is shallow, at exactly that commit, and limited to the patterns (so firmware and disk images a repository carries never land here). Nothing fetched is executed. PDFs and HTML pages are turned into text under reference/text/ for grepping. """ from __future__ import annotations import argparse import hashlib import html import json import re import shutil import subprocess import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] FILES = ROOT / "scripts" / "pinned_files.json" REPOS = ROOT / "scripts" / "pinned_repos.json" TEXT = ROOT / "reference" / "text" def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: while block := handle.read(1 << 20): digest.update(block) return digest.hexdigest() 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), str(trash / path.name)) def file_state(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 download(entry: dict) -> str: path = ROOT / entry["path"] path.parent.mkdir(parents=True, exist_ok=True) part = path.with_name(path.name + ".part") command = ["curl", "-sS", "-L", "--fail", "-m", "1200", "-o", str(part), entry["url"]] subprocess.run(command, check=True) part.replace(path) state = file_state(entry) if state != "ok": set_aside(path) return state def to_text(entry: dict) -> None: path = ROOT / entry["path"] out = TEXT / (path.stem + ".txt") if out.exists(): return TEXT.mkdir(parents=True, exist_ok=True) if path.suffix == ".pdf" and shutil.which("pdftotext"): subprocess.run(["pdftotext", "-layout", str(path), str(out)], check=False) elif path.suffix == ".html": page = path.read_text(encoding="utf-8", errors="replace") page = re.sub(r"|", "", page, flags=re.S) page = html.unescape(re.sub(r"<[^>]+>", "", page)) out.write_text(re.sub(r"\n\s*\n+", "\n", page), encoding="utf-8") 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() return "ok" if head == entry["commit"] else "mismatch" def checkout(entry: dict) -> str: """A shallow checkout of exactly the pinned commit, sparse if the pin says so.""" 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("sparse"): subprocess.run([*git, "config", "core.sparseCheckout", "true"], check=True) info = path / ".git" / "info" info.mkdir(parents=True, exist_ok=True) (info / "sparse-checkout").write_text("\n".join(entry["sparse"]) + "\n", encoding="utf-8") subprocess.run([*git, "fetch", "-q", "--depth", "1", entry["url"], entry["commit"]], check=True) 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 repos = json.loads(REPOS.read_text(encoding="utf-8")) for entry in repos: state = repo_state(entry) if state == "missing" and not args.verify: state = checkout(entry) bad += state != "ok" print(f"{state:8} {entry['path']} @ {entry['commit'][:12]}") files = json.loads(FILES.read_text(encoding="utf-8")) for entry in files: state = file_state(entry) if state == "mismatch" and not args.verify: set_aside(ROOT / entry["path"]) state = "missing" if state == "missing" and not args.verify: state = download(entry) if state == "ok": to_text(entry) else: bad += 1 print(f"{state:8} {entry['path']}") print(f"{bad} problem(s) among {len(files)} pinned files and {len(repos)} pinned repositories") return 1 if bad else 0 if __name__ == "__main__": sys.exit(main())