#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Fetch pinned revisions of n64brew wiki pages into reference/wiki/. The n64brew wiki (https://n64brew.dev) is CC BY-SA 4.0: its facts are used, its prose and tables are never copied into this repository (sources.md: "facts only", like the NESdev wiki). Each page is pinned by MediaWiki revision id and by the SHA-256 of that revision's wikitext, in scripts/pinned_wiki.json. python -I scripts/fetch_wiki.py # fetch what is missing, check hashes python -I scripts/fetch_wiki.py --verify # hash what is present, fetch nothing python -I scripts/fetch_wiki.py --pin # re-pin every title to its newest revision Re-pinning changes what the docs cite: do it deliberately and say so in a commit. Each page lands as reference/wiki/.wiki (the wikitext of that revision). """ from __future__ import annotations import argparse import hashlib import json import subprocess import sys import urllib.parse from pathlib import Path ROOT = Path(__file__).resolve().parents[1] PINS = ROOT / "scripts" / "pinned_wiki.json" API = "https://n64brew.dev/w/api.php" USER_AGENT = "Mozilla/5.0 (emulator reference fetch)" def api(params: dict[str, str]) -> dict: url = API + "?" + urllib.parse.urlencode({**params, "format": "json", "formatversion": "2"}) result = subprocess.run( ["curl", "-sSfL", "--max-time", "120", "-A", USER_AGENT, url], capture_output=True, check=False, ) if result.returncode: raise OSError(result.stderr.decode("utf-8", "replace").strip()) return json.loads(result.stdout) def local_path(title: str) -> Path: return ROOT / "reference" / "wiki" / (title.replace("/", "--").replace(" ", "_") + ".wiki") def sha256(text: str) -> str: return hashlib.sha256(text.encode("utf-8")).hexdigest() def by_title(title: str) -> tuple[int, str, str, str]: data = api({ "action": "query", "prop": "revisions", "titles": title, "redirects": "1", "rvprop": "ids|timestamp|content", "rvslots": "main", }) page = data["query"]["pages"][0] revision = page["revisions"][0] return revision["revid"], revision["timestamp"], page["title"], revision["slots"]["main"]["content"] def by_revision(revid: int) -> str: data = api({ "action": "query", "prop": "revisions", "revids": str(revid), "rvprop": "content", "rvslots": "main", }) return data["query"]["pages"][0]["revisions"][0]["slots"]["main"]["content"] def pin() -> int: entries = json.loads(PINS.read_text(encoding="utf-8")) for entry in entries: revid, stamp, canonical, text = by_title(entry["title"]) entry.update(title=canonical, revid=revid, timestamp=stamp, sha256=sha256(text)) path = local_path(canonical) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text, encoding="utf-8") print(f"pinned {canonical} at revision {revid} ({stamp})") PINS.write_text(json.dumps(entries, indent=1) + "\n", encoding="utf-8") return 0 def fetch(verify_only: bool) -> int: problems = 0 for entry in json.loads(PINS.read_text(encoding="utf-8")): path = local_path(entry["title"]) if path.exists(): if sha256(path.read_text(encoding="utf-8")) != entry["sha256"]: print(f"ERROR: {path.name} does not match its pin") problems += 1 continue if verify_only: print(f"missing: {path.name}") problems += 1 continue text = by_revision(entry["revid"]) if sha256(text) != entry["sha256"]: print(f"ERROR: revision {entry['revid']} of {entry['title']} does not match its pin") problems += 1 continue path.parent.mkdir(parents=True, exist_ok=True) path.write_text(text, encoding="utf-8") print(f"fetched {path.name}") return problems def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--verify", action="store_true", help="check what is present; fetch nothing") parser.add_argument("--pin", action="store_true", help="re-pin every title to its newest revision") args = parser.parse_args() if args.pin: return pin() problems = fetch(args.verify) print("all pins verified" if not problems else f"{problems} problem(s)") return 1 if problems else 0 if __name__ == "__main__": sys.exit(main())