# 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 the WSdev CPU pages to their newest revisions
Pins live in scripts/: pinned_files.json (URL, SHA-256, size), pinned_repos.json (git
URL and full commit; "sparse" limits the checkout to the listed paths) and
pinned_wiki.json (a WSdev wiki page by revision id and the SHA-256 of its wikitext,
saved as reference/wiki/
.wiki). A file whose hash does not match is moved to
trash/, never deleted. Nothing fetched is run. PDFs get a `pdftotext -layout` copy
under reference/text/.
"""
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]
PINS = ROOT / "scripts"
WIKI_API = "https://ws.nesdev.org/w/api.php"
AGENT = "Mozilla/5.0 (emulator reference fetch)"
def digest(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def move_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(url: str) -> bytes:
return subprocess.run(["curl", "-sSfL", "--max-time", "900", "-A", AGENT, url],
capture_output=True, check=True).stdout # fmt: skip
def load(name: str) -> list[dict]:
return json.loads((PINS / name).read_text(encoding="utf-8"))
def check_files(verify: bool) -> int:
bad = 0
for entry in load("pinned_files.json"):
path = ROOT / entry["path"]
ok = path.exists() and path.stat().st_size == entry["size"] and digest(path.read_bytes()) == entry["sha256"]
if not ok and not verify:
if path.exists():
move_aside(path)
data = download(entry["url"])
if digest(data) == entry["sha256"] and len(data) == entry["size"]:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
ok = True
if ok and path.suffix.lower() == ".pdf" and shutil.which("pdftotext"):
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)
bad += not ok
print(f"{'ok' if ok else 'BAD':8} {entry['path']}")
return bad
def git(path: Path, *args: str) -> subprocess.CompletedProcess:
return subprocess.run(["git", "-C", str(path), *args], capture_output=True, text=True, check=False)
def check_repos(verify: bool) -> int:
bad = 0
for entry in load("pinned_repos.json"):
path = ROOT / entry["path"]
if not (path / ".git").exists() and not verify:
path.mkdir(parents=True, exist_ok=True)
git(path, "init", "-q")
extra = []
if entry.get("sparse"):
git(path, "sparse-checkout", "set", "--no-cone", *entry["sparse"])
extra = ["--filter=blob:none"]
git(path, "fetch", "-q", "--depth", "1", *extra, entry["url"], entry["commit"])
git(path, "checkout", "-q", "FETCH_HEAD")
ok = (path / ".git").exists() and git(path, "rev-parse", "HEAD").stdout.strip() == entry["commit"]
bad += not ok
print(f"{'ok' if ok else 'BAD':8} {entry['path']} @ {entry['commit'][:12]}")
return bad
def wiki_query(params: dict[str, str]) -> dict:
query = urllib.parse.urlencode({**params, "action": "query", "prop": "revisions",
"rvprop": "ids|timestamp|content", "rvslots": "main",
"format": "json", "formatversion": "2"}) # fmt: skip
return json.loads(download(WIKI_API + "?" + query))["query"]["pages"][0]["revisions"][0]
def wiki_file(title: str) -> Path:
return ROOT / "reference" / "wiki" / (title.replace("/", "__").replace(" ", "_") + ".wiki")
def check_wiki(verify: bool) -> int:
bad = 0
for entry in load("pinned_wiki.json"):
path = wiki_file(entry["title"])
ok = path.exists() and digest(path.read_bytes()) == entry["sha256"]
if not ok and not verify:
if path.exists():
move_aside(path)
data = wiki_query({"revids": str(entry["revid"])})["slots"]["main"]["content"].encode("utf-8")
if digest(data) == entry["sha256"]:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
ok = True
bad += not ok
print(f"{'ok' if ok else 'BAD':8} wiki {entry['title']} r{entry['revid']}")
return bad
def pin_wiki() -> int:
entries = load("pinned_wiki.json")
for entry in entries:
revision = wiki_query({"titles": entry["title"]})
entry.update(revid=revision["revid"], timestamp=revision["timestamp"],
sha256=digest(revision["slots"]["main"]["content"].encode("utf-8"))) # fmt: skip
print(f"pinned {entry['title']} r{entry['revid']} {entry['timestamp']}")
(PINS / "pinned_wiki.json").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 = check_repos(args.verify) + check_files(args.verify) + check_wiki(args.verify)
print(f"{bad} problem(s)")
return 1 if bad else 0
if __name__ == "__main__":
sys.exit(main())