# 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, then check python -I scripts/fetch_references.py --verify # check only, download nothing python -I scripts/fetch_references.py --pin-wiki # re-pin every WSdev page to its newest revision Three kinds of pin, each in its own JSON file under scripts/: - pinned_files.json: 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. - pinned_repos.json: a git URL and a full commit SHA, checked out shallow. An entry with "sparse" lists the only paths checked out (a blobless clone plus a sparse checkout, so nothing outside those paths, firmware above all, is ever written). - pinned_wiki.json: a WSdev wiki page by MediaWiki revision id and the SHA-256 of that revision's wikitext, saved as reference/wiki/.wiki. Nothing fetched is executed. PDFs are turned into text (`pdftotext -layout`) under reference/text/ for grepping. Re-pinning the wiki changes what the documents cite: do it deliberately and say so in a commit. """ from __future__ import annotations import argparse import hashlib import json import shutil import subprocess import sys import time import urllib.parse from pathlib import Path ROOT = Path(__file__).resolve().parents[1] FILES = ROOT / "scripts" / "pinned_files.json" REPOS = ROOT / "scripts" / "pinned_repos.json" WIKI = ROOT / "scripts" / "pinned_wiki.json" WIKI_API = "https://ws.nesdev.org/w/api.php" AGENT = "Mozilla/5.0 (emulator reference fetch)" def sha256_bytes(data: bytes) -> str: return hashlib.sha256(data).hexdigest() def sha256_file(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 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 curl(url: str, out: Path | None = None) -> bytes: command = ["curl", "-sSfL", "--max-time", "900", "-A", AGENT, url] if out is not None: command[1:1] = ["-o", str(out)] return subprocess.run(command, capture_output=True, check=True).stdout # Files ------------------------------------------------------------------------------- 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_file(path) != entry["sha256"]: return "mismatch" return "ok" def to_text(path: Path) -> None: if path.suffix.lower() != ".pdf" or shutil.which("pdftotext") is None: return text = ROOT / "reference" / "text" / (path.stem + ".txt") if not text.exists(): text.parent.mkdir(parents=True, exist_ok=True) subprocess.run(["pdftotext", "-layout", str(path), str(text)], check=False) def files(verify: bool) -> int: bad = 0 for entry in json.loads(FILES.read_text(encoding="utf-8")): path = ROOT / entry["path"] state = file_state(entry) if state == "mismatch" and not verify: set_aside(path) state = "missing" if state == "missing" and not verify: path.parent.mkdir(parents=True, exist_ok=True) part = path.with_name(path.name + ".part") curl(entry["url"], part) part.replace(path) state = file_state(entry) if state != "ok": set_aside(path) if state == "ok": to_text(path) bad += state != "ok" print(f"{state:8} {entry['path']}") return bad # Repositories ------------------------------------------------------------------------ def git(path: Path, *args: str) -> subprocess.CompletedProcess: return subprocess.run(["git", "-C", str(path), *args], capture_output=True, text=True, check=False) def repo_state(entry: dict) -> str: path = ROOT / entry["path"] if not (path / ".git").exists(): return "missing" return "ok" if git(path, "rev-parse", "HEAD").stdout.strip() == entry["commit"] else "mismatch" def fetch_repo(entry: dict) -> str: path = ROOT / entry["path"] path.mkdir(parents=True, exist_ok=True) git(path, "init", "-q") git(path, "remote", "add", "origin", entry["url"]) sparse = entry.get("sparse") if sparse: git(path, "sparse-checkout", "set", "--no-cone", *sparse) fetch = git(path, "fetch", "-q", "--depth", "1", "--filter=blob:none", "origin", entry["commit"]) else: fetch = git(path, "fetch", "-q", "--depth", "1", "origin", entry["commit"]) if fetch.returncode != 0: print(fetch.stderr.strip(), file=sys.stderr) return "failed" git(path, "checkout", "-q", "FETCH_HEAD") return repo_state(entry) def repos(verify: bool) -> int: 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 # WSdev wiki -------------------------------------------------------------------------- def wiki_api(params: dict[str, str]) -> dict: query = urllib.parse.urlencode({**params, "format": "json", "formatversion": "2"}) return json.loads(curl(WIKI_API + "?" + query)) def wiki_path(title: str) -> Path: return ROOT / "reference" / "wiki" / (title.replace("/", "__").replace(" ", "_") + ".wiki") def wiki_text(revid: int) -> tuple[str, str]: data = wiki_api({"action": "query", "prop": "revisions", "revids": str(revid), "rvprop": "content|timestamp|ids", "rvslots": "main"}) # fmt: skip revision = data["query"]["pages"][0]["revisions"][0] return revision["slots"]["main"]["content"], revision["timestamp"] def wiki(verify: bool) -> int: bad = 0 for entry in json.loads(WIKI.read_text(encoding="utf-8")): path = wiki_path(entry["title"]) state = "missing" if path.exists(): state = "ok" if sha256_bytes(path.read_bytes()) == entry["sha256"] else "mismatch" if state == "mismatch" and not verify: set_aside(path) state = "missing" if state == "missing" and not verify: text, _ = wiki_text(entry["revid"]) data = text.encode("utf-8") if sha256_bytes(data) == entry["sha256"]: path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(data) state = "ok" else: state = "mismatch" bad += state != "ok" print(f"{state:8} wiki {entry['title']} r{entry['revid']}") return bad def pin_wiki() -> int: entries = json.loads(WIKI.read_text(encoding="utf-8")) for entry in entries: data = wiki_api({"action": "query", "prop": "revisions", "titles": entry["title"], "rvprop": "ids|timestamp|content", "rvslots": "main"}) # fmt: skip revision = data["query"]["pages"][0]["revisions"][0] entry["revid"] = revision["revid"] entry["timestamp"] = revision["timestamp"] entry["sha256"] = sha256_bytes(revision["slots"]["main"]["content"].encode("utf-8")) print(f"pinned {entry['title']} r{entry['revid']} {entry['timestamp']}") WIKI.write_text(json.dumps(entries, indent=1) + "\n", encoding="utf-8") return 0 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("--pin-wiki", action="store_true", help="re-pin the wiki pages") args = parser.parse_args() if args.pin_wiki: return pin_wiki() bad = repos(args.verify) + files(args.verify) + wiki(args.verify) print(f"{bad} problem(s)") return 1 if bad else 0 if __name__ == "__main__": sys.exit(main())