diff --git a/scripts/acquire/__init__.py b/scripts/acquire/__init__.py new file mode 100644 index 000000000..2d4d5ea5b --- /dev/null +++ b/scripts/acquire/__init__.py @@ -0,0 +1 @@ +"""Acquisition: dump-catalog coverage, dumps a held file already contains, and the searches that find a missing file.""" diff --git a/scripts/derivations.py b/scripts/acquire/derivations.py similarity index 100% rename from scripts/derivations.py rename to scripts/acquire/derivations.py diff --git a/scripts/acquire/embedded.py b/scripts/acquire/embedded.py new file mode 100644 index 000000000..72432a1c1 --- /dev/null +++ b/scripts/acquire/embedded.py @@ -0,0 +1,67 @@ +"""A file stored inside others, found at any offset by a rolling crc32.""" + +from __future__ import annotations + +import sys +import zipfile +import zlib +from collections.abc import Iterator +from pathlib import Path + + +_POLY = 0xEDB88320 +_TABLE = [] +for _byte in range(256): + _value = _byte + for _ in range(8): + _value = (_value >> 1) ^ _POLY if _value & 1 else _value >> 1 + _TABLE.append(_value) + + +def _raw(data: bytes) -> int: + """The crc32 register over data, from 0 and without the final xor: a + linear function, which is what lets the window roll.""" + register = 0 + for byte in data: + register = (register >> 8) ^ _TABLE[(register ^ byte) & 0xFF] + return register + + +def offsets(data: bytes, crc32: int, size: int) -> list[int]: + """Every offset where data[offset:offset + size] has this zlib crc32.""" + if size <= 0 or len(data) < size: + return [] + # zlib's crc32 of a window is the linear register xor a constant that + # depends on the length alone: the crc32 of as many zero bytes. + target = crc32 ^ zlib.crc32(bytes(size)) + leaving = [_raw(bytes([byte]) + bytes(size)) for byte in range(256)] + table = _TABLE + register = _raw(data[:size]) + found = [0] if register == target else [] + for start in range(len(data) - size): + register = ((register >> 8) ^ table[(register ^ data[start + size]) & 0xFF] + ^ leaving[data[start]]) + if register == target: + found.append(start + 1) + return found + + +def sources(paths: list[Path]) -> Iterator[tuple[str, bytes]]: + """(label, bytes) of each file under paths, and of each ZIP member.""" + for path in paths: + files = sorted(p for p in path.rglob("*") if p.is_file()) if path.is_dir() else [path] + for file in files: + try: + data = file.read_bytes() + except OSError as exc: + print(f" {file}: not read ({exc.strerror or exc})", file=sys.stderr) + continue + yield str(file), data + if zipfile.is_zipfile(file): + try: + with zipfile.ZipFile(file) as archive: + for info in archive.infolist(): + if not info.is_dir(): + yield f"{file}!{info.filename}", archive.read(info) + except (zipfile.BadZipFile, OSError, RuntimeError, NotImplementedError) as exc: + print(f" {file}: members not read ({exc})", file=sys.stderr) diff --git a/scripts/acquire/fetch.py b/scripts/acquire/fetch.py new file mode 100644 index 000000000..a5272efef --- /dev/null +++ b/scripts/acquire/fetch.py @@ -0,0 +1,577 @@ +"""The searches for a missing file: the database, old branches, public repositories, Software Heritage, archive.org.""" + +from __future__ import annotations + +import hashlib +import http.client +import json +import os +import re +import subprocess +import sys +import urllib.error +import urllib.parse +import urllib.request +from pathlib import Path + + +MAX_DOWNLOAD = 100 * 1024 * 1024 # 100MB per file + +LEGACY_BRANCHES = ["libretro", "RetroArch", "RetroPie", "Recalbox", "batocera", "Other"] + +PUBLIC_REPOS = [ + # archtaurus/RetroPieBIOS - most complete verified collection + "https://raw.githubusercontent.com/archtaurus/RetroPieBIOS/master/BIOS/{name}", + "https://raw.githubusercontent.com/archtaurus/RetroPieBIOS/master/BIOS/pcsx2/bios/{name}", + "https://raw.githubusercontent.com/archtaurus/RetroPieBIOS/master/BIOS/ep128emu/roms/{name}", + "https://raw.githubusercontent.com/archtaurus/RetroPieBIOS/master/BIOS/fuse/{name}", + # prefetchnta/retroarch-bios - alternative verified collection + "https://raw.githubusercontent.com/prefetchnta/retroarch-bios/main/system/{name}", + "https://raw.githubusercontent.com/prefetchnta/retroarch-bios/main/system/pcsx2/bios/{name}", + # BatoceraPLUS - Batocera-specific + "https://raw.githubusercontent.com/BatoceraPLUS/Batocera.PLUS-bios/main/{name}", +] + +# Software Heritage archives the source of every public forge, deleted +# repositories and rewritten histories included, and finds a file by its +# hash: a ROM once committed anywhere answers here even when no forge still +# serves it. Anonymous use allows 120 requests an hour. +SOFTWARE_HERITAGE = "https://archive.softwareheritage.org/api/1/content" + +ARCHIVE_ORG_COLLECTIONS = [ + "RetroarchSystemFiles", + "retroarch_bios", + "retroarch-ultimate-bios-pack_20250824", + "system_20240621", + "full-pack-bios-batocera-39", +] + + +def find_missing(config: dict, db: dict) -> list[dict]: + """Files the platform's own check or its cores' code would not find. + + Read from verify, the platform's native check: a hash or name lookup + of our own called pc6001.zip and fmtowns.zip missing on Batocera, which + checks them inside the zip and holds them, and saw none of the files + the cores need that no platform lists. + """ + from resolve.nativemode import reads_file_contents + from packs.verdicts import Status + from packs.coverage import verify_platform + + result = verify_platform(config, db) + hashed = reads_file_contents(config.get("verification_mode", "existence")) + wanted = { + (d.get("system", ""), d.get("name", "")) + for d in result["details"] + if d["status"] == Status.MISSING or (hashed and d["status"] == Status.UNTESTED) + } + missing: list[dict] = [] + for sys_id, system in config.get("systems", {}).items(): + for file_entry in system.get("files", []): + name = file_entry.get("name", "") + if (sys_id, name) not in wanted: + continue + if file_entry.get("storage", "embedded") != "embedded": + continue + missing.append({ + "name": name, + "system": sys_id, + "sha1": file_entry.get("sha1"), + "md5": file_entry.get("md5"), + "sha256": file_entry.get("sha256"), + "crc32": file_entry.get("crc32"), + "size": file_entry.get("size"), + "destination": file_entry.get("destination", name), + }) + for u in result["undeclared_files"]: + # A file installed with its emulator is not an acquisition target: + # verify leaves it out of the missing count, and bundled_only.py + # --strict refuses a copy that only bundled entries reach. + if u.get("in_repo") or not u.get("required") or u.get("bundled"): + continue + missing.append({ + "name": u["name"], + "system": u.get("system") or "", + "sha1": u.get("sha1"), + "md5": u.get("md5"), + "sha256": u.get("sha256"), + "crc32": u.get("crc32"), + "size": u.get("size"), + "destination": u.get("path") or u["name"], + "emulator": u.get("emulator", ""), + }) + return missing + + +def _accepted(entry: dict, field: str) -> set[str]: + """Every value an entry accepts for a hash field. + + A profile lists several revisions as a YAML list (daedalusx64's + n64.psh), a platform as a comma-separated string. Read as one value, + the list stopped the run with an unhashable-type error. + """ + value = entry.get(field) + values = value if isinstance(value, list) else str(value or "").split(",") + return {str(v).strip().lower() for v in values if str(v).strip()} + + +def _crc32s(entry: dict) -> set[str]: + return {value.removeprefix("0x").zfill(8) for value in _accepted(entry, "crc32")} + + +def _size(entry: dict) -> int | None: + try: + return int(entry["size"]) if entry.get("size") is not None else None + except (TypeError, ValueError): + return None + + +CRYPTO_HASHES = ( + ("sha256", hashlib.sha256), + ("sha1", hashlib.sha1), + ("md5", hashlib.md5), +) + + +def verifiable(entry: dict) -> bool: + """Whether a network download can be proved to be this file. + + Only a cryptographic hash proves it. A crc32 and a size can be met by + crafted bytes, so they identify a file the database already holds + (step 1) and never accept one a remote source serves. + """ + return any(_accepted(entry, field) for field, _digest in CRYPTO_HASHES) + + +def verify_content(data: bytes, expected: dict) -> bool: + """Whether downloaded bytes match every cryptographic hash declared. + + Each declared field must hold the bytes' digest among its accepted + values. An entry declaring none is refused. + """ + declared = [ + (accepted, digest) + for field, digest in CRYPTO_HASHES + for accepted in [_accepted(expected, field)] + if accepted + ] + return bool(declared) and all( + digest(data).hexdigest() in accepted for accepted, digest in declared + ) + + +def _read_limited( + resp: http.client.HTTPResponse, limit: int = MAX_DOWNLOAD +) -> bytes | None: + """Read response up to limit bytes. Returns None if exceeded.""" + data = resp.read(limit + 1) + if len(data) > limit: + return None + return data + + +def step1_crossref_db(entry: dict, db: dict) -> str | None: + """Check if file exists under different name/path in database.""" + files = db.get("files", {}) + for sha1 in sorted(_accepted(entry, "sha1")): + if sha1 in files: + return files[sha1]["path"] + indexes = db.get("indexes", {}) + for field, index in (("sha256", "by_sha256"), ("md5", "by_md5")): + by_hash = indexes.get(index, {}) + for value in sorted(_accepted(entry, field)): + sha1_match = by_hash.get(value) + if sha1_match and sha1_match in files: + return files[sha1_match]["path"] + size = _size(entry) + if size is not None: + by_crc32 = indexes.get("by_crc32", {}) + for crc in sorted(_crc32s(entry)): + sha1_match = by_crc32.get(crc) + if sha1_match in files and files[sha1_match].get("size") == size: + return files[sha1_match]["path"] + return None + + +def step2_scan_branches(entry: dict) -> bytes | None: + """Search old git branches for the file by hash.""" + name = entry["name"] + + for branch in LEGACY_BRANCHES: + ref = f"origin/{branch}" + try: + subprocess.run( + ["git", "rev-parse", "--verify", ref], + capture_output=True, + check=True, + ) + except subprocess.CalledProcessError: + continue + + result = subprocess.run( + ["git", "ls-tree", "-r", "--name-only", ref], + capture_output=True, + text=True, + check=False, + ) + + for filepath in result.stdout.strip().split("\n"): + if os.path.basename(filepath) == name: + try: + blob = subprocess.run( + ["git", "show", f"{ref}:{filepath}"], + capture_output=True, + check=True, + ) + if verify_content(blob.stdout, entry): + return blob.stdout + except subprocess.CalledProcessError: + continue + + return None + + +# Sources that did not answer during the current file's search. A 404 is an +# answer, the file is not there. Anything else leaves the question open: an +# offline run used to report every file as needing a community contribution. +_UNANSWERED: list[str] = [] + + +def _unanswered(url: str, exc: Exception) -> None: + if isinstance(exc, urllib.error.HTTPError) and exc.code == 404: + return + _UNANSWERED.append(f"{url}: {exc}") + + +def step3_search_public_repos(entry: dict) -> bytes | None: + """Search public GitHub BIOS repos.""" + name = entry["name"] + destination = entry.get("destination", name) + + for url_template in PUBLIC_REPOS: + url = url_template.format(name=name) + try: + req = urllib.request.Request( + url, headers={"User-Agent": "retrobios-fetch/1.0"} + ) + with urllib.request.urlopen(req, timeout=30) as resp: + data = _read_limited(resp) + if data is None: + continue + if verify_content(data, entry): + return data + except urllib.error.URLError as exc: + _unanswered(url, exc) + continue + + if "/" in destination: + url = url_template.format(name=destination) + try: + req = urllib.request.Request( + url, headers={"User-Agent": "retrobios-fetch/1.0"} + ) + with urllib.request.urlopen(req, timeout=30) as resp: + data = _read_limited(resp) + if data is None: + continue + if verify_content(data, entry): + return data + except urllib.error.URLError as exc: + _unanswered(url, exc) + continue + + return None + + +def step3b_software_heritage(entry: dict) -> bytes | None: + """Ask Software Heritage for the file by each accepted sha1, then + sha256: its archive answers by content, whatever the file was named.""" + for field in ("sha1", "sha256"): + for value in sorted(_accepted(entry, field)): + url = f"{SOFTWARE_HERITAGE}/{field}:{value}/raw/" + try: + req = urllib.request.Request( + url, headers={"User-Agent": "retrobios-fetch/1.0"} + ) + with urllib.request.urlopen(req, timeout=60) as resp: + data = _read_limited(resp) + except urllib.error.URLError as exc: + _unanswered(url, exc) + continue + if data is not None and verify_content(data, entry): + return data + return None + + +def step4_search_archive_org(entry: dict) -> bytes | None: + """Search archive.org firmware collections by direct download.""" + name = entry["name"] + + for collection_id in ARCHIVE_ORG_COLLECTIONS: + for path in [name, f"system/{name}", f"bios/{name}"]: + url = f"https://archive.org/download/{collection_id}/{path}" + try: + req = urllib.request.Request( + url, headers={"User-Agent": "retrobios-fetch/1.0"} + ) + with urllib.request.urlopen(req, timeout=30) as resp: + data = _read_limited(resp) + if data is None: + continue + if verify_content(data, entry): + return data + except urllib.error.URLError as exc: + _unanswered(url, exc) + continue + + sha1s = sorted(_accepted(entry, "sha1")) + if not sha1s: + return None + # Each accepted revision is a query of its own: archive.org matches one. + sha1 = " OR ".join(f"sha1:{value}" for value in sha1s) + + search_url = ( + "https://archive.org/advancedsearch.php?q=" + f"{urllib.parse.quote(sha1)}&output=json&rows=1" + ) + + try: + req = urllib.request.Request( + search_url, headers={"User-Agent": "retrobios-fetch/1.0"} + ) + with urllib.request.urlopen(req, timeout=30) as resp: + result = json.loads(resp.read()) + docs = result.get("response", {}).get("docs", []) + if docs: + identifier = docs[0].get("identifier") + if identifier: + dl_url = f"https://archive.org/download/{identifier}/{name}" + try: + req2 = urllib.request.Request( + dl_url, headers={"User-Agent": "retrobios-fetch/1.0"} + ) + with urllib.request.urlopen(req2, timeout=30) as resp2: + data = _read_limited(resp2) + if data is not None and verify_content(data, entry): + return data + except urllib.error.URLError as exc: + _unanswered(dl_url, exc) + except (urllib.error.URLError, json.JSONDecodeError) as exc: + _unanswered(search_url, exc) + + return None + + +def place_file(data: bytes, entry: dict, bios_dir: str, db: dict) -> str: + """Place a fetched BIOS file in the correct location.""" + name = os.path.basename(entry["name"]) + system = entry["system"] + + dest_dir = Path(bios_dir) + + # Every part of the slug, not any: matching "nintendo" alone filed the + # N64's n64.psh under the first Nintendo folder walked, the SNES one. + parts = [part for part in system.lower().split("-") if len(part) > 1] + matches = sorted( + (len(f"{manufacturer_dir.name}/{console_dir.name}"), str(console_dir), console_dir) + for manufacturer_dir in dest_dir.iterdir() if manufacturer_dir.is_dir() + for console_dir in manufacturer_dir.iterdir() if console_dir.is_dir() + and all( + part in f"{manufacturer_dir.name}/{console_dir.name}".lower() + for part in parts + ) + ) + folder = matches[0][2] if matches else dest_dir / "Unknown" / system + dest = folder / name + if dest.exists() and dest.read_bytes() != data: + # Another revision under the same name: the collection keeps it + # beside, never in place of, the file already there. + dest = folder / ".variants" / f"{name}.{hashlib.sha1(data).hexdigest()[:8]}" + dest.parent.mkdir(parents=True, exist_ok=True) + with open(dest, "wb") as f: + f.write(data) + return str(dest) + + +def fetch_missing( + missing: list[dict], + db: dict, + bios_dir: str, + dry_run: bool = False, +) -> dict: + """Run the 5-step auto-fetch pipeline for missing files.""" + stats = {"found": 0, "not_found": 0, "errors": 0, "unverifiable": 0} + still_missing = [] + + for entry in missing: + name = entry["name"] + _UNANSWERED.clear() + print(f"\n Searching: {name} ({entry['system']})") + + existing = step1_crossref_db(entry, db) + if existing: + print(f" [1] Found in database at: {existing}") + stats["found"] += 1 + continue + + if not verifiable(entry): + # Searched, a file of that name could only ever be refused. + print(" [-] Cannot be verified from the network: declares no " + "cryptographic hash. Not searched, nothing written") + still_missing.append(entry) + stats["unverifiable"] += 1 + continue + + if dry_run: + print(" [DRY RUN] Would search branches, repos, Software Heritage, archive.org") + still_missing.append(entry) + stats["not_found"] += 1 + continue + + data = step2_scan_branches(entry) + if data: + path = place_file(data, entry, bios_dir, db) + print(f" [2] Found in branch, saved to: {path}") + stats["found"] += 1 + continue + + data = step3_search_public_repos(entry) + if data: + path = place_file(data, entry, bios_dir, db) + print(f" [3] Found in public repo, saved to: {path}") + stats["found"] += 1 + continue + + data = step3b_software_heritage(entry) + if data: + path = place_file(data, entry, bios_dir, db) + print(f" [3b] Found in Software Heritage, saved to: {path}") + stats["found"] += 1 + continue + + data = step4_search_archive_org(entry) + if data: + path = place_file(data, entry, bios_dir, db) + print(f" [4] Found on archive.org, saved to: {path}") + stats["found"] += 1 + continue + + if _UNANSWERED: + # Not looked for everywhere: no issue asks the community for it. + print( + f" [5] Search incomplete, {len(_UNANSWERED)} source(s) did not " + f"answer (first: {_UNANSWERED[0]})" + ) + stats["errors"] += 1 + continue + print(" [5] Not found, open for contributions") + still_missing.append(entry) + stats["not_found"] += 1 + + return {"stats": stats, "still_missing": still_missing} + + +ACQUIRE_DIR = Path("tmp") / "acquire" + + +def lookup_sha1s(sha1s: list[str], db: dict, dry_run: bool = False) -> int: + """--sha1: each file looked for by its hash alone, without a platform. + Found bytes are verified, then saved as tmp/acquire/, never into + bios/: placing a file is a decision the collection makes. 0 when every + one was found, 1 otherwise.""" + missing = 0 + for raw in sha1s: + sha1 = raw.strip().lower() + if not re.fullmatch(r"[0-9a-f]{40}", sha1): + print(f" {raw}: not a sha1", file=sys.stderr) + missing += 1 + continue + entry = {"name": sha1, "sha1": sha1, "system": ""} + _UNANSWERED.clear() + held = step1_crossref_db(entry, db) + if held: + print(f" {sha1}: already held at {held}") + continue + if dry_run: + print(f" {sha1}: would ask Software Heritage and archive.org") + continue + data = step3b_software_heritage(entry) + where = "Software Heritage" + if data is None: + data, where = _archive_org_by_sha1(sha1), "archive.org" + if data is None: + note = f", {len(_UNANSWERED)} source(s) did not answer" if _UNANSWERED else "" + print(f" {sha1}: not found{note}") + missing += 1 + continue + ACQUIRE_DIR.mkdir(parents=True, exist_ok=True) + out = ACQUIRE_DIR / sha1 + out.write_bytes(data) + print(f" {sha1}: found in {where}, {len(data)} bytes, saved to {out}") + return 1 if missing else 0 + + +def _archive_org_by_sha1(sha1: str) -> bytes | None: + """The first archive.org file whose metadata names sha1, read and checked.""" + search = ("https://archive.org/advancedsearch.php?q=" + f"{urllib.parse.quote(f'sha1:{sha1}')}&fl[]=identifier&output=json&rows=5") + try: + with urllib.request.urlopen(urllib.request.Request( + search, headers={"User-Agent": "retrobios-fetch/1.0"}), timeout=30) as resp: + docs = json.loads(resp.read()).get("response", {}).get("docs", []) + except (urllib.error.URLError, json.JSONDecodeError) as exc: + _unanswered(search, exc) + return None + for doc in docs: + identifier = doc.get("identifier") + meta = f"https://archive.org/metadata/{identifier}/files" + try: + with urllib.request.urlopen(urllib.request.Request( + meta, headers={"User-Agent": "retrobios-fetch/1.0"}), timeout=30) as resp: + files = json.loads(resp.read()).get("result", []) + except (urllib.error.URLError, json.JSONDecodeError) as exc: + _unanswered(meta, exc) + continue + for item in files: + if str(item.get("sha1", "")).lower() != sha1: + continue + url = (f"https://archive.org/download/{identifier}/" + f"{urllib.parse.quote(item['name'])}") + try: + with urllib.request.urlopen(urllib.request.Request( + url, headers={"User-Agent": "retrobios-fetch/1.0"}), timeout=60) as resp: + data = _read_limited(resp) + except urllib.error.URLError as exc: + _unanswered(url, exc) + continue + if data is not None and hashlib.sha1(data).hexdigest() == sha1: + return data + return None + + +CONTRIBUTING_URL = "https://github.com/Abdess/retrobios/blob/main/CONTRIBUTING.md" + + +def generate_issue_body(missing: list[dict], platform: str) -> str: + """An issue body for the files a platform still needs. + + The hashes are written in full: a contributor matches a file against + them, and a 12-character prefix confirms nothing. + """ + lines = [ + f"## Files {platform} still needs", + "", + "| File | System | SHA1 | MD5 |", + "|------|--------|------|-----|", + ] + for entry in missing: + sha1 = ", ".join(f"`{h}`" for h in sorted(_accepted(entry, "sha1"))) or "none declared" + md5 = ", ".join(f"`{h}`" for h in sorted(_accepted(entry, "md5"))) or "none declared" + lines.append(f"| `{entry['name']}` | {entry['system']} | {sha1} | {md5} |") + lines += [ + "", + "A file with one of these hashes can be added through the upload link in" + f" [CONTRIBUTING.md]({CONTRIBUTING_URL}). CI checks it on arrival.", + ] + return "\n".join(lines) diff --git a/scripts/acquire/history.py b/scripts/acquire/history.py new file mode 100644 index 000000000..acdfd3035 --- /dev/null +++ b/scripts/acquire/history.py @@ -0,0 +1,53 @@ +"""The upstream revision whose copy of a file has a pinned md5, found by walking the file's history.""" + +from __future__ import annotations + +import hashlib +import urllib.parse + +from core import upstream + + +# Commits listed per page and the most pages walked: a data file older than +# 2 000 commits on its own path is not one a platform list still pins. +PER_PAGE = 100 +MAX_PAGES = 20 + + +def _history_url(repo: upstream.Repo, path: str, page: int) -> str: + quoted = urllib.parse.quote(path) + if repo.family == "gitlab": + project = urllib.parse.quote(repo.slug, safe="") + return (f"{repo.api_base}/projects/{project}/repository/commits" + f"?path={quoted}&per_page={PER_PAGE}&page={page}") + if repo.family == "github": + return (f"{repo.api_base}/repos/{repo.slug}/commits" + f"?path={quoted}&per_page={PER_PAGE}&page={page}") + return (f"{repo.api_base}/repos/{repo.slug}/commits" + f"?path={quoted}&limit={PER_PAGE}&page={page}") + + +def path_history(repo: upstream.Repo, path: str, cache_dir: str) -> list[str]: + """Commits that touched a path, newest first.""" + shas: list[str] = [] + for page in range(1, MAX_PAGES + 1): + payload = upstream._api(_history_url(repo, path, page), cache_dir, False, + max_age=upstream.MOVING_TTL) + if not isinstance(payload, list) or not payload: + break + shas += [str(entry.get("sha") or entry.get("id")) for entry in payload] + if len(payload) < PER_PAGE: + break + return shas + + +def find_revision( + repo: upstream.Repo, path: str, md5: str, cache_dir: str, +) -> tuple[str, bytes] | None: + """The newest revision whose copy of the path has this md5, and its bytes.""" + wanted = md5.lower() + for sha in path_history(repo, path, cache_dir): + data = upstream._fetch(upstream.content_url(repo, sha, path)) + if data is not None and hashlib.md5(data).hexdigest() == wanted: + return sha, data + return None diff --git a/scripts/acquire/provenance.py b/scripts/acquire/provenance.py new file mode 100644 index 000000000..5c5b3101d --- /dev/null +++ b/scripts/acquire/provenance.py @@ -0,0 +1,335 @@ +"""Dump-catalog coverage: which catalogued dumps the collection holds, and the profiles a missing one would fill.""" + +from __future__ import annotations + +import hashlib +import json +import os +import sys +import zipfile +from pathlib import Path + +from core.paths import REPO_ROOT + + +HASH_FIELDS = ("sha1", "md5", "sha256") + + +def _values(entry: dict, field: str) -> set[str]: + """Every value a profile or catalog entry gives for a hash field.""" + value = entry.get(field) + values = value if isinstance(value, list) else str(value or "").split(",") + return {str(v).strip().lower() for v in values if str(v).strip()} + + +def _crc_key(value: str) -> str: + return value.removeprefix("0x").zfill(8) + + +def _fits(size: int | None, entry: dict) -> bool: + """Whether a size meets what a profile entry states about it.""" + if size is None: + return False + declared = entry.get("size") + if declared is not None: + accepted = declared if isinstance(declared, list) else [declared] + return size in {int(value) for value in accepted} + low, high = entry.get("min_size"), entry.get("max_size") + return (low is None or size >= int(low)) and (high is None or size <= int(high)) + + +def profile_needs(profiles: dict, db: dict) -> dict: + """The files emulator profiles read that the collection does not hold. + + Keyed by every hash a profile accepts, and, for an entry that declares + a size and no hash, by its names casefolded. An entry with neither + cannot be told apart from any same-named dump and is left out, as is a + file the emulator installs itself (`bundled:`) on every platform. + """ + files = db.get("files", {}) + indexes = db.get("indexes", {}) + held_hashes = { + "sha1": set(files), + "md5": set(indexes.get("by_md5", {})), + "sha256": set(indexes.get("by_sha256", {})), + } + held_crc = { + (_crc_key(str(f.get("crc32", "")).lower()), f.get("size")) + for f in files.values() if f.get("crc32") + } + # Held under its own name or under an alias the database indexes, as + # the resolver and verify read it: np2pi's KANJI2.ROM is the PC-88 + # n88knj2.rom, and its own name alone listed it missing. + sizes_by_name: dict[str, set[int]] = {} + for record in files.values(): + sizes_by_name.setdefault(str(record.get("name", "")).casefold(), set()).add( + record.get("size") + ) + for alias, sha1s in indexes.get("by_name", {}).items(): + held = sizes_by_name.setdefault(str(alias).casefold(), set()) + held.update(files[sha1].get("size") for sha1 in sha1s if sha1 in files) + + by_hash: dict[tuple, list[dict]] = {} + by_name: dict[str, list[tuple[dict, dict]]] = {} + for emulator, profile in sorted(profiles.items()): + for entry in profile.get("files", []) or []: + name = str(entry.get("name", "")) + if not name or name.endswith("/"): + continue + # Installed with the emulator, so not an acquisition target, + # unless a platform package leaves it out. + if entry.get("bundled") and not entry.get("not_bundled_on"): + continue + need = {"emulator": emulator, "name": name, + "required": bool(entry.get("required"))} + hashes = {(field, v) for field in HASH_FIELDS for v in _values(entry, field)} + crcs = {_crc_key(v) for v in _values(entry, "crc32")} + declared = entry.get("size") + sizes = [] if declared is None else ( + declared if isinstance(declared, list) else [declared] + ) + crc_keys = {(crc, int(size)) for crc in crcs for size in sizes} + if hashes or crc_keys: + if any(v in held_hashes[field] for field, v in hashes) or ( + crc_keys & held_crc + ): + continue + for key in hashes | {("crc32", crc, size) for crc, size in crc_keys}: + by_hash.setdefault(key, []).append(need) + continue + if all(entry.get(k) is None for k in ("size", "min_size", "max_size")): + continue + names = [name, *(entry.get("aliases") or [])] + # An unsourceable entry is not held by a homonym: xm7's + # KANJI2.ROM is the Fujitsu font, the held one the PC-88's. + if not entry.get("unsourceable") and any( + _fits(held, entry) + for alias in names + for held in sizes_by_name.get(str(alias).casefold(), ()) + ): + continue + for alias in names: + by_name.setdefault(str(alias).casefold(), []).append((need, entry)) + return {"by_hash": by_hash, "by_name": by_name} + + +def needs_filled(entry: dict, needs: dict) -> list[dict]: + """The profile needs a catalog dump answers, required ones first.""" + found: dict[tuple[str, str], dict] = {} + keys: list[tuple[object, ...]] = [ + (field, v) for field in HASH_FIELDS for v in _values(entry, field) + ] + if entry.get("size") is not None: + keys += [("crc32", _crc_key(v), entry["size"]) for v in _values(entry, "crc32")] + for key in keys: + for need in needs["by_hash"].get(key, []): + found.setdefault((need["emulator"], need["name"]), {**need, "by": key[0]}) + size = entry.get("size") + name = str(entry.get("name", "")).casefold() + for need, declared in needs["by_name"].get(name, []): + if _fits(size, declared): + found.setdefault( + (need["emulator"], need["name"]), {**need, "by": "name and size"} + ) + return sorted(found.values(), key=lambda n: (not n["required"], n["emulator"], n["name"])) + + +def archive_members(db: dict) -> dict[tuple[str, int], list[tuple[str, str]]]: + """(crc32, size) of every member of the collection's ZIPs -> (zip, member). + + Read from the central directories alone: a romset member is a dump the + collection already holds, and listing it as an acquisition target sent + searches after astrocdw.zip's bioswhit.bin and the Gamate BIOS. + """ + members: dict[tuple[str, int], list[tuple[str, str]]] = {} + for entry in db.get("files", {}).values(): + path = entry.get("path", "") + if not path.endswith(".zip") or not os.path.exists(path): + continue + try: + with zipfile.ZipFile(path) as archive: + for info in archive.infolist(): + if info.is_dir(): + continue + key = (f"{info.CRC:08x}", info.file_size) + members.setdefault(key, []).append((path, info.filename)) + except (zipfile.BadZipFile, OSError) as exc: + print(f" WARNING: {path}: {exc}", file=sys.stderr) + return members + + +def _held_in_archive(entry: dict, members: dict) -> bool: + """Whether a catalog entry is a member of one of the collection's ZIPs. + + crc32 and size only nominate candidates. A declared sha1 must match the + member's bytes. + """ + crc = str(entry.get("crc32") or "").lower() + size = entry.get("size") + if not crc or size is None: + return False + candidates = members.get((crc.zfill(8), int(size)), []) + sha1 = str(entry.get("sha1") or "").lower() + if not sha1: + return bool(candidates) + for path, name in candidates: + try: + with zipfile.ZipFile(path) as archive: + if hashlib.sha1(archive.read(name)).hexdigest() == sha1: + return True + except (zipfile.BadZipFile, OSError, KeyError) as exc: + print(f" WARNING: {path}:{name}: {exc}", file=sys.stderr) + return False + + +RECIPES_DIR = REPO_ROOT / "recipes" + + +def romset_index(recipes_dir: Path = RECIPES_DIR) -> dict[tuple[str, int], list[dict]]: + """(crc32, size) of every member of an imported romset -> where it sits. + + A dump the collection lacks may still ship inside an emulator's romset: + 17 TOSEC ZX Spectrum ROMs are members of MAME's spectrum.zip. Naming the + set and the versions that carry it turns a dead end into a download. + """ + index: dict[tuple[str, int], list[dict]] = {} + for snapshot in sorted(recipes_dir.glob("*.json")): + with snapshot.open(encoding="utf-8") as handle: + data = json.load(handle) + source = data.get("source", snapshot.stem) + for entry in data.get("entries", []): + dats = entry.get("dats") or [entry.get("dat", "")] + for member in entry.get("members", []) or []: + crc, size = str(member.get("crc32") or "").lower(), member.get("size") + if not crc or size is None: + continue + index.setdefault((crc.zfill(8), int(size)), []).append({ + "source": source, + "archive": entry.get("name", ""), + "member": member.get("name", ""), + "sha1": member.get("sha1", ""), + "dats": dats, + }) + return index + + +def romsets_holding(entry: dict, index: dict) -> list[dict]: + """The imported romsets whose members are this dump. + + A member and an entry that both carry a sha1 must agree on it: crc32 + and size alone match by accident across 40 000 ROMs. + """ + crc, size = str(entry.get("crc32") or "").lower(), entry.get("size") + if not crc or size is None: + return [] + sha1 = str(entry.get("sha1") or "").lower() + # A set whose contents changed between versions is stored once per + # distinct content: one line per set and member, with every version. + merged: dict[tuple[str, str, str], dict] = {} + for hit in index.get((crc.zfill(8), int(size)), []): + if sha1 and hit["sha1"] and hit["sha1"].lower() != sha1: + continue + key = (hit["source"], hit["archive"], hit["member"]) + held = merged.setdefault(key, {**hit, "dats": []}) + held["dats"] = sorted(set(held["dats"]) | set(hit["dats"])) + return list(merged.values()) + + +def dump_identity(entry: dict) -> tuple: + """What makes two catalog listings one dump: the strongest hash stated.""" + if entry.get("sha1"): + return ("sha1", str(entry["sha1"]).lower()) + if entry.get("md5"): + return ("md5", str(entry["md5"]).lower(), entry.get("size")) + if entry.get("crc32"): + return ("crc32", str(entry["crc32"]).lower(), entry.get("size")) + return ("name", entry.get("dat", ""), entry.get("name", "")) + + +def distinct_missing(report: dict) -> int: + """Missing dumps across every catalog, each counted once.""" + return len({dump_identity(e) for data in report.values() for e in data["missing"]}) + + +def build_report( + db: dict, + snapshots: dict, + members: dict | None = None, + romsets: dict | None = None, + needs: dict | None = None, +) -> dict: + """Compare each snapshot against the collection. + + A DAT counts as covered when the collection holds at least one of + its entries. Missing entries from covered DATs are acquisition + targets. Missing entries from DATs the collection does not cover at + all are out of scope and only counted. No-Intro tags every non-game + dump "[BIOS]", including digital title distribution, so without this + split the target list is swamped by content the project never ships. + """ + by_sha1 = db.get("files", {}) + # The members a romset holds are held too, whoever asks: the site built + # its Wanted page without them and asked the public for the Astrocade + # and Gamate BIOS that astrocdw.zip and gamate.zip already carry. + members = archive_members(db) if members is None else members + romsets = romset_index() if romsets is None else romsets + by_md5_size = { + (entry.get("md5", ""), entry.get("size", 0)) for entry in by_sha1.values() + } + # Redump lists some dumps by crc32 alone (ps2-0101jd-20030110, DTL-H10100): + # collected as a loose file it would stay MISSING for good without this. + by_crc32_size = { + (str(entry.get("crc32", "")).lower(), entry.get("size", 0)) + for entry in by_sha1.values() + if entry.get("crc32") + } + + report = {} + for source, snapshot in sorted(snapshots.items()): + matched: set = set() + covered_dats = set() + unmatched = [] + for entry in snapshot["entries"]: + if ( + entry.get("sha1") in by_sha1 + or (entry.get("md5"), entry.get("size")) in by_md5_size + or (str(entry.get("crc32") or "").lower(), entry.get("size")) in by_crc32_size + or _held_in_archive(entry, members) + ): + matched.add(dump_identity(entry)) + covered_dats.add(entry.get("dat", "")) + else: + unmatched.append(entry) + # One dump listed by several DATs (No-Intro's three FM-7 DATs share + # DICROM.rom, KANJI.rom...) is one dump: counted per listing, the + # report announced 2 485 missing for 2 284 distinct ones. + merged: dict = {} + for entry in unmatched: + if entry.get("dat", "") not in covered_dats: + continue + held = merged.get(dump_identity(entry)) + if held is None: + merged[dump_identity(entry)] = {**entry, "dats": [entry.get("dat", "")]} + elif entry.get("dat", "") not in held["dats"]: + held["dats"].append(entry.get("dat", "")) + missing = list(merged.values()) + for entry in missing: + holders = romsets_holding(entry, romsets) + if holders: + entry["romsets"] = holders + filled = needs_filled(entry, needs) if needs else [] + if filled: + entry["needed_by"] = filled + out_of_scope = len({ + dump_identity(e) for e in unmatched if e.get("dat", "") not in covered_dats + }) + report[source] = { + "imported_at": snapshot.get("imported_at", ""), + "dats": snapshot.get("dats", {}), + "total": len(snapshot["entries"]), + "matched": len(matched), + "covered_dats": sorted(covered_dats), + "missing": missing, + "out_of_scope": out_of_scope, + } + return report diff --git a/scripts/archive_build.py b/scripts/archive_build.py deleted file mode 100644 index 23b2eee29..000000000 --- a/scripts/archive_build.py +++ /dev/null @@ -1,544 +0,0 @@ -"""A recipe for every archive the collection holds, and the build that uses it. - -The collection must be able to regenerate each archive it serves from the -ROMs it holds plus a committed recipe, without any copy of that archive -from elsewhere. ``recipes/archives.json`` is that recipe list: one record -per archive in ``database.json``, keyed by its path. - -A record names the members in archive order, each with its size, crc32 and -sha1, and the container's sha1, md5 and size. ``rebuild`` says what the -build reproduces: - -``exact`` - The archive is TorrentZip and ``build_torrentzip()`` over its members - gives its bytes. Proven at capture by rebuilding it. -``canonical`` - Same members, other container bytes: the archive was written by another - tool. The build writes the TorrentZip form and checks members only. - -``sources`` lists the recipes that agree on the member list: profile -``contents:`` blocks and the MAME and FBNeo DAT snapshots under -``recipes/``, then ``collection``, the archive itself. A DAT is provenance, -never the only source. ``bytes_pinned`` marks an archive whose container -hash a platform or a profile pins, with each pin named. - -The build reads each member by sha1: a loose file first, then a member of -another archive, then the archive's own copy, and verifies what it wrote -before moving it into place. -""" - -from __future__ import annotations - -import hashlib -import io -import json -import os -import re -import zipfile -from collections import defaultdict -from collections.abc import Callable, Iterable -from concurrent.futures import ProcessPoolExecutor -from dataclasses import dataclass, field -from pathlib import Path -from typing import BinaryIO - -from core.torrentzip import Source as Readable -from core.paths import REPO_ROOT -from core.torrentzip import write_torrentzip, zlib_ng_version - -ARCHIVES_FILE = REPO_ROOT / "recipes" / "archives.json" -# The writer contract: build_torrentzip's layout over stock zlib. A change to -# the layout is a new builder name and a new proof of every record. -BUILDER = "torrentzip-1" -_ARCHIVE_PATH = re.compile(r"\.zip(\.[0-9a-f]{8})?$", re.IGNORECASE) -_TORRENTZIP_COMMENT = b"TORRENTZIPPED-" - - -def is_archive_path(path: str) -> bool: - """A ZIP by its name: ``x.zip`` or a ``.variants/`` copy ``x.zip.1a2b3c4d``.""" - return bool(_ARCHIVE_PATH.search(path)) - - -def database_archives(db: dict) -> dict[str, dict]: - """Path -> database entry, for every archive the database lists.""" - return { - entry["path"]: entry - for entry in (db.get("files") or {}).values() - if is_archive_path(entry.get("path", "")) - } - - -# --- the ledger file -------------------------------------------------------- - - -def load_ledger(path: Path = ARCHIVES_FILE) -> dict[str, dict]: - """Path -> record, from ``recipes/archives.json``, empty when absent.""" - if not path.is_file(): - return {} - with path.open(encoding="utf-8") as handle: - data = json.load(handle) - return {record["path"]: record for record in data.get("archives", [])} - - -def rebuild_counts(path: Path = ARCHIVES_FILE) -> dict[str, int]: - """How many recipes rebuild ``exact`` and ``canonical``, and ``total``: - the figures the README and the site print.""" - records = load_ledger(path).values() - return { - "total": len(records), - **{kind: sum(1 for r in records if r.get("rebuild") == kind) - for kind in ("exact", "canonical")}, - } - - -def ledger_text(records: dict[str, dict]) -> str: - """One record per line, so a diff names the archive that changed.""" - lines = [ - json.dumps(records[path], ensure_ascii=False, separators=(",", ":")) - for path in sorted(records) - ] - body = ",\n".join(f" {line}" for line in lines) - return f'{{"builder": "{BUILDER}", "archives": [\n{body}\n]}}\n' - - -def write_ledger(records: dict[str, dict], path: Path = ARCHIVES_FILE) -> bool: - from core.artifacts import write_if_changed - - path.parent.mkdir(parents=True, exist_ok=True) - return write_if_changed(str(path), ledger_text(records)) - - -# --- capture ---------------------------------------------------------------- - - -class HashSink: - """A write target that hashes what it receives, and keeps it if asked.""" - - def __init__(self, handle: BinaryIO | None = None) -> None: - self.handle = handle - self.sha1 = hashlib.sha1() - self.md5 = hashlib.md5() - self.size = 0 - - def write(self, data: bytes) -> int: - self.sha1.update(data) - self.md5.update(data) - self.size += len(data) - if self.handle is not None: - self.handle.write(data) - return len(data) - - -class _Member(io.RawIOBase): - """One member of a ZIP, open for reading, closing the archive with it.""" - - def __init__(self, archive: Path, name: str) -> None: - super().__init__() - self._zip = zipfile.ZipFile(archive) - self._stream = self._zip.open(name) - - def readable(self) -> bool: - return True - - def read(self, size: int = -1) -> bytes: - return self._stream.read(size) - - def close(self) -> None: - if not self.closed: - self._stream.close() - self._zip.close() - super().close() - - -def _opener(source: Path, member: str | None) -> Callable[[], Readable]: - if member is None: - return lambda: source.open("rb") - return lambda: _Member(source, member) - - -def _file_infos(path: Path) -> tuple[list[zipfile.ZipInfo], list[str], bool]: - with zipfile.ZipFile(path) as archive: - infos = archive.infolist() - torrentzip = archive.comment.startswith(_TORRENTZIP_COMMENT) - files = [info for info in infos if not info.is_dir()] - directories = [info.filename for info in infos if info.is_dir()] - return files, directories, torrentzip - - -def _member_sha1(path: Path, name: str) -> str: - digest = hashlib.sha1() - with _Member(path, name) as stream: - while chunk := stream.read(16 * 1024 * 1024): - digest.update(chunk) - return digest.hexdigest() - - -def read_archive(path: Path, sha1: str) -> dict: - """Members, directories and rebuild class of the archive at *path*. - - A TorrentZip archive is rebuilt from its own members: equal bytes make - the recipe ``exact``. A mismatch is rebuilt once more before it is - believed, because this host sometimes computes wrongly under load. Any - other archive is ``canonical`` and only its members are read. - """ - files, directories, torrentzip = _file_infos(path) - rebuild = "canonical" - by_name: dict[str, str] = {} - if torrentzip: - for _attempt in range(2): - sink = HashSink() - written = write_torrentzip( - sink, [(info.filename, _opener(path, info.filename)) for info in files] - ) - by_name = {member.name: member.sha1 for member in written} - if sink.sha1.hexdigest() == sha1: - rebuild = "exact" - break - else: - by_name = {info.filename: _member_sha1(path, info.filename) for info in files} - record: dict = { - "rebuild": rebuild, - "members": [ - { - "name": info.filename, - "size": info.file_size, - "crc32": f"{info.CRC:08x}", - "sha1": by_name[info.filename], - } - for info in files - ], - } - if directories: - record["directories"] = directories - return record - - -def _read_job(job: tuple[str, str]) -> tuple[str, dict | str]: - path, sha1 = job - try: - return path, read_archive(Path(path), sha1) - except (OSError, zipfile.BadZipFile, UnicodeEncodeError) as exc: - return path, f"{type(exc).__name__}: {exc}" - - -def _hash_values(value: object) -> set[str]: - raw = value if isinstance(value, list) else str(value or "").split(",") - return {str(item).strip().lower() for item in raw if str(item).strip()} - - -def container_pins(platforms_dir: str, emulators_dir: str) -> dict[str, set[str]]: - """Container hash -> who pins it: ``platform:`` or ``profile:``. - - A ``zipped_file`` entry pins a ROM inside the archive, and a Recalbox - archive md5 is the composite of its members (``zip_digest: composite``, - Bios.cpp:64-68): neither pins the container bytes. - """ - from model.registry import list_registered_platforms - from model.profiles import load_emulator_profiles - from model.platforms import load_platform_config - - pins: dict[str, set[str]] = defaultdict(set) - for platform in list_registered_platforms(platforms_dir): - config = load_platform_config(platform, platforms_dir) - for system in config.get("systems", {}).values(): - for entry in system.get("files", []) or []: - if entry.get("zipped_file") or entry.get("zip_digest") == "composite": - continue - for key in ("md5", "sha1", "alt_md5"): - for value in _hash_values(entry.get(key)): - pins[value].add(f"platform:{platform}") - for name, profile in load_emulator_profiles(emulators_dir, skip_aliases=False).items(): - for entry in profile.get("files", []) or []: - for key in ("md5", "sha1", "sha256"): - for value in _hash_values(entry.get(key)): - pins[value].add(f"profile:{name}") - return dict(pins) - - -MemberList = tuple[tuple[str, str], ...] - - -def recipe_index(emulators_dir: str, recipes_dir: str) -> dict[MemberList, set[str]]: - """Sorted (name, crc32) -> labels of the recipes with exactly those members. - - Matching on the member list, not the archive name, credits a DAT that - knows the set under another name (``aga.zip`` is MAME's ``isa_aga``). - """ - from model.profiles import load_emulator_profiles - from romset_recipes import collect_recipes, load_dat_recipes - - index: dict[MemberList, set[str]] = defaultdict(set) - profiles = load_emulator_profiles(emulators_dir, skip_aliases=False) - for per_label in collect_recipes(profiles).values(): - for label, recipe in per_label.items(): - index[tuple(sorted(recipe))].add(f"profile:{label}") - for per_label in load_dat_recipes(recipes_dir).values(): - for label, recipe in per_label.items(): - index[tuple(sorted(recipe))].add(label) - return dict(index) - - -def member_key(members: Iterable[dict]) -> MemberList: - return tuple(sorted((m["name"], m["crc32"]) for m in members)) - - -def capture( - db: dict, - previous: dict[str, dict], - index: dict[MemberList, set[str]], - pins: dict[str, set[str]], - workers: int = 4, - log: Callable[[str], None] = print, -) -> tuple[dict[str, dict], dict[str, str]]: - """A record for every archive in *db*, and the archives that could not be read. - - A previous record whose sha1 still names the file is kept as read: the - container bytes fix the members. Sources and pins are recomputed every - time, since profiles, snapshots and platform lists move. - """ - if zlib_ng_version(): - raise ZlibNgError(zlib_ng_version()) - archives = database_archives(db) - reused: dict[str, dict] = {} - jobs: list[tuple[str, str]] = [] - for path, entry in sorted(archives.items()): - old = previous.get(path) - if old and old.get("sha1") == entry["sha1"] and old.get("members"): - reused[path] = old - else: - jobs.append((path, entry["sha1"])) - read: dict[str, dict] = {} - failed: dict[str, str] = {} - if jobs: - log(f" reading {len(jobs)} archives ({len(reused)} unchanged)") - with ProcessPoolExecutor(max_workers=workers) as pool: - for path, result in pool.map(_read_job, jobs, chunksize=4): - if isinstance(result, str): - failed[path] = result - else: - read[path] = result - records: dict[str, dict] = {} - for path, entry in sorted(archives.items()): - body = reused.get(path) or read.get(path) - if body is None: - continue - record = { - "path": path, - "sha1": entry["sha1"], - "md5": entry["md5"], - "size": entry["size"], - "rebuild": body["rebuild"], - "members": body["members"], - } - if body.get("directories"): - record["directories"] = body["directories"] - record["sources"] = sorted(index.get(member_key(body["members"]), set())) + [ - "collection" - ] - pinned = set() - for value in (entry["md5"], entry["sha1"], entry.get("sha256", "")): - pinned |= pins.get(str(value).lower(), set()) - if pinned: - record["bytes_pinned"] = True - record["pins"] = sorted(pinned) - records[path] = record - return records, failed - - -class ZlibNgError(RuntimeError): - def __init__(self, version: str | None) -> None: - super().__init__( - f"this Python deflates with zlib-ng {version}: TorrentZip bytes are " - "stock zlib's level-9 output, so an exact rebuild cannot be proven " - "or claimed here. Run under a Python linked against stock zlib." - ) - - -# --- build ------------------------------------------------------------------ - - -@dataclass -class Source: - path: Path - member: str | None # None for a loose file - - -@dataclass -class AtomIndex: - """Where each member sha1 can be read in the collection.""" - - loose: dict[str, Path] = field(default_factory=dict) - inside: dict[str, list[tuple[Path, str]]] = field(default_factory=dict) - - @classmethod - def from_collection(cls, ledger: dict[str, dict], db: dict, root: Path) -> AtomIndex: - index = cls() - for entry in (db.get("files") or {}).values(): - path = root / entry.get("path", "") - if not is_archive_path(entry.get("path", "")) and path.is_file(): - index.loose.setdefault(entry["sha1"], path) - for archive, record in sorted(ledger.items()): - path = root / archive - if not path.is_file(): - continue - for member in record.get("members", []): - index.inside.setdefault(member["sha1"], []).append((path, member["name"])) - return index - - def find(self, sha1: str, own: Path) -> Source | None: - """A loose copy first, then another archive, then the archive itself.""" - if sha1 in self.loose: - return Source(self.loose[sha1], None) - holders = self.inside.get(sha1, []) - for path, member in holders: - if path != own: - return Source(path, member) - for path, member in holders: - return Source(path, member) - return None - - def held(self, sha1: str) -> bool: - return sha1 in self.loose or sha1 in self.inside - - -@dataclass -class BuildResult: - path: str - status: str # exact, canonical, impossible, failed - output: str = "" - detail: str = "" - missing: list[dict] = field(default_factory=list) - own_members: int = 0 - - -def _members_match(built: Path, members: list[dict]) -> str: - """Empty when *built* holds exactly *members*, else what differs.""" - expected = sorted((m["name"], m["size"], m["crc32"], m["sha1"]) for m in members) - with zipfile.ZipFile(built) as archive: - names = [info.filename for info in archive.infolist() if not info.is_dir()] - sizes = {info.filename: info.file_size for info in archive.infolist()} - crcs = {info.filename: f"{info.CRC:08x}" for info in archive.infolist()} - held = sorted( - (name, sizes[name], crcs[name], _member_sha1(built, name)) for name in names - ) - if held == expected: - return "" - missing = sorted(set(expected) - set(held)) - extra = sorted(set(held) - set(expected)) - return f"members differ: expected {missing[:3]}, built {extra[:3]}" - - -def _file_sha1(path: Path) -> str: - digest = hashlib.sha1() - with path.open("rb") as handle: - while chunk := handle.read(16 * 1024 * 1024): - digest.update(chunk) - return digest.hexdigest() - - -def destination(record_path: str, output_dir: Path) -> Path: - """Where a build lands: the archive's path below ``bios/``, under *output_dir*.""" - parts = Path(record_path).parts - relative = Path(*parts[1:]) if parts and parts[0] == "bios" else Path(record_path) - return output_dir / relative - - -def build_archive( - record: dict, - atoms: AtomIndex, - output_dir: Path, - root: Path = REPO_ROOT, - attempts: int = 2, -) -> BuildResult: - """Build *record* from held members into *output_dir*, verified. - - The bytes are written to a scratch file beside the destination and read - back from disk: an exact recipe must give its recorded sha1, a canonical - one its members. A mismatch is built once more, then refused: nothing - wrong is ever moved to the destination. Under zlib-ng an exact recipe is - checked by its members only and never reported exact. - """ - path = record["path"] - own = root / path - sources: list[tuple[str, Source]] = [] - missing: list[dict] = [] - for member in record["members"]: - source = atoms.find(member["sha1"], own) - if source is None: - missing.append(member) - else: - sources.append((member["name"], source)) - if missing: - return BuildResult(path, "impossible", missing=missing) - own_members = sum(1 for _name, source in sources if source.path == own) - ng = zlib_ng_version() - exact = record["rebuild"] == "exact" and not ng - target = destination(path, output_dir) - target.parent.mkdir(parents=True, exist_ok=True) - scratch = target.with_name(f".{target.name}.{os.getpid()}.part") - detail = "" - try: - for _attempt in range(attempts): - with scratch.open("wb") as handle: - write_torrentzip( - handle, - [(name, _opener(source.path, source.member)) for name, source in sources], - ) - if exact: - written = _file_sha1(scratch) - detail = "" if written == record["sha1"] else ( - f"sha1 {written} is not the recorded {record['sha1']}" - ) - else: - detail = _members_match(scratch, record["members"]) - if not detail: - os.replace(scratch, target) - status = "exact" if exact else "canonical" - note = ( - f"zlib-ng {ng}: exact bytes not claimed, members verified" - if ng and record["rebuild"] == "exact" else "" - ) - return BuildResult(path, status, str(target), note, own_members=own_members) - finally: - if scratch.exists(): - scratch.unlink() - return BuildResult(path, "failed", detail=detail, own_members=own_members) - - -def select(ledger: dict[str, dict], wanted: str, root: Path = REPO_ROOT) -> list[dict]: - """Records named by a path (relative or absolute) or by a file name.""" - candidate = Path(wanted) - if candidate.is_absolute(): - try: - candidate = candidate.resolve().relative_to(root.resolve()) - except ValueError: - return [] - key = candidate.as_posix() - if key in ledger: - return [ledger[key]] - return [record for path, record in sorted(ledger.items()) if Path(path).name == wanted] - - -def missing_members(ledger: dict[str, dict], db: dict) -> list[dict]: - """Members held nowhere: neither as a loose file nor inside any archive. - - Read from the committed data alone, so it holds without the files: a - member is held when database.json has its sha1 as a file, or when the - recipe of an archive database.json lists carries it. - """ - archives = database_archives(db) - loose = { - sha1 for sha1, entry in (db.get("files") or {}).items() - if not is_archive_path(entry.get("path", "")) - } - inside = { - member["sha1"] - for path, record in ledger.items() if path in archives - for member in record.get("members", []) - } - return [ - {"archive": path, "member": member["name"], "sha1": member["sha1"]} - for path, record in sorted(ledger.items()) - for member in record.get("members", []) - if member["sha1"] not in loose and member["sha1"] not in inside - ] diff --git a/scripts/auto_fetch.py b/scripts/auto_fetch.py index bf491e3f1..9b8a9f9fb 100644 --- a/scripts/auto_fetch.py +++ b/scripts/auto_fetch.py @@ -17,17 +17,8 @@ Usage: from __future__ import annotations import argparse -import hashlib -import http.client -import json import os -import re -import subprocess import sys -import urllib.error -import urllib.parse -import urllib.request -from pathlib import Path sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from model.cliargs import platform_arg, require_platform @@ -36,6 +27,7 @@ from model.registry import list_registered_platforms from model.database import load_database from model.platforms import load_platform_config from model.safeparse import require_yaml +from acquire.fetch import fetch_missing, find_missing, generate_issue_body, lookup_sha1s yaml = require_yaml() @@ -43,567 +35,6 @@ DEFAULT_DB = "database.json" DEFAULT_PLATFORMS_DIR = "platforms" DEFAULT_BIOS_DIR = "bios" -MAX_DOWNLOAD = 100 * 1024 * 1024 # 100MB per file - -LEGACY_BRANCHES = ["libretro", "RetroArch", "RetroPie", "Recalbox", "batocera", "Other"] - -PUBLIC_REPOS = [ - # archtaurus/RetroPieBIOS - most complete verified collection - "https://raw.githubusercontent.com/archtaurus/RetroPieBIOS/master/BIOS/{name}", - "https://raw.githubusercontent.com/archtaurus/RetroPieBIOS/master/BIOS/pcsx2/bios/{name}", - "https://raw.githubusercontent.com/archtaurus/RetroPieBIOS/master/BIOS/ep128emu/roms/{name}", - "https://raw.githubusercontent.com/archtaurus/RetroPieBIOS/master/BIOS/fuse/{name}", - # prefetchnta/retroarch-bios - alternative verified collection - "https://raw.githubusercontent.com/prefetchnta/retroarch-bios/main/system/{name}", - "https://raw.githubusercontent.com/prefetchnta/retroarch-bios/main/system/pcsx2/bios/{name}", - # BatoceraPLUS - Batocera-specific - "https://raw.githubusercontent.com/BatoceraPLUS/Batocera.PLUS-bios/main/{name}", -] - -# Software Heritage archives the source of every public forge, deleted -# repositories and rewritten histories included, and finds a file by its -# hash: a ROM once committed anywhere answers here even when no forge still -# serves it. Anonymous use allows 120 requests an hour. -SOFTWARE_HERITAGE = "https://archive.softwareheritage.org/api/1/content" - -ARCHIVE_ORG_COLLECTIONS = [ - "RetroarchSystemFiles", - "retroarch_bios", - "retroarch-ultimate-bios-pack_20250824", - "system_20240621", - "full-pack-bios-batocera-39", -] - - -def find_missing(config: dict, db: dict) -> list[dict]: - """Files the platform's own check or its cores' code would not find. - - Read from verify, the platform's native check: a hash or name lookup - of our own called pc6001.zip and fmtowns.zip missing on Batocera, which - checks them inside the zip and holds them, and saw none of the files - the cores need that no platform lists. - """ - from resolve.nativemode import reads_file_contents - from packs.verdicts import Status - from packs.coverage import verify_platform - - result = verify_platform(config, db) - hashed = reads_file_contents(config.get("verification_mode", "existence")) - wanted = { - (d.get("system", ""), d.get("name", "")) - for d in result["details"] - if d["status"] == Status.MISSING or (hashed and d["status"] == Status.UNTESTED) - } - missing: list[dict] = [] - for sys_id, system in config.get("systems", {}).items(): - for file_entry in system.get("files", []): - name = file_entry.get("name", "") - if (sys_id, name) not in wanted: - continue - if file_entry.get("storage", "embedded") != "embedded": - continue - missing.append({ - "name": name, - "system": sys_id, - "sha1": file_entry.get("sha1"), - "md5": file_entry.get("md5"), - "sha256": file_entry.get("sha256"), - "crc32": file_entry.get("crc32"), - "size": file_entry.get("size"), - "destination": file_entry.get("destination", name), - }) - for u in result["undeclared_files"]: - # A file installed with its emulator is not an acquisition target: - # verify leaves it out of the missing count, and bundled_only.py - # --strict refuses a copy that only bundled entries reach. - if u.get("in_repo") or not u.get("required") or u.get("bundled"): - continue - missing.append({ - "name": u["name"], - "system": u.get("system") or "", - "sha1": u.get("sha1"), - "md5": u.get("md5"), - "sha256": u.get("sha256"), - "crc32": u.get("crc32"), - "size": u.get("size"), - "destination": u.get("path") or u["name"], - "emulator": u.get("emulator", ""), - }) - return missing - - -def _accepted(entry: dict, field: str) -> set[str]: - """Every value an entry accepts for a hash field. - - A profile lists several revisions as a YAML list (daedalusx64's - n64.psh), a platform as a comma-separated string. Read as one value, - the list stopped the run with an unhashable-type error. - """ - value = entry.get(field) - values = value if isinstance(value, list) else str(value or "").split(",") - return {str(v).strip().lower() for v in values if str(v).strip()} - - -def _crc32s(entry: dict) -> set[str]: - return {value.removeprefix("0x").zfill(8) for value in _accepted(entry, "crc32")} - - -def _size(entry: dict) -> int | None: - try: - return int(entry["size"]) if entry.get("size") is not None else None - except (TypeError, ValueError): - return None - - -CRYPTO_HASHES = ( - ("sha256", hashlib.sha256), - ("sha1", hashlib.sha1), - ("md5", hashlib.md5), -) - - -def verifiable(entry: dict) -> bool: - """Whether a network download can be proved to be this file. - - Only a cryptographic hash proves it. A crc32 and a size can be met by - crafted bytes, so they identify a file the database already holds - (step 1) and never accept one a remote source serves. - """ - return any(_accepted(entry, field) for field, _digest in CRYPTO_HASHES) - - -def verify_content(data: bytes, expected: dict) -> bool: - """Whether downloaded bytes match every cryptographic hash declared. - - Each declared field must hold the bytes' digest among its accepted - values. An entry declaring none is refused. - """ - declared = [ - (accepted, digest) - for field, digest in CRYPTO_HASHES - for accepted in [_accepted(expected, field)] - if accepted - ] - return bool(declared) and all( - digest(data).hexdigest() in accepted for accepted, digest in declared - ) - - -def _read_limited( - resp: http.client.HTTPResponse, limit: int = MAX_DOWNLOAD -) -> bytes | None: - """Read response up to limit bytes. Returns None if exceeded.""" - data = resp.read(limit + 1) - if len(data) > limit: - return None - return data - - -def step1_crossref_db(entry: dict, db: dict) -> str | None: - """Check if file exists under different name/path in database.""" - files = db.get("files", {}) - for sha1 in sorted(_accepted(entry, "sha1")): - if sha1 in files: - return files[sha1]["path"] - indexes = db.get("indexes", {}) - for field, index in (("sha256", "by_sha256"), ("md5", "by_md5")): - by_hash = indexes.get(index, {}) - for value in sorted(_accepted(entry, field)): - sha1_match = by_hash.get(value) - if sha1_match and sha1_match in files: - return files[sha1_match]["path"] - size = _size(entry) - if size is not None: - by_crc32 = indexes.get("by_crc32", {}) - for crc in sorted(_crc32s(entry)): - sha1_match = by_crc32.get(crc) - if sha1_match in files and files[sha1_match].get("size") == size: - return files[sha1_match]["path"] - return None - - -def step2_scan_branches(entry: dict) -> bytes | None: - """Search old git branches for the file by hash.""" - name = entry["name"] - - for branch in LEGACY_BRANCHES: - ref = f"origin/{branch}" - try: - subprocess.run( - ["git", "rev-parse", "--verify", ref], - capture_output=True, - check=True, - ) - except subprocess.CalledProcessError: - continue - - result = subprocess.run( - ["git", "ls-tree", "-r", "--name-only", ref], - capture_output=True, - text=True, - check=False, - ) - - for filepath in result.stdout.strip().split("\n"): - if os.path.basename(filepath) == name: - try: - blob = subprocess.run( - ["git", "show", f"{ref}:{filepath}"], - capture_output=True, - check=True, - ) - if verify_content(blob.stdout, entry): - return blob.stdout - except subprocess.CalledProcessError: - continue - - return None - - -# Sources that did not answer during the current file's search. A 404 is an -# answer, the file is not there. Anything else leaves the question open: an -# offline run used to report every file as needing a community contribution. -_UNANSWERED: list[str] = [] - - -def _unanswered(url: str, exc: Exception) -> None: - if isinstance(exc, urllib.error.HTTPError) and exc.code == 404: - return - _UNANSWERED.append(f"{url}: {exc}") - - -def step3_search_public_repos(entry: dict) -> bytes | None: - """Search public GitHub BIOS repos.""" - name = entry["name"] - destination = entry.get("destination", name) - - for url_template in PUBLIC_REPOS: - url = url_template.format(name=name) - try: - req = urllib.request.Request( - url, headers={"User-Agent": "retrobios-fetch/1.0"} - ) - with urllib.request.urlopen(req, timeout=30) as resp: - data = _read_limited(resp) - if data is None: - continue - if verify_content(data, entry): - return data - except urllib.error.URLError as exc: - _unanswered(url, exc) - continue - - if "/" in destination: - url = url_template.format(name=destination) - try: - req = urllib.request.Request( - url, headers={"User-Agent": "retrobios-fetch/1.0"} - ) - with urllib.request.urlopen(req, timeout=30) as resp: - data = _read_limited(resp) - if data is None: - continue - if verify_content(data, entry): - return data - except urllib.error.URLError as exc: - _unanswered(url, exc) - continue - - return None - - -def step3b_software_heritage(entry: dict) -> bytes | None: - """Ask Software Heritage for the file by each accepted sha1, then - sha256: its archive answers by content, whatever the file was named.""" - for field in ("sha1", "sha256"): - for value in sorted(_accepted(entry, field)): - url = f"{SOFTWARE_HERITAGE}/{field}:{value}/raw/" - try: - req = urllib.request.Request( - url, headers={"User-Agent": "retrobios-fetch/1.0"} - ) - with urllib.request.urlopen(req, timeout=60) as resp: - data = _read_limited(resp) - except urllib.error.URLError as exc: - _unanswered(url, exc) - continue - if data is not None and verify_content(data, entry): - return data - return None - - -def step4_search_archive_org(entry: dict) -> bytes | None: - """Search archive.org firmware collections by direct download.""" - name = entry["name"] - - for collection_id in ARCHIVE_ORG_COLLECTIONS: - for path in [name, f"system/{name}", f"bios/{name}"]: - url = f"https://archive.org/download/{collection_id}/{path}" - try: - req = urllib.request.Request( - url, headers={"User-Agent": "retrobios-fetch/1.0"} - ) - with urllib.request.urlopen(req, timeout=30) as resp: - data = _read_limited(resp) - if data is None: - continue - if verify_content(data, entry): - return data - except urllib.error.URLError as exc: - _unanswered(url, exc) - continue - - sha1s = sorted(_accepted(entry, "sha1")) - if not sha1s: - return None - # Each accepted revision is a query of its own: archive.org matches one. - sha1 = " OR ".join(f"sha1:{value}" for value in sha1s) - - search_url = ( - "https://archive.org/advancedsearch.php?q=" - f"{urllib.parse.quote(sha1)}&output=json&rows=1" - ) - - try: - req = urllib.request.Request( - search_url, headers={"User-Agent": "retrobios-fetch/1.0"} - ) - with urllib.request.urlopen(req, timeout=30) as resp: - result = json.loads(resp.read()) - docs = result.get("response", {}).get("docs", []) - if docs: - identifier = docs[0].get("identifier") - if identifier: - dl_url = f"https://archive.org/download/{identifier}/{name}" - try: - req2 = urllib.request.Request( - dl_url, headers={"User-Agent": "retrobios-fetch/1.0"} - ) - with urllib.request.urlopen(req2, timeout=30) as resp2: - data = _read_limited(resp2) - if data is not None and verify_content(data, entry): - return data - except urllib.error.URLError as exc: - _unanswered(dl_url, exc) - except (urllib.error.URLError, json.JSONDecodeError) as exc: - _unanswered(search_url, exc) - - return None - - -def place_file(data: bytes, entry: dict, bios_dir: str, db: dict) -> str: - """Place a fetched BIOS file in the correct location.""" - name = os.path.basename(entry["name"]) - system = entry["system"] - - dest_dir = Path(bios_dir) - - # Every part of the slug, not any: matching "nintendo" alone filed the - # N64's n64.psh under the first Nintendo folder walked, the SNES one. - parts = [part for part in system.lower().split("-") if len(part) > 1] - matches = sorted( - (len(f"{manufacturer_dir.name}/{console_dir.name}"), str(console_dir), console_dir) - for manufacturer_dir in dest_dir.iterdir() if manufacturer_dir.is_dir() - for console_dir in manufacturer_dir.iterdir() if console_dir.is_dir() - and all( - part in f"{manufacturer_dir.name}/{console_dir.name}".lower() - for part in parts - ) - ) - folder = matches[0][2] if matches else dest_dir / "Unknown" / system - dest = folder / name - if dest.exists() and dest.read_bytes() != data: - # Another revision under the same name: the collection keeps it - # beside, never in place of, the file already there. - dest = folder / ".variants" / f"{name}.{hashlib.sha1(data).hexdigest()[:8]}" - dest.parent.mkdir(parents=True, exist_ok=True) - with open(dest, "wb") as f: - f.write(data) - return str(dest) - - -def fetch_missing( - missing: list[dict], - db: dict, - bios_dir: str, - dry_run: bool = False, -) -> dict: - """Run the 5-step auto-fetch pipeline for missing files.""" - stats = {"found": 0, "not_found": 0, "errors": 0, "unverifiable": 0} - still_missing = [] - - for entry in missing: - name = entry["name"] - _UNANSWERED.clear() - print(f"\n Searching: {name} ({entry['system']})") - - existing = step1_crossref_db(entry, db) - if existing: - print(f" [1] Found in database at: {existing}") - stats["found"] += 1 - continue - - if not verifiable(entry): - # Searched, a file of that name could only ever be refused. - print(" [-] Cannot be verified from the network: declares no " - "cryptographic hash. Not searched, nothing written") - still_missing.append(entry) - stats["unverifiable"] += 1 - continue - - if dry_run: - print(" [DRY RUN] Would search branches, repos, Software Heritage, archive.org") - still_missing.append(entry) - stats["not_found"] += 1 - continue - - data = step2_scan_branches(entry) - if data: - path = place_file(data, entry, bios_dir, db) - print(f" [2] Found in branch, saved to: {path}") - stats["found"] += 1 - continue - - data = step3_search_public_repos(entry) - if data: - path = place_file(data, entry, bios_dir, db) - print(f" [3] Found in public repo, saved to: {path}") - stats["found"] += 1 - continue - - data = step3b_software_heritage(entry) - if data: - path = place_file(data, entry, bios_dir, db) - print(f" [3b] Found in Software Heritage, saved to: {path}") - stats["found"] += 1 - continue - - data = step4_search_archive_org(entry) - if data: - path = place_file(data, entry, bios_dir, db) - print(f" [4] Found on archive.org, saved to: {path}") - stats["found"] += 1 - continue - - if _UNANSWERED: - # Not looked for everywhere: no issue asks the community for it. - print( - f" [5] Search incomplete, {len(_UNANSWERED)} source(s) did not " - f"answer (first: {_UNANSWERED[0]})" - ) - stats["errors"] += 1 - continue - print(" [5] Not found, open for contributions") - still_missing.append(entry) - stats["not_found"] += 1 - - return {"stats": stats, "still_missing": still_missing} - - -ACQUIRE_DIR = Path("tmp") / "acquire" - - -def lookup_sha1s(sha1s: list[str], db: dict, dry_run: bool = False) -> int: - """--sha1: each file looked for by its hash alone, without a platform. - Found bytes are verified, then saved as tmp/acquire/, never into - bios/: placing a file is a decision the collection makes. 0 when every - one was found, 1 otherwise.""" - missing = 0 - for raw in sha1s: - sha1 = raw.strip().lower() - if not re.fullmatch(r"[0-9a-f]{40}", sha1): - print(f" {raw}: not a sha1", file=sys.stderr) - missing += 1 - continue - entry = {"name": sha1, "sha1": sha1, "system": ""} - _UNANSWERED.clear() - held = step1_crossref_db(entry, db) - if held: - print(f" {sha1}: already held at {held}") - continue - if dry_run: - print(f" {sha1}: would ask Software Heritage and archive.org") - continue - data = step3b_software_heritage(entry) - where = "Software Heritage" - if data is None: - data, where = _archive_org_by_sha1(sha1), "archive.org" - if data is None: - note = f", {len(_UNANSWERED)} source(s) did not answer" if _UNANSWERED else "" - print(f" {sha1}: not found{note}") - missing += 1 - continue - ACQUIRE_DIR.mkdir(parents=True, exist_ok=True) - out = ACQUIRE_DIR / sha1 - out.write_bytes(data) - print(f" {sha1}: found in {where}, {len(data)} bytes, saved to {out}") - return 1 if missing else 0 - - -def _archive_org_by_sha1(sha1: str) -> bytes | None: - """The first archive.org file whose metadata names sha1, read and checked.""" - search = ("https://archive.org/advancedsearch.php?q=" - f"{urllib.parse.quote(f'sha1:{sha1}')}&fl[]=identifier&output=json&rows=5") - try: - with urllib.request.urlopen(urllib.request.Request( - search, headers={"User-Agent": "retrobios-fetch/1.0"}), timeout=30) as resp: - docs = json.loads(resp.read()).get("response", {}).get("docs", []) - except (urllib.error.URLError, json.JSONDecodeError) as exc: - _unanswered(search, exc) - return None - for doc in docs: - identifier = doc.get("identifier") - meta = f"https://archive.org/metadata/{identifier}/files" - try: - with urllib.request.urlopen(urllib.request.Request( - meta, headers={"User-Agent": "retrobios-fetch/1.0"}), timeout=30) as resp: - files = json.loads(resp.read()).get("result", []) - except (urllib.error.URLError, json.JSONDecodeError) as exc: - _unanswered(meta, exc) - continue - for item in files: - if str(item.get("sha1", "")).lower() != sha1: - continue - url = (f"https://archive.org/download/{identifier}/" - f"{urllib.parse.quote(item['name'])}") - try: - with urllib.request.urlopen(urllib.request.Request( - url, headers={"User-Agent": "retrobios-fetch/1.0"}), timeout=60) as resp: - data = _read_limited(resp) - except urllib.error.URLError as exc: - _unanswered(url, exc) - continue - if data is not None and hashlib.sha1(data).hexdigest() == sha1: - return data - return None - - -CONTRIBUTING_URL = "https://github.com/Abdess/retrobios/blob/main/CONTRIBUTING.md" - - -def generate_issue_body(missing: list[dict], platform: str) -> str: - """An issue body for the files a platform still needs. - - The hashes are written in full: a contributor matches a file against - them, and a 12-character prefix confirms nothing. - """ - lines = [ - f"## Files {platform} still needs", - "", - "| File | System | SHA1 | MD5 |", - "|------|--------|------|-----|", - ] - for entry in missing: - sha1 = ", ".join(f"`{h}`" for h in sorted(_accepted(entry, "sha1"))) or "none declared" - md5 = ", ".join(f"`{h}`" for h in sorted(_accepted(entry, "md5"))) or "none declared" - lines.append(f"| `{entry['name']}` | {entry['system']} | {sha1} | {md5} |") - lines += [ - "", - "A file with one of these hashes can be added through the upload link in" - f" [CONTRIBUTING.md]({CONTRIBUTING_URL}). CI checks it on arrival.", - ] - return "\n".join(lines) - def main() -> None: parser = argparse.ArgumentParser(allow_abbrev=False, description="Auto-fetch missing BIOS files") diff --git a/scripts/find_embedded.py b/scripts/find_embedded.py index 5b4367ab3..38757eae4 100644 --- a/scripts/find_embedded.py +++ b/scripts/find_embedded.py @@ -21,68 +21,11 @@ from __future__ import annotations import argparse import hashlib import sys -import zipfile -import zlib -from collections.abc import Iterator from pathlib import Path +from acquire.embedded import offsets, sources + ACQUIRE_DIR = Path("tmp") / "acquire" -_POLY = 0xEDB88320 -_TABLE = [] -for _byte in range(256): - _value = _byte - for _ in range(8): - _value = (_value >> 1) ^ _POLY if _value & 1 else _value >> 1 - _TABLE.append(_value) - - -def _raw(data: bytes) -> int: - """The crc32 register over data, from 0 and without the final xor: a - linear function, which is what lets the window roll.""" - register = 0 - for byte in data: - register = (register >> 8) ^ _TABLE[(register ^ byte) & 0xFF] - return register - - -def offsets(data: bytes, crc32: int, size: int) -> list[int]: - """Every offset where data[offset:offset + size] has this zlib crc32.""" - if size <= 0 or len(data) < size: - return [] - # zlib's crc32 of a window is the linear register xor a constant that - # depends on the length alone: the crc32 of as many zero bytes. - target = crc32 ^ zlib.crc32(bytes(size)) - leaving = [_raw(bytes([byte]) + bytes(size)) for byte in range(256)] - table = _TABLE - register = _raw(data[:size]) - found = [0] if register == target else [] - for start in range(len(data) - size): - register = ((register >> 8) ^ table[(register ^ data[start + size]) & 0xFF] - ^ leaving[data[start]]) - if register == target: - found.append(start + 1) - return found - - -def sources(paths: list[Path]) -> Iterator[tuple[str, bytes]]: - """(label, bytes) of each file under paths, and of each ZIP member.""" - for path in paths: - files = sorted(p for p in path.rglob("*") if p.is_file()) if path.is_dir() else [path] - for file in files: - try: - data = file.read_bytes() - except OSError as exc: - print(f" {file}: not read ({exc.strerror or exc})", file=sys.stderr) - continue - yield str(file), data - if zipfile.is_zipfile(file): - try: - with zipfile.ZipFile(file) as archive: - for info in archive.infolist(): - if not info.is_dir(): - yield f"{file}!{info.filename}", archive.read(info) - except (zipfile.BadZipFile, OSError, RuntimeError, NotImplementedError) as exc: - print(f" {file}: members not read ({exc})", file=sys.stderr) def main() -> int: diff --git a/scripts/find_pinned_revision.py b/scripts/find_pinned_revision.py index 3cceb6128..8c3f3e4fd 100644 --- a/scripts/find_pinned_revision.py +++ b/scripts/find_pinned_revision.py @@ -15,57 +15,12 @@ each until one matches. from __future__ import annotations import argparse -import hashlib import sys -import urllib.parse from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) from core import upstream - -# Commits listed per page and the most pages walked: a data file older than -# 2 000 commits on its own path is not one a platform list still pins. -PER_PAGE = 100 -MAX_PAGES = 20 - - -def _history_url(repo: upstream.Repo, path: str, page: int) -> str: - quoted = urllib.parse.quote(path) - if repo.family == "gitlab": - project = urllib.parse.quote(repo.slug, safe="") - return (f"{repo.api_base}/projects/{project}/repository/commits" - f"?path={quoted}&per_page={PER_PAGE}&page={page}") - if repo.family == "github": - return (f"{repo.api_base}/repos/{repo.slug}/commits" - f"?path={quoted}&per_page={PER_PAGE}&page={page}") - return (f"{repo.api_base}/repos/{repo.slug}/commits" - f"?path={quoted}&limit={PER_PAGE}&page={page}") - - -def path_history(repo: upstream.Repo, path: str, cache_dir: str) -> list[str]: - """Commits that touched a path, newest first.""" - shas: list[str] = [] - for page in range(1, MAX_PAGES + 1): - payload = upstream._api(_history_url(repo, path, page), cache_dir, False, - max_age=upstream.MOVING_TTL) - if not isinstance(payload, list) or not payload: - break - shas += [str(entry.get("sha") or entry.get("id")) for entry in payload] - if len(payload) < PER_PAGE: - break - return shas - - -def find_revision( - repo: upstream.Repo, path: str, md5: str, cache_dir: str, -) -> tuple[str, bytes] | None: - """The newest revision whose copy of the path has this md5, and its bytes.""" - wanted = md5.lower() - for sha in path_history(repo, path, cache_dir): - data = upstream._fetch(upstream.content_url(repo, sha, path)) - if data is not None and hashlib.md5(data).hexdigest() == wanted: - return sha, data - return None +from acquire.history import find_revision def main() -> int: diff --git a/scripts/provenance_report.py b/scripts/provenance_report.py index 731eb1b1c..a52b7cd64 100644 --- a/scripts/provenance_report.py +++ b/scripts/provenance_report.py @@ -19,341 +19,22 @@ name and size when it declares a size and no hash. from __future__ import annotations import argparse -import hashlib import json import os import sys -import zipfile -from pathlib import Path sys.path.insert(0, os.path.dirname(__file__)) from model.dumpcatalog import DEFAULT_PROVENANCE_DIR, load_provenance_snapshots from model.database import load_database from model.profiles import load_emulator_profiles from core.artifacts import write_if_changed -from core.paths import REPO_ROOT - -HASH_FIELDS = ("sha1", "md5", "sha256") - - -def _values(entry: dict, field: str) -> set[str]: - """Every value a profile or catalog entry gives for a hash field.""" - value = entry.get(field) - values = value if isinstance(value, list) else str(value or "").split(",") - return {str(v).strip().lower() for v in values if str(v).strip()} - - -def _crc_key(value: str) -> str: - return value.removeprefix("0x").zfill(8) - - -def _fits(size: int | None, entry: dict) -> bool: - """Whether a size meets what a profile entry states about it.""" - if size is None: - return False - declared = entry.get("size") - if declared is not None: - accepted = declared if isinstance(declared, list) else [declared] - return size in {int(value) for value in accepted} - low, high = entry.get("min_size"), entry.get("max_size") - return (low is None or size >= int(low)) and (high is None or size <= int(high)) - - -def profile_needs(profiles: dict, db: dict) -> dict: - """The files emulator profiles read that the collection does not hold. - - Keyed by every hash a profile accepts, and, for an entry that declares - a size and no hash, by its names casefolded. An entry with neither - cannot be told apart from any same-named dump and is left out, as is a - file the emulator installs itself (`bundled:`) on every platform. - """ - files = db.get("files", {}) - indexes = db.get("indexes", {}) - held_hashes = { - "sha1": set(files), - "md5": set(indexes.get("by_md5", {})), - "sha256": set(indexes.get("by_sha256", {})), - } - held_crc = { - (_crc_key(str(f.get("crc32", "")).lower()), f.get("size")) - for f in files.values() if f.get("crc32") - } - # Held under its own name or under an alias the database indexes, as - # the resolver and verify read it: np2pi's KANJI2.ROM is the PC-88 - # n88knj2.rom, and its own name alone listed it missing. - sizes_by_name: dict[str, set[int]] = {} - for record in files.values(): - sizes_by_name.setdefault(str(record.get("name", "")).casefold(), set()).add( - record.get("size") - ) - for alias, sha1s in indexes.get("by_name", {}).items(): - held = sizes_by_name.setdefault(str(alias).casefold(), set()) - held.update(files[sha1].get("size") for sha1 in sha1s if sha1 in files) - - by_hash: dict[tuple, list[dict]] = {} - by_name: dict[str, list[tuple[dict, dict]]] = {} - for emulator, profile in sorted(profiles.items()): - for entry in profile.get("files", []) or []: - name = str(entry.get("name", "")) - if not name or name.endswith("/"): - continue - # Installed with the emulator, so not an acquisition target, - # unless a platform package leaves it out. - if entry.get("bundled") and not entry.get("not_bundled_on"): - continue - need = {"emulator": emulator, "name": name, - "required": bool(entry.get("required"))} - hashes = {(field, v) for field in HASH_FIELDS for v in _values(entry, field)} - crcs = {_crc_key(v) for v in _values(entry, "crc32")} - declared = entry.get("size") - sizes = [] if declared is None else ( - declared if isinstance(declared, list) else [declared] - ) - crc_keys = {(crc, int(size)) for crc in crcs for size in sizes} - if hashes or crc_keys: - if any(v in held_hashes[field] for field, v in hashes) or ( - crc_keys & held_crc - ): - continue - for key in hashes | {("crc32", crc, size) for crc, size in crc_keys}: - by_hash.setdefault(key, []).append(need) - continue - if all(entry.get(k) is None for k in ("size", "min_size", "max_size")): - continue - names = [name, *(entry.get("aliases") or [])] - # An unsourceable entry is not held by a homonym: xm7's - # KANJI2.ROM is the Fujitsu font, the held one the PC-88's. - if not entry.get("unsourceable") and any( - _fits(held, entry) - for alias in names - for held in sizes_by_name.get(str(alias).casefold(), ()) - ): - continue - for alias in names: - by_name.setdefault(str(alias).casefold(), []).append((need, entry)) - return {"by_hash": by_hash, "by_name": by_name} - - -def needs_filled(entry: dict, needs: dict) -> list[dict]: - """The profile needs a catalog dump answers, required ones first.""" - found: dict[tuple[str, str], dict] = {} - keys: list[tuple[object, ...]] = [ - (field, v) for field in HASH_FIELDS for v in _values(entry, field) - ] - if entry.get("size") is not None: - keys += [("crc32", _crc_key(v), entry["size"]) for v in _values(entry, "crc32")] - for key in keys: - for need in needs["by_hash"].get(key, []): - found.setdefault((need["emulator"], need["name"]), {**need, "by": key[0]}) - size = entry.get("size") - name = str(entry.get("name", "")).casefold() - for need, declared in needs["by_name"].get(name, []): - if _fits(size, declared): - found.setdefault( - (need["emulator"], need["name"]), {**need, "by": "name and size"} - ) - return sorted(found.values(), key=lambda n: (not n["required"], n["emulator"], n["name"])) - - -def archive_members(db: dict) -> dict[tuple[str, int], list[tuple[str, str]]]: - """(crc32, size) of every member of the collection's ZIPs -> (zip, member). - - Read from the central directories alone: a romset member is a dump the - collection already holds, and listing it as an acquisition target sent - searches after astrocdw.zip's bioswhit.bin and the Gamate BIOS. - """ - members: dict[tuple[str, int], list[tuple[str, str]]] = {} - for entry in db.get("files", {}).values(): - path = entry.get("path", "") - if not path.endswith(".zip") or not os.path.exists(path): - continue - try: - with zipfile.ZipFile(path) as archive: - for info in archive.infolist(): - if info.is_dir(): - continue - key = (f"{info.CRC:08x}", info.file_size) - members.setdefault(key, []).append((path, info.filename)) - except (zipfile.BadZipFile, OSError) as exc: - print(f" WARNING: {path}: {exc}", file=sys.stderr) - return members - - -def _held_in_archive(entry: dict, members: dict) -> bool: - """Whether a catalog entry is a member of one of the collection's ZIPs. - - crc32 and size only nominate candidates. A declared sha1 must match the - member's bytes. - """ - crc = str(entry.get("crc32") or "").lower() - size = entry.get("size") - if not crc or size is None: - return False - candidates = members.get((crc.zfill(8), int(size)), []) - sha1 = str(entry.get("sha1") or "").lower() - if not sha1: - return bool(candidates) - for path, name in candidates: - try: - with zipfile.ZipFile(path) as archive: - if hashlib.sha1(archive.read(name)).hexdigest() == sha1: - return True - except (zipfile.BadZipFile, OSError, KeyError) as exc: - print(f" WARNING: {path}:{name}: {exc}", file=sys.stderr) - return False - - -RECIPES_DIR = REPO_ROOT / "recipes" - - -def romset_index(recipes_dir: Path = RECIPES_DIR) -> dict[tuple[str, int], list[dict]]: - """(crc32, size) of every member of an imported romset -> where it sits. - - A dump the collection lacks may still ship inside an emulator's romset: - 17 TOSEC ZX Spectrum ROMs are members of MAME's spectrum.zip. Naming the - set and the versions that carry it turns a dead end into a download. - """ - index: dict[tuple[str, int], list[dict]] = {} - for snapshot in sorted(recipes_dir.glob("*.json")): - with snapshot.open(encoding="utf-8") as handle: - data = json.load(handle) - source = data.get("source", snapshot.stem) - for entry in data.get("entries", []): - dats = entry.get("dats") or [entry.get("dat", "")] - for member in entry.get("members", []) or []: - crc, size = str(member.get("crc32") or "").lower(), member.get("size") - if not crc or size is None: - continue - index.setdefault((crc.zfill(8), int(size)), []).append({ - "source": source, - "archive": entry.get("name", ""), - "member": member.get("name", ""), - "sha1": member.get("sha1", ""), - "dats": dats, - }) - return index - - -def romsets_holding(entry: dict, index: dict) -> list[dict]: - """The imported romsets whose members are this dump. - - A member and an entry that both carry a sha1 must agree on it: crc32 - and size alone match by accident across 40 000 ROMs. - """ - crc, size = str(entry.get("crc32") or "").lower(), entry.get("size") - if not crc or size is None: - return [] - sha1 = str(entry.get("sha1") or "").lower() - # A set whose contents changed between versions is stored once per - # distinct content: one line per set and member, with every version. - merged: dict[tuple[str, str, str], dict] = {} - for hit in index.get((crc.zfill(8), int(size)), []): - if sha1 and hit["sha1"] and hit["sha1"].lower() != sha1: - continue - key = (hit["source"], hit["archive"], hit["member"]) - held = merged.setdefault(key, {**hit, "dats": []}) - held["dats"] = sorted(set(held["dats"]) | set(hit["dats"])) - return list(merged.values()) - - -def dump_identity(entry: dict) -> tuple: - """What makes two catalog listings one dump: the strongest hash stated.""" - if entry.get("sha1"): - return ("sha1", str(entry["sha1"]).lower()) - if entry.get("md5"): - return ("md5", str(entry["md5"]).lower(), entry.get("size")) - if entry.get("crc32"): - return ("crc32", str(entry["crc32"]).lower(), entry.get("size")) - return ("name", entry.get("dat", ""), entry.get("name", "")) - - -def distinct_missing(report: dict) -> int: - """Missing dumps across every catalog, each counted once.""" - return len({dump_identity(e) for data in report.values() for e in data["missing"]}) - - -def build_report( - db: dict, - snapshots: dict, - members: dict | None = None, - romsets: dict | None = None, - needs: dict | None = None, -) -> dict: - """Compare each snapshot against the collection. - - A DAT counts as covered when the collection holds at least one of - its entries. Missing entries from covered DATs are acquisition - targets. Missing entries from DATs the collection does not cover at - all are out of scope and only counted. No-Intro tags every non-game - dump "[BIOS]", including digital title distribution, so without this - split the target list is swamped by content the project never ships. - """ - by_sha1 = db.get("files", {}) - # The members a romset holds are held too, whoever asks: the site built - # its Wanted page without them and asked the public for the Astrocade - # and Gamate BIOS that astrocdw.zip and gamate.zip already carry. - members = archive_members(db) if members is None else members - romsets = romset_index() if romsets is None else romsets - by_md5_size = { - (entry.get("md5", ""), entry.get("size", 0)) for entry in by_sha1.values() - } - # Redump lists some dumps by crc32 alone (ps2-0101jd-20030110, DTL-H10100): - # collected as a loose file it would stay MISSING for good without this. - by_crc32_size = { - (str(entry.get("crc32", "")).lower(), entry.get("size", 0)) - for entry in by_sha1.values() - if entry.get("crc32") - } - - report = {} - for source, snapshot in sorted(snapshots.items()): - matched: set = set() - covered_dats = set() - unmatched = [] - for entry in snapshot["entries"]: - if ( - entry.get("sha1") in by_sha1 - or (entry.get("md5"), entry.get("size")) in by_md5_size - or (str(entry.get("crc32") or "").lower(), entry.get("size")) in by_crc32_size - or _held_in_archive(entry, members) - ): - matched.add(dump_identity(entry)) - covered_dats.add(entry.get("dat", "")) - else: - unmatched.append(entry) - # One dump listed by several DATs (No-Intro's three FM-7 DATs share - # DICROM.rom, KANJI.rom...) is one dump: counted per listing, the - # report announced 2 485 missing for 2 284 distinct ones. - merged: dict = {} - for entry in unmatched: - if entry.get("dat", "") not in covered_dats: - continue - held = merged.get(dump_identity(entry)) - if held is None: - merged[dump_identity(entry)] = {**entry, "dats": [entry.get("dat", "")]} - elif entry.get("dat", "") not in held["dats"]: - held["dats"].append(entry.get("dat", "")) - missing = list(merged.values()) - for entry in missing: - holders = romsets_holding(entry, romsets) - if holders: - entry["romsets"] = holders - filled = needs_filled(entry, needs) if needs else [] - if filled: - entry["needed_by"] = filled - out_of_scope = len({ - dump_identity(e) for e in unmatched if e.get("dat", "") not in covered_dats - }) - report[source] = { - "imported_at": snapshot.get("imported_at", ""), - "dats": snapshot.get("dats", {}), - "total": len(snapshot["entries"]), - "matched": len(matched), - "covered_dats": sorted(covered_dats), - "missing": missing, - "out_of_scope": out_of_scope, - } - return report +from acquire.provenance import ( + archive_members, + build_report, + distinct_missing, + dump_identity, + profile_needs, +) def _print_missing(entry: dict, derived: dict[str, dict]) -> None: @@ -420,7 +101,7 @@ def main() -> int: report = build_report(db, snapshots, archive_members(db), needs=needs) derived: dict[str, dict] = {} if args.derive: - from derivations import derivable + from acquire.derivations import derivable derived = derivable((e for d in report.values() for e in d["missing"]), db) for data in report.values(): diff --git a/scripts/recipes/__init__.py b/scripts/recipes/__init__.py new file mode 100644 index 000000000..7350424af --- /dev/null +++ b/scripts/recipes/__init__.py @@ -0,0 +1 @@ +"""Archive recipes: romset identification, rebuilt pinned archives, and the recipe and build of every archive the collection holds.""" diff --git a/scripts/recipes/build.py b/scripts/recipes/build.py new file mode 100644 index 000000000..8a4713aa7 --- /dev/null +++ b/scripts/recipes/build.py @@ -0,0 +1,179 @@ +"""Build: an archive rebuilt from the members the collection holds, verified before it lands.""" + +from __future__ import annotations + +import hashlib +import os +import zipfile +from dataclasses import dataclass, field +from pathlib import Path + +from core.paths import REPO_ROOT +from core.torrentzip import write_torrentzip, zlib_ng_version +from recipes.ledger import is_archive_path +from recipes.members import _member_sha1, _opener + + +# --- build ------------------------------------------------------------------ + + +@dataclass +class Source: + path: Path + member: str | None # None for a loose file + + +@dataclass +class AtomIndex: + """Where each member sha1 can be read in the collection.""" + + loose: dict[str, Path] = field(default_factory=dict) + inside: dict[str, list[tuple[Path, str]]] = field(default_factory=dict) + + @classmethod + def from_collection(cls, ledger: dict[str, dict], db: dict, root: Path) -> AtomIndex: + index = cls() + for entry in (db.get("files") or {}).values(): + path = root / entry.get("path", "") + if not is_archive_path(entry.get("path", "")) and path.is_file(): + index.loose.setdefault(entry["sha1"], path) + for archive, record in sorted(ledger.items()): + path = root / archive + if not path.is_file(): + continue + for member in record.get("members", []): + index.inside.setdefault(member["sha1"], []).append((path, member["name"])) + return index + + def find(self, sha1: str, own: Path) -> Source | None: + """A loose copy first, then another archive, then the archive itself.""" + if sha1 in self.loose: + return Source(self.loose[sha1], None) + holders = self.inside.get(sha1, []) + for path, member in holders: + if path != own: + return Source(path, member) + for path, member in holders: + return Source(path, member) + return None + + def held(self, sha1: str) -> bool: + return sha1 in self.loose or sha1 in self.inside + + +@dataclass +class BuildResult: + path: str + status: str # exact, canonical, impossible, failed + output: str = "" + detail: str = "" + missing: list[dict] = field(default_factory=list) + own_members: int = 0 + + +def _members_match(built: Path, members: list[dict]) -> str: + """Empty when *built* holds exactly *members*, else what differs.""" + expected = sorted((m["name"], m["size"], m["crc32"], m["sha1"]) for m in members) + with zipfile.ZipFile(built) as archive: + names = [info.filename for info in archive.infolist() if not info.is_dir()] + sizes = {info.filename: info.file_size for info in archive.infolist()} + crcs = {info.filename: f"{info.CRC:08x}" for info in archive.infolist()} + held = sorted( + (name, sizes[name], crcs[name], _member_sha1(built, name)) for name in names + ) + if held == expected: + return "" + missing = sorted(set(expected) - set(held)) + extra = sorted(set(held) - set(expected)) + return f"members differ: expected {missing[:3]}, built {extra[:3]}" + + +def _file_sha1(path: Path) -> str: + digest = hashlib.sha1() + with path.open("rb") as handle: + while chunk := handle.read(16 * 1024 * 1024): + digest.update(chunk) + return digest.hexdigest() + + +def destination(record_path: str, output_dir: Path) -> Path: + """Where a build lands: the archive's path below ``bios/``, under *output_dir*.""" + parts = Path(record_path).parts + relative = Path(*parts[1:]) if parts and parts[0] == "bios" else Path(record_path) + return output_dir / relative + + +def build_archive( + record: dict, + atoms: AtomIndex, + output_dir: Path, + root: Path = REPO_ROOT, + attempts: int = 2, +) -> BuildResult: + """Build *record* from held members into *output_dir*, verified. + + The bytes are written to a scratch file beside the destination and read + back from disk: an exact recipe must give its recorded sha1, a canonical + one its members. A mismatch is built once more, then refused: nothing + wrong is ever moved to the destination. Under zlib-ng an exact recipe is + checked by its members only and never reported exact. + """ + path = record["path"] + own = root / path + sources: list[tuple[str, Source]] = [] + missing: list[dict] = [] + for member in record["members"]: + source = atoms.find(member["sha1"], own) + if source is None: + missing.append(member) + else: + sources.append((member["name"], source)) + if missing: + return BuildResult(path, "impossible", missing=missing) + own_members = sum(1 for _name, source in sources if source.path == own) + ng = zlib_ng_version() + exact = record["rebuild"] == "exact" and not ng + target = destination(path, output_dir) + target.parent.mkdir(parents=True, exist_ok=True) + scratch = target.with_name(f".{target.name}.{os.getpid()}.part") + detail = "" + try: + for _attempt in range(attempts): + with scratch.open("wb") as handle: + write_torrentzip( + handle, + [(name, _opener(source.path, source.member)) for name, source in sources], + ) + if exact: + written = _file_sha1(scratch) + detail = "" if written == record["sha1"] else ( + f"sha1 {written} is not the recorded {record['sha1']}" + ) + else: + detail = _members_match(scratch, record["members"]) + if not detail: + os.replace(scratch, target) + status = "exact" if exact else "canonical" + note = ( + f"zlib-ng {ng}: exact bytes not claimed, members verified" + if ng and record["rebuild"] == "exact" else "" + ) + return BuildResult(path, status, str(target), note, own_members=own_members) + finally: + if scratch.exists(): + scratch.unlink() + return BuildResult(path, "failed", detail=detail, own_members=own_members) + + +def select(ledger: dict[str, dict], wanted: str, root: Path = REPO_ROOT) -> list[dict]: + """Records named by a path (relative or absolute) or by a file name.""" + candidate = Path(wanted) + if candidate.is_absolute(): + try: + candidate = candidate.resolve().relative_to(root.resolve()) + except ValueError: + return [] + key = candidate.as_posix() + if key in ledger: + return [ledger[key]] + return [record for path, record in sorted(ledger.items()) if Path(path).name == wanted] diff --git a/scripts/recipes/capture.py b/scripts/recipes/capture.py new file mode 100644 index 000000000..9a082fa5c --- /dev/null +++ b/scripts/recipes/capture.py @@ -0,0 +1,229 @@ +"""Capture: a recipe record for every archive the database lists.""" + +from __future__ import annotations + +import hashlib +import zipfile +from collections import defaultdict +from collections.abc import Callable, Iterable +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path +from typing import BinaryIO + +from core.torrentzip import write_torrentzip, zlib_ng_version +from recipes.ledger import database_archives +from recipes.members import _member_sha1, _opener + + +_TORRENTZIP_COMMENT = b"TORRENTZIPPED-" + + +# --- capture ---------------------------------------------------------------- + + +class HashSink: + """A write target that hashes what it receives, and keeps it if asked.""" + + def __init__(self, handle: BinaryIO | None = None) -> None: + self.handle = handle + self.sha1 = hashlib.sha1() + self.md5 = hashlib.md5() + self.size = 0 + + def write(self, data: bytes) -> int: + self.sha1.update(data) + self.md5.update(data) + self.size += len(data) + if self.handle is not None: + self.handle.write(data) + return len(data) + + +def _file_infos(path: Path) -> tuple[list[zipfile.ZipInfo], list[str], bool]: + with zipfile.ZipFile(path) as archive: + infos = archive.infolist() + torrentzip = archive.comment.startswith(_TORRENTZIP_COMMENT) + files = [info for info in infos if not info.is_dir()] + directories = [info.filename for info in infos if info.is_dir()] + return files, directories, torrentzip + + +def read_archive(path: Path, sha1: str) -> dict: + """Members, directories and rebuild class of the archive at *path*. + + A TorrentZip archive is rebuilt from its own members: equal bytes make + the recipe ``exact``. A mismatch is rebuilt once more before it is + believed, because this host sometimes computes wrongly under load. Any + other archive is ``canonical`` and only its members are read. + """ + files, directories, torrentzip = _file_infos(path) + rebuild = "canonical" + by_name: dict[str, str] = {} + if torrentzip: + for _attempt in range(2): + sink = HashSink() + written = write_torrentzip( + sink, [(info.filename, _opener(path, info.filename)) for info in files] + ) + by_name = {member.name: member.sha1 for member in written} + if sink.sha1.hexdigest() == sha1: + rebuild = "exact" + break + else: + by_name = {info.filename: _member_sha1(path, info.filename) for info in files} + record: dict = { + "rebuild": rebuild, + "members": [ + { + "name": info.filename, + "size": info.file_size, + "crc32": f"{info.CRC:08x}", + "sha1": by_name[info.filename], + } + for info in files + ], + } + if directories: + record["directories"] = directories + return record + + +def _read_job(job: tuple[str, str]) -> tuple[str, dict | str]: + path, sha1 = job + try: + return path, read_archive(Path(path), sha1) + except (OSError, zipfile.BadZipFile, UnicodeEncodeError) as exc: + return path, f"{type(exc).__name__}: {exc}" + + +def _hash_values(value: object) -> set[str]: + raw = value if isinstance(value, list) else str(value or "").split(",") + return {str(item).strip().lower() for item in raw if str(item).strip()} + + +def container_pins(platforms_dir: str, emulators_dir: str) -> dict[str, set[str]]: + """Container hash -> who pins it: ``platform:`` or ``profile:``. + + A ``zipped_file`` entry pins a ROM inside the archive, and a Recalbox + archive md5 is the composite of its members (``zip_digest: composite``, + Bios.cpp:64-68): neither pins the container bytes. + """ + from model.registry import list_registered_platforms + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config + + pins: dict[str, set[str]] = defaultdict(set) + for platform in list_registered_platforms(platforms_dir): + config = load_platform_config(platform, platforms_dir) + for system in config.get("systems", {}).values(): + for entry in system.get("files", []) or []: + if entry.get("zipped_file") or entry.get("zip_digest") == "composite": + continue + for key in ("md5", "sha1", "alt_md5"): + for value in _hash_values(entry.get(key)): + pins[value].add(f"platform:{platform}") + for name, profile in load_emulator_profiles(emulators_dir, skip_aliases=False).items(): + for entry in profile.get("files", []) or []: + for key in ("md5", "sha1", "sha256"): + for value in _hash_values(entry.get(key)): + pins[value].add(f"profile:{name}") + return dict(pins) + + +MemberList = tuple[tuple[str, str], ...] + + +def recipe_index(emulators_dir: str, recipes_dir: str) -> dict[MemberList, set[str]]: + """Sorted (name, crc32) -> labels of the recipes with exactly those members. + + Matching on the member list, not the archive name, credits a DAT that + knows the set under another name (``aga.zip`` is MAME's ``isa_aga``). + """ + from model.profiles import load_emulator_profiles + from recipes.romsets import collect_recipes, load_dat_recipes + + index: dict[MemberList, set[str]] = defaultdict(set) + profiles = load_emulator_profiles(emulators_dir, skip_aliases=False) + for per_label in collect_recipes(profiles).values(): + for label, recipe in per_label.items(): + index[tuple(sorted(recipe))].add(f"profile:{label}") + for per_label in load_dat_recipes(recipes_dir).values(): + for label, recipe in per_label.items(): + index[tuple(sorted(recipe))].add(label) + return dict(index) + + +def member_key(members: Iterable[dict]) -> MemberList: + return tuple(sorted((m["name"], m["crc32"]) for m in members)) + + +def capture( + db: dict, + previous: dict[str, dict], + index: dict[MemberList, set[str]], + pins: dict[str, set[str]], + workers: int = 4, + log: Callable[[str], None] = print, +) -> tuple[dict[str, dict], dict[str, str]]: + """A record for every archive in *db*, and the archives that could not be read. + + A previous record whose sha1 still names the file is kept as read: the + container bytes fix the members. Sources and pins are recomputed every + time, since profiles, snapshots and platform lists move. + """ + if zlib_ng_version(): + raise ZlibNgError(zlib_ng_version()) + archives = database_archives(db) + reused: dict[str, dict] = {} + jobs: list[tuple[str, str]] = [] + for path, entry in sorted(archives.items()): + old = previous.get(path) + if old and old.get("sha1") == entry["sha1"] and old.get("members"): + reused[path] = old + else: + jobs.append((path, entry["sha1"])) + read: dict[str, dict] = {} + failed: dict[str, str] = {} + if jobs: + log(f" reading {len(jobs)} archives ({len(reused)} unchanged)") + with ProcessPoolExecutor(max_workers=workers) as pool: + for path, result in pool.map(_read_job, jobs, chunksize=4): + if isinstance(result, str): + failed[path] = result + else: + read[path] = result + records: dict[str, dict] = {} + for path, entry in sorted(archives.items()): + body = reused.get(path) or read.get(path) + if body is None: + continue + record = { + "path": path, + "sha1": entry["sha1"], + "md5": entry["md5"], + "size": entry["size"], + "rebuild": body["rebuild"], + "members": body["members"], + } + if body.get("directories"): + record["directories"] = body["directories"] + record["sources"] = sorted(index.get(member_key(body["members"]), set())) + [ + "collection" + ] + pinned = set() + for value in (entry["md5"], entry["sha1"], entry.get("sha256", "")): + pinned |= pins.get(str(value).lower(), set()) + if pinned: + record["bytes_pinned"] = True + record["pins"] = sorted(pinned) + records[path] = record + return records, failed + + +class ZlibNgError(RuntimeError): + def __init__(self, version: str | None) -> None: + super().__init__( + f"this Python deflates with zlib-ng {version}: TorrentZip bytes are " + "stock zlib's level-9 output, so an exact rebuild cannot be proven " + "or claimed here. Run under a Python linked against stock zlib." + ) diff --git a/scripts/recipes/identify.py b/scripts/recipes/identify.py new file mode 100644 index 000000000..f73690744 --- /dev/null +++ b/scripts/recipes/identify.py @@ -0,0 +1,213 @@ +"""Which recipe rebuilds a held archive, and which pinned archives the collection lacks but can rebuild.""" + +from __future__ import annotations + +import hashlib +import sys +import zipfile +from collections import defaultdict +from pathlib import Path + +from core.torrentzip import is_torrentzip +from model.platforms import load_platform_config +from model.registry import list_registered_platforms +from recipes.pool import AtomPool +from recipes.romsets import Recipe + + +def identify_archive( + path: Path, recipes: dict[str, Recipe], pool: AtomPool +) -> str | None: + """Return the recipe label that reproduces *path* byte for byte. + + Equal bytes need equal (name, crc32) members, which the archive's + central directory gives without inflating anything: building every + recipe at DEFLATE level 9 first took 94 s and 1 GB at pipeline step 1c. + """ + held = _member_list(path) + if held is None: + return None + original = path.read_bytes() + md5, size = hashlib.md5(original).hexdigest(), len(original) + for label, recipe in sorted(recipes.items()): + if sorted((name, crc.lower()) for name, crc in recipe) != held: + continue + if pool.digest(recipe) == (md5, size): + return label + return None + + +def _member_list(path: Path) -> list[tuple[str, str]] | None: + """Sorted (name, crc32) of an archive's members, from its directory.""" + try: + with zipfile.ZipFile(path) as archive: + return sorted( + (info.filename, format(info.CRC, "08x")) + for info in archive.infolist() if not info.is_dir() + ) + except (zipfile.BadZipFile, OSError) as exc: + print(f" UNREADABLE: {path}: {exc}", file=sys.stderr) + return None + + +def reconstruct( + target_md5: str, recipes: dict[str, Recipe], pool: AtomPool +) -> tuple[str, bytes] | None: + """Return the (label, bytes) whose TorrentZip build matches *target_md5*.""" + target = target_md5.lower() + for label, recipe in sorted(recipes.items()): + known = pool.digest(recipe) + if known is not None and known[0] == target: + blob = pool.build(recipe) + if blob is not None and hashlib.md5(blob).hexdigest() == target: + return label, blob + return None + + +def platform_targets(platforms_dir: str) -> dict[str, set[str]]: + """Container MD5s the platforms pin, per archive name. + + ``zipped_file`` entries pin an inner ROM instead of the container, so + their MD5 is not an archive hash and is skipped. So is a Recalbox md5, + the composite of the members (``zip_digest: composite``, Bios.cpp:64-68): + no container build can ever give it. + """ + targets: dict[str, set[str]] = defaultdict(set) + for name in list_registered_platforms(platforms_dir): + config = load_platform_config(name, platforms_dir) + for system in config.get("systems", {}).values(): + for entry in system.get("files", []) or []: + archive = entry.get("name", "") + if ( + not archive.endswith(".zip") + or entry.get("zipped_file") + or entry.get("zip_digest") == "composite" + ): + continue + for value in str(entry.get("md5") or "").split(","): + value = value.strip().lower() + if len(value) == 32: + targets[archive].add(value) + return dict(targets) + + +def _is_archive(path: Path) -> bool: + """Whether *path* is a readable ZIP. + + A name index entry can be an alias: ``d2fdc.zip`` names a loose Apple II + ROM, not an archive. Recipes only describe archives. + """ + try: + with zipfile.ZipFile(path): + return True + except (OSError, zipfile.BadZipFile): + return False + + +def _local_paths(archive: str, db: dict) -> list[Path]: + matches = db["indexes"]["by_name"].get(archive) or [] + if isinstance(matches, str): + matches = [matches] + paths = [Path(db["files"][sha1]["path"]) for sha1 in matches if sha1 in db["files"]] + return [path for path in paths if path.is_file() and _is_archive(path)] + + +def identify_report( + recipes: dict[str, dict[str, Recipe]], pool: AtomPool, db: dict +) -> dict: + """Label every archive the collection holds with the version it matches.""" + identified: list[dict] = [] + unidentified: list[dict] = [] + for archive, per_profile in sorted(recipes.items()): + for path in _local_paths(archive, db): + label = identify_archive(path, per_profile, pool) + record = { + "archive": archive, + "path": str(path), + "torrentzip": is_torrentzip(path), + } + if label: + record["recipe"] = label + identified.append(record) + else: + record["candidates"] = sorted(per_profile) + unidentified.append(record) + return {"identified": identified, "unidentified": unidentified} + + +def missing_report( + recipes: dict[str, dict[str, Recipe]], + pool: AtomPool, + db: dict, + platforms_dir: str, +) -> dict: + """Pinned archives the collection lacks, split by why they are absent.""" + have = set(db["indexes"]["by_md5"]) + constructible: list[dict] = [] + no_recipe: list[dict] = [] + unreproducible: list[dict] = [] + for archive, pinned in sorted(platform_targets(platforms_dir).items()): + per_profile = recipes.get(archive, {}) + for target in sorted(pinned - have): + if not per_profile: + no_recipe.append({"archive": archive, "md5": target}) + continue + found = reconstruct(target, per_profile, pool) + if found: + label, blob = found + constructible.append( + { + "archive": archive, + "md5": target, + "recipe": label, + "size": len(blob), + } + ) + else: + usable = [ + label + for label, recipe in per_profile.items() + if all(crc in pool for _name, crc in recipe) + ] + unreproducible.append( + { + "archive": archive, + "md5": target, + "recipes_tried": sorted(usable), + "reason": ( + "no recipe reproduces this MD5: the pinned archive is " + "not TorrentZip or follows a recipe not documented here" + if usable + else "ROMs for every documented recipe are missing" + ), + } + ) + return { + "constructible": constructible, + "unreproducible": unreproducible, + "no_recipe": no_recipe, + } + + +def write_reconstructions( + entries: list[dict], + recipes: dict[str, dict[str, Recipe]], + pool: AtomPool, + bios_dir: Path, + db: dict, +) -> list[str]: + """Write each constructible archive beside its set, as a variant.""" + written: list[str] = [] + for entry in entries: + archive = entry["archive"] + recipe = recipes[archive][entry["recipe"]] + blob = pool.build(recipe) + if blob is None: + continue + siblings = _local_paths(archive, db) + parent = siblings[0].parent if siblings else bios_dir + destination = parent / ".variants" / f"{archive}.{entry['md5'][:8]}" + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(blob) + written.append(str(destination)) + return written diff --git a/scripts/recipes/ledger.py b/scripts/recipes/ledger.py new file mode 100644 index 000000000..aacdf544a --- /dev/null +++ b/scripts/recipes/ledger.py @@ -0,0 +1,122 @@ +"""A recipe for every archive the collection holds, and the build that uses it. + +The collection must be able to regenerate each archive it serves from the +ROMs it holds plus a committed recipe, without any copy of that archive +from elsewhere. ``recipes/archives.json`` is that recipe list: one record +per archive in ``database.json``, keyed by its path. + +A record names the members in archive order, each with its size, crc32 and +sha1, and the container's sha1, md5 and size. ``rebuild`` says what the +build reproduces: + +``exact`` + The archive is TorrentZip and ``build_torrentzip()`` over its members + gives its bytes. Proven at capture by rebuilding it. +``canonical`` + Same members, other container bytes: the archive was written by another + tool. The build writes the TorrentZip form and checks members only. + +``sources`` lists the recipes that agree on the member list: profile +``contents:`` blocks and the MAME and FBNeo DAT snapshots under +``recipes/``, then ``collection``, the archive itself. A DAT is provenance, +never the only source. ``bytes_pinned`` marks an archive whose container +hash a platform or a profile pins, with each pin named. + +The build reads each member by sha1: a loose file first, then a member of +another archive, then the archive's own copy, and verifies what it wrote +before moving it into place. +""" + +from __future__ import annotations + +import json +import re +from pathlib import Path + +from core.paths import REPO_ROOT + + +ARCHIVES_FILE = REPO_ROOT / "recipes" / "archives.json" +# The writer contract: build_torrentzip's layout over stock zlib. A change to +# the layout is a new builder name and a new proof of every record. +BUILDER = "torrentzip-1" +_ARCHIVE_PATH = re.compile(r"\.zip(\.[0-9a-f]{8})?$", re.IGNORECASE) + + +def is_archive_path(path: str) -> bool: + """A ZIP by its name: ``x.zip`` or a ``.variants/`` copy ``x.zip.1a2b3c4d``.""" + return bool(_ARCHIVE_PATH.search(path)) + + +def database_archives(db: dict) -> dict[str, dict]: + """Path -> database entry, for every archive the database lists.""" + return { + entry["path"]: entry + for entry in (db.get("files") or {}).values() + if is_archive_path(entry.get("path", "")) + } + + +# --- the ledger file -------------------------------------------------------- + + +def load_ledger(path: Path = ARCHIVES_FILE) -> dict[str, dict]: + """Path -> record, from ``recipes/archives.json``, empty when absent.""" + if not path.is_file(): + return {} + with path.open(encoding="utf-8") as handle: + data = json.load(handle) + return {record["path"]: record for record in data.get("archives", [])} + + +def rebuild_counts(path: Path = ARCHIVES_FILE) -> dict[str, int]: + """How many recipes rebuild ``exact`` and ``canonical``, and ``total``: + the figures the README and the site print.""" + records = load_ledger(path).values() + return { + "total": len(records), + **{kind: sum(1 for r in records if r.get("rebuild") == kind) + for kind in ("exact", "canonical")}, + } + + +def ledger_text(records: dict[str, dict]) -> str: + """One record per line, so a diff names the archive that changed.""" + lines = [ + json.dumps(records[path], ensure_ascii=False, separators=(",", ":")) + for path in sorted(records) + ] + body = ",\n".join(f" {line}" for line in lines) + return f'{{"builder": "{BUILDER}", "archives": [\n{body}\n]}}\n' + + +def write_ledger(records: dict[str, dict], path: Path = ARCHIVES_FILE) -> bool: + from core.artifacts import write_if_changed + + path.parent.mkdir(parents=True, exist_ok=True) + return write_if_changed(str(path), ledger_text(records)) + + +def missing_members(ledger: dict[str, dict], db: dict) -> list[dict]: + """Members held nowhere: neither as a loose file nor inside any archive. + + Read from the committed data alone, so it holds without the files: a + member is held when database.json has its sha1 as a file, or when the + recipe of an archive database.json lists carries it. + """ + archives = database_archives(db) + loose = { + sha1 for sha1, entry in (db.get("files") or {}).items() + if not is_archive_path(entry.get("path", "")) + } + inside = { + member["sha1"] + for path, record in ledger.items() if path in archives + for member in record.get("members", []) + } + return [ + {"archive": path, "member": member["name"], "sha1": member["sha1"]} + for path, record in sorted(ledger.items()) + for member in record.get("members", []) + if member["sha1"] not in loose and member["sha1"] not in inside + ] diff --git a/scripts/recipes/members.py b/scripts/recipes/members.py new file mode 100644 index 000000000..035c00b03 --- /dev/null +++ b/scripts/recipes/members.py @@ -0,0 +1,46 @@ +"""Members of a ZIP read as streams, one opener per member.""" + +from __future__ import annotations + +import hashlib +import io +import zipfile +from collections.abc import Callable +from pathlib import Path + +from core.torrentzip import Source as Readable + + +class _Member(io.RawIOBase): + """One member of a ZIP, open for reading, closing the archive with it.""" + + def __init__(self, archive: Path, name: str) -> None: + super().__init__() + self._zip = zipfile.ZipFile(archive) + self._stream = self._zip.open(name) + + def readable(self) -> bool: + return True + + def read(self, size: int = -1) -> bytes: + return self._stream.read(size) + + def close(self) -> None: + if not self.closed: + self._stream.close() + self._zip.close() + super().close() + + +def _opener(source: Path, member: str | None) -> Callable[[], Readable]: + if member is None: + return lambda: source.open("rb") + return lambda: _Member(source, member) + + +def _member_sha1(path: Path, name: str) -> str: + digest = hashlib.sha1() + with _Member(path, name) as stream: + while chunk := stream.read(16 * 1024 * 1024): + digest.update(chunk) + return digest.hexdigest() diff --git a/scripts/recipes/pool.py b/scripts/recipes/pool.py new file mode 100644 index 000000000..8c68a76e7 --- /dev/null +++ b/scripts/recipes/pool.py @@ -0,0 +1,135 @@ +"""ROM bytes the collection holds, addressed by crc32, and the TorrentZip builds of recipes over them.""" + +from __future__ import annotations + +import hashlib +import json +import sys +import zipfile +from pathlib import Path + +from core.paths import REPO_ROOT +from core.torrentzip import build_torrentzip +from recipes.romsets import Recipe + + +class AtomPool: + """ROM bytes in the collection, addressed by CRC32. + + Members are located once and read on demand: arcade sample sets reach + hundreds of megabytes and a whole-pool preload buys nothing. + """ + + def __init__( + self, bios_dir: Path, digest_cache: Path | None = None, db: dict | None = None + ) -> None: + # crc32 -> (archive, member), or (file, None) for a loose ROM. + self._index: dict[str, tuple[Path, str | None]] = {} + # (md5, size) of each build, kept across runs: TorrentZip bytes are a + # function of the members alone, so a recipe hashed once is known + # until the writer changes. Rebuilding the 1 221 archives took 70 s + # of every pipeline run, 63 s of it in zlib. + self._digest_cache = digest_cache + self._digests: dict[str, list] = _read_digests(digest_cache) + self._digests_changed = False + # A recipe is built once: identification and reconstruction ask for the + # same archives, and every build re-reads and re-deflates its ROMs. + self._built: dict[tuple[tuple[str, str], ...], bytes | None] = {} + self.unreadable: list[str] = [] + for archive in sorted(bios_dir.rglob("*.zip")): + try: + with zipfile.ZipFile(archive) as handle: + for info in handle.infolist(): + if not info.is_dir(): + self._index.setdefault( + f"{info.CRC:08x}", (archive, info.filename) + ) + except (OSError, zipfile.BadZipFile) as exc: + self.unreadable.append(f"{archive}: {exc}") + # Loose ROMs, by the crc32 the database already computed: nmk004.zip + # needs nmk004.bin, which the collection holds only as a file. + root = bios_dir.resolve() + for entry in ((db or {}).get("files") or {}).values(): + crc, path = str(entry.get("crc32") or "").lower(), entry.get("path", "") + if not crc or not path or path.lower().endswith(".zip"): + continue + loose = Path(path) + if root in loose.resolve().parents and loose.is_file(): + self._index.setdefault(crc, (loose, None)) + + def __len__(self) -> int: + return len(self._index) + + def __contains__(self, crc32: str) -> bool: + return crc32.lower() in self._index + + def read(self, crc32: str) -> bytes: + archive, member = self._index[crc32.lower()] + if member is None: + return archive.read_bytes() + with zipfile.ZipFile(archive) as handle: + return handle.read(member) + + def digest(self, recipe: Recipe) -> tuple[str, int] | None: + """(md5, size) of the recipe's TorrentZip build, None if incomplete.""" + if not all(crc in self for _name, crc in recipe): + return None + key = _recipe_key(recipe) + known = self._digests.get(key) + if known is None: + blob = self.build(recipe) + if blob is None: + return None + known = self._digests[key] = [hashlib.md5(blob).hexdigest(), len(blob)] + self._digests_changed = True + return known[0], known[1] + + def save_digests(self) -> None: + """Write the digest cache back, when this run learned anything.""" + if self._digest_cache is None or not self._digests_changed: + return + from core.artifacts import write_text_atomic + + self._digest_cache.parent.mkdir(parents=True, exist_ok=True) + write_text_atomic( + str(self._digest_cache), json.dumps(self._digests, sort_keys=True) + "\n" + ) + + def build(self, recipe: Recipe) -> bytes | None: + """Return the TorrentZip bytes for *recipe*, or None if incomplete.""" + key = tuple(recipe) + if key not in self._built: + if all(crc in self for _name, crc in recipe): + self._built[key] = build_torrentzip( + [(name, self.read(crc)) for name, crc in recipe] + ) + else: + self._built[key] = None + return self._built[key] + + +DIGEST_CACHE = REPO_ROOT / ".cache" / "romset_digests.json" +# The writer's own source is part of every key: a change to how TorrentZip +# bytes are laid out invalidates every digest it produced. +_WRITER = hashlib.sha256( + (REPO_ROOT / "scripts" / "core" / "torrentzip.py").read_bytes() +).hexdigest()[:16] + + +def _recipe_key(recipe: Recipe) -> str: + members = json.dumps([[name, crc.lower()] for name, crc in recipe]) + return hashlib.sha256(f"{_WRITER}:{members}".encode()).hexdigest() + + +def _read_digests(path: Path | None) -> dict[str, list]: + if path is None: + return {} + try: + with open(path, encoding="utf-8") as handle: + data = json.load(handle) + except FileNotFoundError: + return {} + except (OSError, ValueError) as exc: + print(f" digest cache {path} unreadable, rebuilding: {exc}", file=sys.stderr) + return {} + return data if isinstance(data, dict) else {} diff --git a/scripts/recipes/romsets.py b/scripts/recipes/romsets.py new file mode 100644 index 000000000..6a7280498 --- /dev/null +++ b/scripts/recipes/romsets.py @@ -0,0 +1,79 @@ +"""Romset recipes: the (member, crc32) lists profiles and imported DATs give per archive.""" + +from __future__ import annotations + +import json +from collections import defaultdict +from pathlib import Path + + +Recipe = list[tuple[str, str]] + + +def load_dat_recipes(path: str | Path) -> dict[str, dict[str, Recipe]]: + """Recipes imported from MAME or FBNeo DATs. + + A DAT documents every set of one emulator version, where profiles only + document the few hundred the collection curates by hand. Labels are + prefixed so an identification says which DAT decided it. + """ + target = Path(path) + if target.is_dir(): + merged: dict[str, dict[str, Recipe]] = {} + for snapshot_file in sorted(target.glob("*.json")): + merged = merge_recipes(merged, load_dat_recipes(snapshot_file)) + return merged + snapshot_path = target + if not snapshot_path.is_file(): + return {} + with snapshot_path.open(encoding="utf-8") as handle: + snapshot = json.load(handle) + source = snapshot.get("source", "dat") + # A recipe shared by several versions is stored once under the earliest. + # The label therefore reads "unchanged since", not "is this version". + recipes: dict[str, dict[str, Recipe]] = defaultdict(dict) + for entry in snapshot.get("entries", []): + archive = entry.get("name", "") + members = entry.get("members", []) or [] + recipe = [ + (str(member["name"]), str(member.get("crc32") or "").lower()) + for member in members + if member.get("name") is not None + ] + if not archive or not recipe or not all(crc for _name, crc in recipe): + continue + label = f"{source}:{entry.get('dat', 'unnamed')}" + recipes[archive][label] = recipe + return dict(recipes) + + +def merge_recipes(*sources: dict[str, dict[str, Recipe]]) -> dict[str, dict[str, Recipe]]: + """Combine recipe sets, keeping every label distinct.""" + merged: dict[str, dict[str, Recipe]] = defaultdict(dict) + for source in sources: + for archive, per_label in source.items(): + merged[archive].update(per_label) + return dict(merged) + + +def collect_recipes(profiles: dict) -> dict[str, dict[str, Recipe]]: + """Map each archive name to one recipe per profile that documents it. + + A recipe is only usable when every member carries a CRC32: the pool is + addressed by content, so a member without one cannot be located. + """ + recipes: dict[str, dict[str, Recipe]] = defaultdict(dict) + for profile_name, profile in sorted(profiles.items()): + for entry in profile.get("files", []) or []: + contents = entry.get("contents") + archive = entry.get("name", "") + if not contents or not archive: + continue + recipe = [ + (str(member["name"]), str(member.get("crc32") or "").lower()) + for member in contents + if member.get("name") is not None + ] + if recipe and all(crc for _name, crc in recipe): + recipes[archive][profile_name] = recipe + return dict(recipes) diff --git a/scripts/romset_recipes.py b/scripts/romset_recipes.py index 83b08bae8..a9b78a538 100644 --- a/scripts/romset_recipes.py +++ b/scripts/romset_recipes.py @@ -43,10 +43,8 @@ Every archive the collection holds also has a recipe of its own in from __future__ import annotations import argparse -import hashlib import json import sys -import zipfile from collections import defaultdict from pathlib import Path @@ -56,403 +54,12 @@ from core.cli import require_directory from core.paths import REPO_ROOT from model.database import load_database from model.profiles import load_emulator_profiles -from model.platforms import load_platform_config -from model.registry import list_registered_platforms -from core.torrentzip import build_torrentzip, is_torrentzip +from recipes.identify import identify_report, missing_report, write_reconstructions +from recipes.pool import AtomPool, DIGEST_CACHE +from recipes.romsets import collect_recipes, load_dat_recipes, merge_recipes ARCHIVES_FILE = REPO_ROOT / "recipes" / "archives.json" -Recipe = list[tuple[str, str]] - - -def load_dat_recipes(path: str | Path) -> dict[str, dict[str, Recipe]]: - """Recipes imported from MAME or FBNeo DATs. - - A DAT documents every set of one emulator version, where profiles only - document the few hundred the collection curates by hand. Labels are - prefixed so an identification says which DAT decided it. - """ - target = Path(path) - if target.is_dir(): - merged: dict[str, dict[str, Recipe]] = {} - for snapshot_file in sorted(target.glob("*.json")): - merged = merge_recipes(merged, load_dat_recipes(snapshot_file)) - return merged - snapshot_path = target - if not snapshot_path.is_file(): - return {} - with snapshot_path.open(encoding="utf-8") as handle: - snapshot = json.load(handle) - source = snapshot.get("source", "dat") - # A recipe shared by several versions is stored once under the earliest. - # The label therefore reads "unchanged since", not "is this version". - recipes: dict[str, dict[str, Recipe]] = defaultdict(dict) - for entry in snapshot.get("entries", []): - archive = entry.get("name", "") - members = entry.get("members", []) or [] - recipe = [ - (str(member["name"]), str(member.get("crc32") or "").lower()) - for member in members - if member.get("name") is not None - ] - if not archive or not recipe or not all(crc for _name, crc in recipe): - continue - label = f"{source}:{entry.get('dat', 'unnamed')}" - recipes[archive][label] = recipe - return dict(recipes) - - -def merge_recipes(*sources: dict[str, dict[str, Recipe]]) -> dict[str, dict[str, Recipe]]: - """Combine recipe sets, keeping every label distinct.""" - merged: dict[str, dict[str, Recipe]] = defaultdict(dict) - for source in sources: - for archive, per_label in source.items(): - merged[archive].update(per_label) - return dict(merged) - - -def collect_recipes(profiles: dict) -> dict[str, dict[str, Recipe]]: - """Map each archive name to one recipe per profile that documents it. - - A recipe is only usable when every member carries a CRC32: the pool is - addressed by content, so a member without one cannot be located. - """ - recipes: dict[str, dict[str, Recipe]] = defaultdict(dict) - for profile_name, profile in sorted(profiles.items()): - for entry in profile.get("files", []) or []: - contents = entry.get("contents") - archive = entry.get("name", "") - if not contents or not archive: - continue - recipe = [ - (str(member["name"]), str(member.get("crc32") or "").lower()) - for member in contents - if member.get("name") is not None - ] - if recipe and all(crc for _name, crc in recipe): - recipes[archive][profile_name] = recipe - return dict(recipes) - - -class AtomPool: - """ROM bytes in the collection, addressed by CRC32. - - Members are located once and read on demand: arcade sample sets reach - hundreds of megabytes and a whole-pool preload buys nothing. - """ - - def __init__( - self, bios_dir: Path, digest_cache: Path | None = None, db: dict | None = None - ) -> None: - # crc32 -> (archive, member), or (file, None) for a loose ROM. - self._index: dict[str, tuple[Path, str | None]] = {} - # (md5, size) of each build, kept across runs: TorrentZip bytes are a - # function of the members alone, so a recipe hashed once is known - # until the writer changes. Rebuilding the 1 221 archives took 70 s - # of every pipeline run, 63 s of it in zlib. - self._digest_cache = digest_cache - self._digests: dict[str, list] = _read_digests(digest_cache) - self._digests_changed = False - # A recipe is built once: identification and reconstruction ask for the - # same archives, and every build re-reads and re-deflates its ROMs. - self._built: dict[tuple[tuple[str, str], ...], bytes | None] = {} - self.unreadable: list[str] = [] - for archive in sorted(bios_dir.rglob("*.zip")): - try: - with zipfile.ZipFile(archive) as handle: - for info in handle.infolist(): - if not info.is_dir(): - self._index.setdefault( - f"{info.CRC:08x}", (archive, info.filename) - ) - except (OSError, zipfile.BadZipFile) as exc: - self.unreadable.append(f"{archive}: {exc}") - # Loose ROMs, by the crc32 the database already computed: nmk004.zip - # needs nmk004.bin, which the collection holds only as a file. - root = bios_dir.resolve() - for entry in ((db or {}).get("files") or {}).values(): - crc, path = str(entry.get("crc32") or "").lower(), entry.get("path", "") - if not crc or not path or path.lower().endswith(".zip"): - continue - loose = Path(path) - if root in loose.resolve().parents and loose.is_file(): - self._index.setdefault(crc, (loose, None)) - - def __len__(self) -> int: - return len(self._index) - - def __contains__(self, crc32: str) -> bool: - return crc32.lower() in self._index - - def read(self, crc32: str) -> bytes: - archive, member = self._index[crc32.lower()] - if member is None: - return archive.read_bytes() - with zipfile.ZipFile(archive) as handle: - return handle.read(member) - - def digest(self, recipe: Recipe) -> tuple[str, int] | None: - """(md5, size) of the recipe's TorrentZip build, None if incomplete.""" - if not all(crc in self for _name, crc in recipe): - return None - key = _recipe_key(recipe) - known = self._digests.get(key) - if known is None: - blob = self.build(recipe) - if blob is None: - return None - known = self._digests[key] = [hashlib.md5(blob).hexdigest(), len(blob)] - self._digests_changed = True - return known[0], known[1] - - def save_digests(self) -> None: - """Write the digest cache back, when this run learned anything.""" - if self._digest_cache is None or not self._digests_changed: - return - from core.artifacts import write_text_atomic - - self._digest_cache.parent.mkdir(parents=True, exist_ok=True) - write_text_atomic( - str(self._digest_cache), json.dumps(self._digests, sort_keys=True) + "\n" - ) - - def build(self, recipe: Recipe) -> bytes | None: - """Return the TorrentZip bytes for *recipe*, or None if incomplete.""" - key = tuple(recipe) - if key not in self._built: - if all(crc in self for _name, crc in recipe): - self._built[key] = build_torrentzip( - [(name, self.read(crc)) for name, crc in recipe] - ) - else: - self._built[key] = None - return self._built[key] - - -DIGEST_CACHE = REPO_ROOT / ".cache" / "romset_digests.json" -# The writer's own source is part of every key: a change to how TorrentZip -# bytes are laid out invalidates every digest it produced. -_WRITER = hashlib.sha256( - (REPO_ROOT / "scripts" / "core" / "torrentzip.py").read_bytes() -).hexdigest()[:16] - - -def _recipe_key(recipe: Recipe) -> str: - members = json.dumps([[name, crc.lower()] for name, crc in recipe]) - return hashlib.sha256(f"{_WRITER}:{members}".encode()).hexdigest() - - -def _read_digests(path: Path | None) -> dict[str, list]: - if path is None: - return {} - try: - with open(path, encoding="utf-8") as handle: - data = json.load(handle) - except FileNotFoundError: - return {} - except (OSError, ValueError) as exc: - print(f" digest cache {path} unreadable, rebuilding: {exc}", file=sys.stderr) - return {} - return data if isinstance(data, dict) else {} - - -def identify_archive( - path: Path, recipes: dict[str, Recipe], pool: AtomPool -) -> str | None: - """Return the recipe label that reproduces *path* byte for byte. - - Equal bytes need equal (name, crc32) members, which the archive's - central directory gives without inflating anything: building every - recipe at DEFLATE level 9 first took 94 s and 1 GB at pipeline step 1c. - """ - held = _member_list(path) - if held is None: - return None - original = path.read_bytes() - md5, size = hashlib.md5(original).hexdigest(), len(original) - for label, recipe in sorted(recipes.items()): - if sorted((name, crc.lower()) for name, crc in recipe) != held: - continue - if pool.digest(recipe) == (md5, size): - return label - return None - - -def _member_list(path: Path) -> list[tuple[str, str]] | None: - """Sorted (name, crc32) of an archive's members, from its directory.""" - try: - with zipfile.ZipFile(path) as archive: - return sorted( - (info.filename, format(info.CRC, "08x")) - for info in archive.infolist() if not info.is_dir() - ) - except (zipfile.BadZipFile, OSError) as exc: - print(f" UNREADABLE: {path}: {exc}", file=sys.stderr) - return None - - -def reconstruct( - target_md5: str, recipes: dict[str, Recipe], pool: AtomPool -) -> tuple[str, bytes] | None: - """Return the (label, bytes) whose TorrentZip build matches *target_md5*.""" - target = target_md5.lower() - for label, recipe in sorted(recipes.items()): - known = pool.digest(recipe) - if known is not None and known[0] == target: - blob = pool.build(recipe) - if blob is not None and hashlib.md5(blob).hexdigest() == target: - return label, blob - return None - - -def platform_targets(platforms_dir: str) -> dict[str, set[str]]: - """Container MD5s the platforms pin, per archive name. - - ``zipped_file`` entries pin an inner ROM instead of the container, so - their MD5 is not an archive hash and is skipped. So is a Recalbox md5, - the composite of the members (``zip_digest: composite``, Bios.cpp:64-68): - no container build can ever give it. - """ - targets: dict[str, set[str]] = defaultdict(set) - for name in list_registered_platforms(platforms_dir): - config = load_platform_config(name, platforms_dir) - for system in config.get("systems", {}).values(): - for entry in system.get("files", []) or []: - archive = entry.get("name", "") - if ( - not archive.endswith(".zip") - or entry.get("zipped_file") - or entry.get("zip_digest") == "composite" - ): - continue - for value in str(entry.get("md5") or "").split(","): - value = value.strip().lower() - if len(value) == 32: - targets[archive].add(value) - return dict(targets) - - -def _is_archive(path: Path) -> bool: - """Whether *path* is a readable ZIP. - - A name index entry can be an alias: ``d2fdc.zip`` names a loose Apple II - ROM, not an archive. Recipes only describe archives. - """ - try: - with zipfile.ZipFile(path): - return True - except (OSError, zipfile.BadZipFile): - return False - - -def _local_paths(archive: str, db: dict) -> list[Path]: - matches = db["indexes"]["by_name"].get(archive) or [] - if isinstance(matches, str): - matches = [matches] - paths = [Path(db["files"][sha1]["path"]) for sha1 in matches if sha1 in db["files"]] - return [path for path in paths if path.is_file() and _is_archive(path)] - - -def identify_report( - recipes: dict[str, dict[str, Recipe]], pool: AtomPool, db: dict -) -> dict: - """Label every archive the collection holds with the version it matches.""" - identified: list[dict] = [] - unidentified: list[dict] = [] - for archive, per_profile in sorted(recipes.items()): - for path in _local_paths(archive, db): - label = identify_archive(path, per_profile, pool) - record = { - "archive": archive, - "path": str(path), - "torrentzip": is_torrentzip(path), - } - if label: - record["recipe"] = label - identified.append(record) - else: - record["candidates"] = sorted(per_profile) - unidentified.append(record) - return {"identified": identified, "unidentified": unidentified} - - -def missing_report( - recipes: dict[str, dict[str, Recipe]], - pool: AtomPool, - db: dict, - platforms_dir: str, -) -> dict: - """Pinned archives the collection lacks, split by why they are absent.""" - have = set(db["indexes"]["by_md5"]) - constructible: list[dict] = [] - no_recipe: list[dict] = [] - unreproducible: list[dict] = [] - for archive, pinned in sorted(platform_targets(platforms_dir).items()): - per_profile = recipes.get(archive, {}) - for target in sorted(pinned - have): - if not per_profile: - no_recipe.append({"archive": archive, "md5": target}) - continue - found = reconstruct(target, per_profile, pool) - if found: - label, blob = found - constructible.append( - { - "archive": archive, - "md5": target, - "recipe": label, - "size": len(blob), - } - ) - else: - usable = [ - label - for label, recipe in per_profile.items() - if all(crc in pool for _name, crc in recipe) - ] - unreproducible.append( - { - "archive": archive, - "md5": target, - "recipes_tried": sorted(usable), - "reason": ( - "no recipe reproduces this MD5: the pinned archive is " - "not TorrentZip or follows a recipe not documented here" - if usable - else "ROMs for every documented recipe are missing" - ), - } - ) - return { - "constructible": constructible, - "unreproducible": unreproducible, - "no_recipe": no_recipe, - } - - -def write_reconstructions( - entries: list[dict], - recipes: dict[str, dict[str, Recipe]], - pool: AtomPool, - bios_dir: Path, - db: dict, -) -> list[str]: - """Write each constructible archive beside its set, as a variant.""" - written: list[str] = [] - for entry in entries: - archive = entry["archive"] - recipe = recipes[archive][entry["recipe"]] - blob = pool.build(recipe) - if blob is None: - continue - siblings = _local_paths(archive, db) - parent = siblings[0].parent if siblings else bios_dir - destination = parent / ".variants" / f"{archive}.{entry['md5'][:8]}" - destination.parent.mkdir(parents=True, exist_ok=True) - destination.write_bytes(blob) - written.append(str(destination)) - return written - def print_missing(gap: dict) -> None: """The pinned archives the collection lacks, each one named.""" @@ -480,21 +87,22 @@ def print_missing(gap: dict) -> None: def run_capture(args: argparse.Namespace, db: dict) -> int: """Write recipes/archives.json for every archive the database lists.""" - import archive_build + from recipes import capture + from recipes import ledger as recipes_ledger try: - records, failed = archive_build.capture( + records, failed = capture.capture( db, - archive_build.load_ledger(Path(args.archives)), - archive_build.recipe_index(args.emulators_dir, args.dat_recipes), - archive_build.container_pins(args.platforms_dir, args.emulators_dir), + recipes_ledger.load_ledger(Path(args.archives)), + capture.recipe_index(args.emulators_dir, args.dat_recipes), + capture.container_pins(args.platforms_dir, args.emulators_dir), ) - except archive_build.ZlibNgError as exc: + except capture.ZlibNgError as exc: print(f"ERROR: {exc}", file=sys.stderr) return 2 for path, reason in sorted(failed.items()): print(f" UNREADABLE: {path}: {reason}", file=sys.stderr) - changed = archive_build.write_ledger(records, Path(args.archives)) + changed = recipes_ledger.write_ledger(records, Path(args.archives)) by_class: dict[str, int] = defaultdict(int) for record in records.values(): by_class[record["rebuild"]] += 1 @@ -511,31 +119,33 @@ def run_capture(args: argparse.Namespace, db: dict) -> int: def run_build(args: argparse.Namespace, db: dict) -> int: """Build one archive, or all of them, from the members the collection holds.""" - import archive_build + from core import torrentzip + from recipes import build as recipes_build + from recipes import ledger as recipes_ledger if not args.output_dir: print("ERROR: --build and --build-all need --output-dir", file=sys.stderr) return 2 - ledger = archive_build.load_ledger(Path(args.archives)) + ledger = recipes_ledger.load_ledger(Path(args.archives)) if args.build_all: records = [ledger[path] for path in sorted(ledger)] else: - records = archive_build.select(ledger, args.build) + records = recipes_build.select(ledger, args.build) if not records: print(f"ERROR: no archive recipe named {args.build}", file=sys.stderr) return 2 - ng = archive_build.zlib_ng_version() + ng = torrentzip.zlib_ng_version() if ng: print( f" zlib-ng {ng} in use: TorrentZip bytes are stock zlib's output, so no " "build is claimed exact here; exact recipes are checked by their members" ) root = Path(args.bios_dir).resolve().parent - atoms = archive_build.AtomIndex.from_collection(ledger, db, root) + atoms = recipes_build.AtomIndex.from_collection(ledger, db, root) counts: dict[str, int] = defaultdict(int) own: list[tuple[str, int]] = [] for record in records: - result = archive_build.build_archive(record, atoms, Path(args.output_dir), root) + result = recipes_build.build_archive(record, atoms, Path(args.output_dir), root) counts[result.status] += 1 if result.own_members: own.append((result.path, result.own_members)) diff --git a/scripts/sitegen/build.py b/scripts/sitegen/build.py index 56ea71f94..1fe6195c1 100644 --- a/scripts/sitegen/build.py +++ b/scripts/sitegen/build.py @@ -11,7 +11,7 @@ from collections.abc import Callable from dataclasses import dataclass from pathlib import Path -import archive_build +from recipes import ledger import release_record from model import siteinputs from model.collection import _group_by_manufacturer, _slug @@ -24,7 +24,7 @@ from model.registry import list_registered_platforms from model.safeparse import yaml_load from model.systemnames import program_names, set_console_sections, system_name from packs.crossref import FileConsumers -from provenance_report import build_report, profile_needs +from acquire.provenance import build_report, profile_needs from resolve.cores import resolve_platform_cores from resolve.review import load_platform_hashes, load_profile_hashes from sitegen import ( @@ -492,7 +492,7 @@ def _write_gap_pages(run: _SiteRun, provenance_report: dict) -> None: print("Generating the wanted page...") wanted = sitewanted.build_wanted( profiles, coverages, run.gap_report, db, placer, system_name, - sitewanted.load_ledger(archive_build.ARCHIVES_FILE), + sitewanted.load_ledger(ledger.ARCHIVES_FILE), _wanted_link(profiles), ) (public / "data").mkdir(parents=True, exist_ok=True) @@ -547,7 +547,7 @@ def _write_wiki_pages(run: _SiteRun, measured: sitemeasurements.Built) -> None: recipes_page = _REPO_ROOT / ARCHIVE_RECIPES_PAGE if recipes_page.is_file(): write_if_changed(str(recipes_page), with_archive_counts( - recipes_page.read_text(encoding="utf-8"), archive_build.rebuild_counts())) + recipes_page.read_text(encoding="utf-8"), ledger.rebuild_counts())) if wiki_src.is_dir(): for src_file in wiki_src.glob("*.md"): shutil.copy2(src_file, wiki_dest / src_file.name) diff --git a/scripts/sitegen/dataexports.py b/scripts/sitegen/dataexports.py index 48460e9b9..931a85fe6 100644 --- a/scripts/sitegen/dataexports.py +++ b/scripts/sitegen/dataexports.py @@ -19,7 +19,7 @@ from core.artifacts import json_text as _json_text from model import retired as model_retired from model.dumpcatalog import load_provenance_snapshots from packs.crossref import FileConsumers -from provenance_report import build_report +from acquire.provenance import build_report from sitegen.apiitems import _sha1_by_path, core_index_items, system_index_items from sitegen.config import DATA_LICENSE, REPO_URL, _REPO_ROOT, _timestamp from sitegen.install import _release_pack_platforms diff --git a/scripts/sitegen/provenance.py b/scripts/sitegen/provenance.py index 0beaee5d5..747d5e8a1 100644 --- a/scripts/sitegen/provenance.py +++ b/scripts/sitegen/provenance.py @@ -7,7 +7,7 @@ import json from datetime import datetime from model.composition import compute_composition, count_catalog_matched -from provenance_report import distinct_missing +from acquire.provenance import distinct_missing from sitegen import entries as siteentries, markup from sitegen.cards import _PROVENANCE_LABELS, _ROMSET_SOURCES from sitegen.config import _date_line diff --git a/scripts/sitegen/readme.py b/scripts/sitegen/readme.py index 1135339d5..59ba623ba 100644 --- a/scripts/sitegen/readme.py +++ b/scripts/sitegen/readme.py @@ -11,7 +11,7 @@ from datetime import datetime, timezone from pathlib import Path from types import ModuleType -import archive_build +from recipes import ledger import pr_checks import release_record from core.artifacts import write_if_changed @@ -728,7 +728,7 @@ def generate_readme(db: dict, platforms_dir: str, db_path: str = "database.json" " the file name for RetroArch, as their own code does", f"- **{len(system_ids)} systems**, {total_files:,} files in the collection," f" [what is still missing]({SITE_URL}gaps/) named file by file", - archive_line(archive_build.rebuild_counts()), + archive_line(ledger.rebuild_counts()), f"- Public data: [JSON, CSV and SQLite]({SITE_URL}data/), the metadata under MIT", "", "
", diff --git a/scripts/sitegen/wanted.py b/scripts/sitegen/wanted.py index 2f70f01e6..66435d7ff 100644 --- a/scripts/sitegen/wanted.py +++ b/scripts/sitegen/wanted.py @@ -21,7 +21,7 @@ import urllib.parse from collections.abc import Callable, Iterable from pathlib import Path -import archive_build +from recipes import ledger as recipes_ledger from resolve.layout import runs_standalone from model.profiles import unique_emulator_profiles from packs.crossref import _first_hash @@ -523,7 +523,7 @@ def _merge_named(records: dict[tuple, dict]) -> None: def load_ledger(path: Path) -> list[dict]: """The archive records of recipes/archives.json, empty when absent.""" - return list(archive_build.load_ledger(path).values()) + return list(recipes_ledger.load_ledger(path).values()) def page(total: int, known: int) -> str: diff --git a/tests/test_archive_build.py b/tests/test_archive_build.py index f5543e1b5..c9d7fcaa3 100644 --- a/tests/test_archive_build.py +++ b/tests/test_archive_build.py @@ -18,7 +18,9 @@ import zipfile from pathlib import Path from unittest import mock -import archive_build +from recipes import build as recipes_build +from recipes import capture as recipes_capture +from recipes import ledger from core.torrentzip import build_torrentzip ROOT = Path(__file__).resolve().parent.parent @@ -41,8 +43,8 @@ class TheLedgerCoversTheCollection(unittest.TestCase): def setUpClass(cls): with (ROOT / "database.json").open(encoding="utf-8") as handle: cls.db = json.load(handle) - cls.ledger = archive_build.load_ledger() - cls.archives = archive_build.database_archives(cls.db) + cls.ledger = ledger.load_ledger() + cls.archives = ledger.database_archives(cls.db) def test_every_database_archive_has_a_recipe(self): absent = sorted(set(self.archives) - set(self.ledger)) @@ -77,15 +79,15 @@ class TheLedgerCoversTheCollection(unittest.TestCase): def test_every_member_is_held_in_the_collection(self): """The list printed here is the acquisition list: a member neither held as a loose file nor inside any archive the database lists.""" - missing = archive_build.missing_members(self.ledger, self.db) + missing = ledger.missing_members(self.ledger, self.db) listing = "\n".join( f" {m['archive']}: {m['member']} ({m['sha1']})" for m in missing ) self.assertEqual(missing, [], f"members held nowhere:\n{listing}") def test_the_file_is_written_the_one_way(self): - text = archive_build.ARCHIVES_FILE.read_text(encoding="utf-8") - self.assertEqual(text, archive_build.ledger_text(self.ledger)) + text = ledger.ARCHIVES_FILE.read_text(encoding="utf-8") + self.assertEqual(text, ledger.ledger_text(self.ledger)) def test_recipes_describe_the_archives_on_disk(self): """Names in order, sizes and crc32 against each central directory.""" @@ -139,7 +141,7 @@ class Fixture(unittest.TestCase): self.temp.cleanup() def capture(self, **kwargs) -> dict[str, dict]: - records, failed = archive_build.capture( + records, failed = recipes_capture.capture( self.db, kwargs.get("previous", {}), kwargs.get("index", {}), kwargs.get("pins", {}), workers=1, log=lambda _line: None, ) @@ -175,7 +177,7 @@ class Capture(Fixture): self.assertEqual(exact["sources"], ["collection"]) def test_dat_agreement_and_pins_are_recorded(self): - key = archive_build.member_key( + key = recipes_capture.member_key( [{"name": n, "crc32": c} for n, c in ( ("a.rom", self._crc(ROM_A)), ("b.rom", self._crc(ROM_B)), ("c.rom", self._crc(ROM_C)), @@ -197,8 +199,8 @@ class Capture(Fixture): self.assertEqual(records["bios/set.zip"]["members"][0]["sha1"], "kept") def test_zlib_ng_refuses_to_capture(self): - with mock.patch.object(archive_build, "zlib_ng_version", lambda: "2.2.4"), \ - self.assertRaises(archive_build.ZlibNgError): + with mock.patch.object(recipes_build, "zlib_ng_version", lambda: "2.2.4"), \ + self.assertRaises(recipes_capture.ZlibNgError): self.capture() def test_composite_and_zipped_pins_name_no_container(self): @@ -229,7 +231,7 @@ class Capture(Fixture): f" - name: set.zip\n sha1: {'d' * 40}\n", encoding="utf-8", ) - pins = archive_build.container_pins(str(platforms), str(emulators)) + pins = recipes_capture.container_pins(str(platforms), str(emulators)) self.assertEqual(pins, {"a" * 32: {"platform:plain"}, "d" * 40: {"profile:core"}}) @staticmethod @@ -248,11 +250,11 @@ class Build(Fixture): os.chdir(self.root) self.ledger = self.capture() os.chdir(self._cwd) - self.atoms = archive_build.AtomIndex.from_collection(self.ledger, self.db, self.root) + self.atoms = recipes_build.AtomIndex.from_collection(self.ledger, self.db, self.root) self.out = self.root / "out" def build(self, path: str): - return archive_build.build_archive(self.ledger[path], self.atoms, self.out, self.root) + return recipes_build.build_archive(self.ledger[path], self.atoms, self.out, self.root) def test_an_exact_recipe_rebuilds_the_bytes(self): result = self.build("bios/set.zip") @@ -279,14 +281,14 @@ class Build(Fixture): record["members"] = record["members"] + [ {"name": "gone.rom", "size": 1, "crc32": "00000000", "sha1": "f" * 40} ] - result = archive_build.build_archive(record, self.atoms, self.out, self.root) + result = recipes_build.build_archive(record, self.atoms, self.out, self.root) self.assertEqual(result.status, "impossible") self.assertEqual([m["name"] for m in result.missing], ["gone.rom"]) self.assertFalse(self.out.exists()) def test_a_mismatch_is_never_promoted(self): record = dict(self.ledger["bios/set.zip"], sha1="0" * 40) - result = archive_build.build_archive(record, self.atoms, self.out, self.root) + result = recipes_build.build_archive(record, self.atoms, self.out, self.root) self.assertEqual(result.status, "failed") self.assertIn("is not the recorded", result.detail) self.assertEqual(list(self.out.rglob("*")), [], "no file, no scratch left") @@ -295,37 +297,37 @@ class Build(Fixture): record = dict(self.ledger["bios/other.zip"]) record["members"] = [dict(m) for m in record["members"]] record["members"][0]["crc32"] = "00000000" - result = archive_build.build_archive(record, self.atoms, self.out, self.root) + result = recipes_build.build_archive(record, self.atoms, self.out, self.root) self.assertEqual(result.status, "failed") self.assertEqual(list(self.out.rglob("*")), []) def test_zlib_ng_never_claims_exact(self): - with mock.patch.object(archive_build, "zlib_ng_version", lambda: "2.2.4"): + with mock.patch.object(recipes_build, "zlib_ng_version", lambda: "2.2.4"): result = self.build("bios/set.zip") self.assertEqual(result.status, "canonical") self.assertIn("zlib-ng 2.2.4", result.detail) def test_an_archive_is_named_by_path_or_by_name(self): self.assertEqual( - [r["path"] for r in archive_build.select(self.ledger, "set.zip", self.root)], + [r["path"] for r in recipes_build.select(self.ledger, "set.zip", self.root)], ["bios/set.zip"], ) self.assertEqual( - len(archive_build.select(self.ledger, str(self.exact_path), self.root)), 1 + len(recipes_build.select(self.ledger, str(self.exact_path), self.root)), 1 ) - self.assertEqual(archive_build.select(self.ledger, "none.zip", self.root), []) + self.assertEqual(recipes_build.select(self.ledger, "none.zip", self.root), []) def test_missing_members_reads_the_committed_data(self): - self.assertEqual(archive_build.missing_members(self.ledger, self.db), []) + self.assertEqual(ledger.missing_members(self.ledger, self.db), []) del self.db["files"][_sha1(self.exact_path.read_bytes())] - missing = archive_build.missing_members(self.ledger, self.db) + missing = ledger.missing_members(self.ledger, self.db) self.assertEqual( [(m["archive"], m["member"]) for m in missing], [("bios/set.zip", "c.rom")] ) def test_the_command_reports_each_archive(self): archives = self.root / "archives.json" - archives.write_text(archive_build.ledger_text(self.ledger), encoding="utf-8") + archives.write_text(ledger.ledger_text(self.ledger), encoding="utf-8") db = self.root / "database.json" db.write_text(json.dumps(self.db), encoding="utf-8") run = subprocess.run( diff --git a/tests/test_archive_recipes.py b/tests/test_archive_recipes.py index a868634f1..0bbe0a1e9 100644 --- a/tests/test_archive_recipes.py +++ b/tests/test_archive_recipes.py @@ -85,7 +85,7 @@ def _hashes(values: object) -> set[str]: def _allowed_members() -> dict[str, set[str]]: from model.profiles import load_emulator_profiles - from romset_recipes import load_dat_recipes + from recipes.romsets import load_dat_recipes allowed: dict[str, set[str]] = defaultdict(set) for archive, per_label in load_dat_recipes(REPO_ROOT / "recipes").items(): diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index 574d1ad84..485277049 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -922,17 +922,17 @@ class AutoFetchReadsListsAndPlacesWithoutClobbering(unittest.TestCase): def test_a_hash_list_is_every_accepted_revision(self): import hashlib - from scripts import auto_fetch + from scripts.acquire import fetch as acquire_fetch data = b"second revision" entry = {"sha1": ["0" * 40, hashlib.sha1(data).hexdigest()]} - self.assertTrue(auto_fetch.verify_content(data, entry)) + self.assertTrue(acquire_fetch.verify_content(data, entry)) db = {"files": {hashlib.sha1(data).hexdigest(): {"path": "bios/x/n64.psh"}}, "indexes": {"by_md5": {}}} - self.assertEqual(auto_fetch.step1_crossref_db(entry, db), "bios/x/n64.psh") + self.assertEqual(acquire_fetch.step1_crossref_db(entry, db), "bios/x/n64.psh") def test_the_whole_slug_picks_the_folder_and_nothing_is_overwritten(self): - from scripts import auto_fetch + from scripts.acquire import fetch as acquire_fetch with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: bios = Path(directory) @@ -940,7 +940,7 @@ class AutoFetchReadsListsAndPlacesWithoutClobbering(unittest.TestCase): (bios / folder).mkdir(parents=True) held = bios / "Nintendo" / "N64" / "n64.psh" held.write_bytes(b"other revision") - placed = Path(auto_fetch.place_file( + placed = Path(acquire_fetch.place_file( b"fetched", {"name": "n64.psh", "system": "nintendo-64"}, str(bios), {} )) self.assertEqual(placed.parent.parent, bios / "Nintendo" / "N64") @@ -4623,7 +4623,7 @@ class TheWantedPageCountsRomsetMembers(unittest.TestCase): Wanted page asked for dumps the collection holds inside romsets.""" def test_members_are_read_unless_given(self): - from scripts import provenance_report + from scripts.acquire import provenance calls = [] @@ -4631,9 +4631,9 @@ class TheWantedPageCountsRomsetMembers(unittest.TestCase): calls.append(db) return {} - with mock.patch.object(provenance_report, "archive_members", members): - provenance_report.build_report({"files": {}}, {}) - provenance_report.build_report({"files": {}}, {}, {}) + with mock.patch.object(provenance, "archive_members", members): + provenance.build_report({"files": {}}, {}) + provenance.build_report({"files": {}}, {}, {}) self.assertEqual(len(calls), 1) @@ -4644,7 +4644,7 @@ class AutoFetchAsksVerifyWhatIsMissing(unittest.TestCase): file was ever one. 721 announced where verify saw none critical.""" def test_the_targets_are_verify_verdicts(self): - from scripts import auto_fetch + from scripts.acquire import fetch as acquire_fetch from packs import coverage as packs_coverage from packs import verdicts @@ -4671,7 +4671,7 @@ class AutoFetchAsksVerifyWhatIsMissing(unittest.TestCase): ], } with mock.patch.object(packs_coverage, "verify_platform", lambda c, d: result): - names = [m["name"] for m in auto_fetch.find_missing(config, {})] + names = [m["name"] for m in acquire_fetch.find_missing(config, {})] self.assertEqual(names, ["gone.bin", "bad.bin", "diabdat.mpq"]) @@ -6668,7 +6668,7 @@ class AnUnansweredSearchIsNotANotFound(unittest.TestCase): def _fetch(self, error): from unittest import mock - from scripts import auto_fetch + from scripts.acquire import fetch as acquire_fetch def refuse(*_args, **_kwargs): raise error @@ -6676,9 +6676,9 @@ class AnUnansweredSearchIsNotANotFound(unittest.TestCase): entry = {"name": "nowhere.bin", "system": "test-system", "sha1": "0" * 40} db = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}}} with mock.patch("urllib.request.urlopen", refuse), \ - mock.patch.object(auto_fetch, "step2_scan_branches", lambda e: None), \ + mock.patch.object(acquire_fetch, "step2_scan_branches", lambda e: None), \ contextlib.redirect_stdout(io.StringIO()): - return auto_fetch.fetch_missing([entry], db, "bios") + return acquire_fetch.fetch_missing([entry], db, "bios") def test_offline_is_not_searched(self): import urllib.error @@ -6705,21 +6705,21 @@ class AutoFetchProvesEveryHashItIsGiven(unittest.TestCase): def test_a_sha256_proves_a_download(self): import hashlib - from scripts import auto_fetch + from scripts.acquire import fetch as acquire_fetch sha256 = {"sha256": hashlib.sha256(self.DATA).hexdigest()} - self.assertTrue(auto_fetch.verify_content(self.DATA, sha256)) - self.assertFalse(auto_fetch.verify_content(b"other", sha256)) + self.assertTrue(acquire_fetch.verify_content(self.DATA, sha256)) + self.assertFalse(acquire_fetch.verify_content(b"other", sha256)) def test_every_declared_cryptographic_hash_must_match(self): import hashlib - from scripts import auto_fetch + from scripts.acquire import fetch as acquire_fetch both = {"sha256": hashlib.sha256(self.DATA).hexdigest(), "md5": "0" * 32} - self.assertFalse(auto_fetch.verify_content(self.DATA, both)) + self.assertFalse(acquire_fetch.verify_content(self.DATA, both)) both["md5"] = hashlib.md5(self.DATA).hexdigest() - self.assertTrue(auto_fetch.verify_content(self.DATA, both)) + self.assertTrue(acquire_fetch.verify_content(self.DATA, both)) def test_crc32_and_size_never_accept_a_download(self): """A crc32 can be forged: bytes a source crafts to it would land in @@ -6728,44 +6728,44 @@ class AutoFetchProvesEveryHashItIsGiven(unittest.TestCase): import zlib from unittest import mock - from scripts import auto_fetch + from scripts.acquire import fetch as acquire_fetch crc = {"name": "forged.bin", "system": "test-system", "crc32": f"{zlib.crc32(self.DATA):08X}", "size": len(self.DATA)} - self.assertFalse(auto_fetch.verify_content(self.DATA, crc)) - self.assertFalse(auto_fetch.verifiable(crc)) + self.assertFalse(acquire_fetch.verify_content(self.DATA, crc)) + self.assertFalse(acquire_fetch.verifiable(crc)) served = io.BytesIO(self.DATA) with tempfile.TemporaryDirectory() as bios, \ mock.patch.object(urllib.request, "urlopen", lambda *a, **k: served), \ - mock.patch.object(auto_fetch, "step2_scan_branches", + mock.patch.object(acquire_fetch, "step2_scan_branches", lambda e: self.DATA), \ contextlib.redirect_stdout(io.StringIO()) as out: - result = auto_fetch.fetch_missing([crc], {"files": {}}, bios) + result = acquire_fetch.fetch_missing([crc], {"files": {}}, bios) self.assertEqual(list(Path(bios).rglob("*")), []) self.assertEqual(result["stats"]["found"], 0) self.assertEqual(result["stats"]["unverifiable"], 1) self.assertIn("declares no cryptographic hash", out.getvalue()) def test_a_held_sha256_is_found_in_the_database(self): - from scripts import auto_fetch + from scripts.acquire import fetch as acquire_fetch db = {"files": {"s": {"path": "bios/x/dsi.bin", "size": 3}}, "indexes": {"by_sha256": {"f" * 64: "s"}}} self.assertEqual( - auto_fetch.step1_crossref_db({"sha256": "F" * 64}, db), "bios/x/dsi.bin" + acquire_fetch.step1_crossref_db({"sha256": "F" * 64}, db), "bios/x/dsi.bin" ) def test_an_entry_without_a_hash_is_not_searched(self): from unittest import mock - from scripts import auto_fetch + from scripts.acquire import fetch as acquire_fetch entry = {"name": "DICROM.ROM", "system": "fujitsu-fm7"} out = io.StringIO() - with mock.patch.object(auto_fetch, "step2_scan_branches") as branches, \ + with mock.patch.object(acquire_fetch, "step2_scan_branches") as branches, \ contextlib.redirect_stdout(out): - result = auto_fetch.fetch_missing([entry], {"files": {}}, "bios", dry_run=True) + result = acquire_fetch.fetch_missing([entry], {"files": {}}, "bios", dry_run=True) branches.assert_not_called() self.assertEqual(result["stats"]["unverifiable"], 1) self.assertNotIn("Would search", out.getvalue()) @@ -7848,9 +7848,9 @@ class AutoFetchIssueBodyReadsAsWritten(unittest.TestCase): "md5": "490f666e1afb15b7362b406ed1cea246"} def test_full_hashes_and_no_template_phrasing(self): - from scripts import auto_fetch + from scripts.acquire import fetch as acquire_fetch - body = auto_fetch.generate_issue_body([self.ENTRY], "RetroArch") + body = acquire_fetch.generate_issue_body([self.ENTRY], "RetroArch") self.assertIn(f"`{self.ENTRY['sha1']}`", body) self.assertIn(f"`{self.ENTRY['md5']}`", body) self.assertNotIn("...", body) diff --git a/tests/test_auto_fetch_lookup.py b/tests/test_auto_fetch_lookup.py index f9352be87..0002f787e 100644 --- a/tests/test_auto_fetch_lookup.py +++ b/tests/test_auto_fetch_lookup.py @@ -16,6 +16,7 @@ from pathlib import Path from unittest import mock import auto_fetch +from acquire import fetch PAYLOAD = b"keyboard mcu" SHA1 = hashlib.sha1(PAYLOAD).hexdigest() @@ -46,24 +47,24 @@ def _serving(payloads: dict[str, bytes]): class SoftwareHeritageAnswersByContent(unittest.TestCase): def test_the_bytes_it_serves_are_kept_when_the_hash_holds(self): - urlopen, asked = _serving({f"{auto_fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/": PAYLOAD}) + urlopen, asked = _serving({f"{fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/": PAYLOAD}) with mock.patch.object(auto_fetch.urllib.request, "urlopen", urlopen): - data = auto_fetch.step3b_software_heritage({"name": "D8039HLC.rom", "sha1": SHA1}) + data = fetch.step3b_software_heritage({"name": "D8039HLC.rom", "sha1": SHA1}) self.assertEqual(data, PAYLOAD) - self.assertEqual(asked, [f"{auto_fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/"]) + self.assertEqual(asked, [f"{fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/"]) def test_other_bytes_under_the_hash_are_refused(self): - urlopen, _asked = _serving({auto_fetch.SOFTWARE_HERITAGE: b"something else"}) + urlopen, _asked = _serving({fetch.SOFTWARE_HERITAGE: b"something else"}) with mock.patch.object(auto_fetch.urllib.request, "urlopen", urlopen): - data = auto_fetch.step3b_software_heritage({"name": "x", "sha1": SHA1}) + data = fetch.step3b_software_heritage({"name": "x", "sha1": SHA1}) self.assertIsNone(data) def test_an_absent_file_is_not_counted_as_a_source_that_did_not_answer(self): urlopen, _asked = _serving({}) - auto_fetch._UNANSWERED.clear() + fetch._UNANSWERED.clear() with mock.patch.object(auto_fetch.urllib.request, "urlopen", urlopen): - self.assertIsNone(auto_fetch.step3b_software_heritage({"name": "x", "sha1": SHA1})) - self.assertEqual(auto_fetch._UNANSWERED, []) + self.assertIsNone(fetch.step3b_software_heritage({"name": "x", "sha1": SHA1})) + self.assertEqual(fetch._UNANSWERED, []) class LookupBySha1(unittest.TestCase): @@ -74,10 +75,10 @@ class LookupBySha1(unittest.TestCase): self.addCleanup(os.chdir, self.cwd) def test_a_found_file_goes_to_tmp_acquire_never_to_bios(self): - urlopen, _asked = _serving({f"{auto_fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/": PAYLOAD}) + urlopen, _asked = _serving({f"{fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/": PAYLOAD}) with mock.patch.object(auto_fetch.urllib.request, "urlopen", urlopen), \ contextlib.redirect_stdout(io.StringIO()) as out: - code = auto_fetch.lookup_sha1s([SHA1.upper()], {"files": {}}) + code = fetch.lookup_sha1s([SHA1.upper()], {"files": {}}) self.assertEqual(code, 0) self.assertEqual((self.root / "tmp" / "acquire" / SHA1).read_bytes(), PAYLOAD) self.assertFalse((self.root / "bios").exists()) @@ -88,7 +89,7 @@ class LookupBySha1(unittest.TestCase): db = {"files": {SHA1: {"path": "bios/Commodore/Amiga/x.rom"}}} with mock.patch.object(auto_fetch.urllib.request, "urlopen", urlopen), \ contextlib.redirect_stdout(io.StringIO()) as out: - code = auto_fetch.lookup_sha1s([SHA1], db) + code = fetch.lookup_sha1s([SHA1], db) self.assertEqual((code, asked), (0, [])) self.assertIn("already held at bios/Commodore/Amiga/x.rom", out.getvalue()) @@ -97,7 +98,7 @@ class LookupBySha1(unittest.TestCase): with mock.patch.object(auto_fetch.urllib.request, "urlopen", urlopen), \ contextlib.redirect_stdout(io.StringIO()) as out, \ contextlib.redirect_stderr(io.StringIO()) as err: - code = auto_fetch.lookup_sha1s([SHA1, "not-a-hash"], {"files": {}}) + code = fetch.lookup_sha1s([SHA1, "not-a-hash"], {"files": {}}) self.assertEqual(code, 1) self.assertIn(f"{SHA1}: not found", out.getvalue()) self.assertIn("not-a-hash: not a sha1", err.getvalue()) diff --git a/tests/test_derivations.py b/tests/test_derivations.py index a620327d8..165919123 100644 --- a/tests/test_derivations.py +++ b/tests/test_derivations.py @@ -18,7 +18,7 @@ import unittest.mock import zlib from pathlib import Path -import derivations +from acquire import derivations REPO_ROOT = Path(__file__).resolve().parent.parent @@ -153,7 +153,7 @@ class CombineMatchesZlib(unittest.TestCase): import os import zlib - from derivations import crc32_combine + from acquire.derivations import crc32_combine for size in (1, 2, 3, 7, 100, 4096, 65537, 1000003): with self.subTest(size=size): diff --git a/tests/test_doc_surfaces.py b/tests/test_doc_surfaces.py index a664d89f7..1a4f562c7 100644 --- a/tests/test_doc_surfaces.py +++ b/tests/test_doc_surfaces.py @@ -650,15 +650,15 @@ class ArchiveRecipesAreCountedFromTheRecipes(unittest.TestCase): that file, never typed.""" def setUp(self) -> None: - import archive_build + from recipes import ledger - records = archive_build.load_ledger().values() + records = ledger.load_ledger().values() self.counts = { "total": len(records), "exact": sum(r["rebuild"] == "exact" for r in records), "canonical": sum(r["rebuild"] == "canonical" for r in records), } - self.assertEqual(archive_build.rebuild_counts(), self.counts) + self.assertEqual(ledger.rebuild_counts(), self.counts) self.assertEqual(self.counts["exact"] + self.counts["canonical"], self.counts["total"]) def test_the_readme_line(self) -> None: diff --git a/tests/test_find_embedded.py b/tests/test_find_embedded.py index 3df63bdd6..4f1079a4a 100644 --- a/tests/test_find_embedded.py +++ b/tests/test_find_embedded.py @@ -19,6 +19,7 @@ from pathlib import Path from unittest import mock import find_embedded +from acquire import embedded ROM = bytes(random.Random(8039).randrange(256) for _ in range(2048)) CRC = zlib.crc32(ROM) @@ -29,11 +30,11 @@ class RollingWindow(unittest.TestCase): def test_every_offset_matches_a_direct_crc(self): noise = random.Random(1).randbytes(5000) data = noise[:777] + ROM + noise[777:3000] + ROM + noise[3000:] - self.assertEqual(find_embedded.offsets(data, CRC, len(ROM)), [777, 777 + 2048 + 2223]) + self.assertEqual(embedded.offsets(data, CRC, len(ROM)), [777, 777 + 2048 + 2223]) def test_the_file_itself_and_a_short_file(self): - self.assertEqual(find_embedded.offsets(ROM, CRC, len(ROM)), [0]) - self.assertEqual(find_embedded.offsets(ROM[:100], CRC, len(ROM)), []) + self.assertEqual(embedded.offsets(ROM, CRC, len(ROM)), [0]) + self.assertEqual(embedded.offsets(ROM[:100], CRC, len(ROM)), []) class Command(unittest.TestCase): diff --git a/tests/test_find_pinned_revision.py b/tests/test_find_pinned_revision.py index 1f1e67747..6cb3d3a91 100644 --- a/tests/test_find_pinned_revision.py +++ b/tests/test_find_pinned_revision.py @@ -12,7 +12,7 @@ import hashlib import unittest from unittest import mock -import find_pinned_revision +from acquire import history from core import upstream @@ -28,10 +28,10 @@ class ThePinnedRevisionIsInTheHistory(unittest.TestCase): return next(data for sha, data in blobs.items() if f"/{sha}/" in url) with mock.patch.object(upstream, "_api", api), mock.patch.object(upstream, "_fetch", fetch): - found = find_pinned_revision.find_revision( + found = history.find_revision( repo, "dists/engine-data/queen.tbl", hashlib.md5(b"pinned").hexdigest(), "unused") - missing = find_pinned_revision.find_revision( + missing = history.find_revision( repo, "dists/engine-data/queen.tbl", "0" * 32, "unused") self.assertEqual(found, ("c2", b"pinned")) self.assertIsNone(missing) diff --git a/tests/test_provenance.py b/tests/test_provenance.py index 2fefc73ad..953bc2d40 100644 --- a/tests/test_provenance.py +++ b/tests/test_provenance.py @@ -17,7 +17,7 @@ from scripts.model.dumpcatalog import ( write_provenance_snapshot, ) from scripts.sitegen.provenance import generate_provenance_page -from scripts.provenance_report import build_report +from scripts.acquire.provenance import build_report from scripts.scraper.dat_pack_importer import _bios_entries, import_pack from scripts.scraper.logiqx_parser import parse_logiqx, validate_logiqx_format from scripts.scraper.redump_dat_scraper import discover_bios_datfiles, parse_redump_dat @@ -430,7 +430,7 @@ class HeldUnderAnAlias(unittest.TestCase): } def _needs(self, **fields): - from scripts.provenance_report import profile_needs + from scripts.acquire.provenance import profile_needs entry = {"name": "KANJI2.ROM", "size": 131072, **fields} return profile_needs({"emu": {"files": [entry]}}, self.DB)["by_name"] @@ -555,7 +555,7 @@ class ArchiveMembersAreHeld(unittest.TestCase): import hashlib import zlib - from scripts.provenance_report import archive_members + from scripts.acquire.provenance import archive_members data = b"bally" * 400 with tempfile.TemporaryDirectory() as tmp: @@ -582,7 +582,7 @@ class OneDumpIsCountedOnce(unittest.TestCase): the site's Wanted page published the larger number.""" def test_a_dump_in_several_dats_is_one_missing_entry(self): - from scripts import provenance_report + from scripts.acquire import provenance as acquire_provenance rom = {"name": "DICROM.rom", "sha1": "a" * 40, "size": 32768} held = {"name": "held.rom", "sha1": "b" * 40, "size": 16} @@ -591,13 +591,13 @@ class OneDumpIsCountedOnce(unittest.TestCase): {**rom, "dat": "FM-7 (Flux)"}, {**held, "dat": "FM-7 (Flux)"}, ]}} db = {"files": {"b" * 40: {"md5": "", "size": 16}}} - report = provenance_report.build_report(db, snapshots, {}) + report = acquire_provenance.build_report(db, snapshots, {}) (entry,) = report["no-intro"]["missing"] self.assertEqual(entry["dats"], ["FM-7 (Bitstream)", "FM-7 (Flux)"]) self.assertEqual(report["no-intro"]["matched"], 1) - self.assertEqual(provenance_report.distinct_missing(report), 1) + self.assertEqual(acquire_provenance.distinct_missing(report), 1) twice = {"redump": report["no-intro"], "no-intro": report["no-intro"]} - self.assertEqual(provenance_report.distinct_missing(twice), 1) + self.assertEqual(acquire_provenance.distinct_missing(twice), 1) class AMissingDumpNamesTheProfileItFills(unittest.TestCase): @@ -613,7 +613,7 @@ class AMissingDumpNamesTheProfileItFills(unittest.TestCase): } def _report(self, db): - from scripts import provenance_report + from scripts.acquire import provenance as acquire_provenance snapshots = {"no-intro": {"entries": [ {"dat": "FM-7", "name": "DICROM.rom", "sha1": "a" * 40, "size": 262144}, @@ -621,8 +621,8 @@ class AMissingDumpNamesTheProfileItFills(unittest.TestCase): {"dat": "FM-7", "name": "Other Name.rom", "sha1": "c" * 40, "size": 8}, {"dat": "FM-7", "name": "unread.rom", "sha1": "d" * 40, "size": 8}, ]}} - needs = provenance_report.profile_needs(self.PROFILES, db) - return provenance_report.build_report(db, snapshots, {}, {}, needs) + needs = acquire_provenance.profile_needs(self.PROFILES, db) + return acquire_provenance.build_report(db, snapshots, {}, {}, needs) def test_a_dump_a_profile_reads_names_it(self): db = {"files": {"b" * 40: {"name": "held.rom", "md5": "", "size": 16}}} @@ -635,23 +635,23 @@ class AMissingDumpNamesTheProfileItFills(unittest.TestCase): self.assertIsNone(missing["unread.rom"]) def test_a_size_outside_the_profile_range_fills_nothing(self): - from scripts import provenance_report + from scripts.acquire import provenance as acquire_provenance - needs = provenance_report.profile_needs(self.PROFILES, {"files": {}}) + needs = acquire_provenance.profile_needs(self.PROFILES, {"files": {}}) small = {"name": "DICROM.rom", "size": 1024} - self.assertEqual(provenance_report.needs_filled(small, needs), []) + self.assertEqual(acquire_provenance.needs_filled(small, needs), []) def test_a_need_the_collection_answers_is_not_one(self): - from scripts import provenance_report + from scripts.acquire import provenance as acquire_provenance db = {"files": {"e" * 40: {"name": "dicrom.rom", "size": 262144}}} - needs = provenance_report.profile_needs(self.PROFILES, db) + needs = acquire_provenance.profile_needs(self.PROFILES, db) self.assertNotIn("dicrom.rom", needs["by_name"]) def test_a_file_installed_with_the_emulator_is_not_a_need(self): """43 of 50 needs were bundled entries (samcoupe.rom, zesarux's tk90x.rom), burying the six xm7 ROMs a maintainer has to find.""" - from scripts import provenance_report + from scripts.acquire import provenance as acquire_provenance profiles = { "samcoupe": {"files": [{"name": "samcoupe.rom", "required": True, @@ -659,7 +659,7 @@ class AMissingDumpNamesTheProfileItFills(unittest.TestCase): "hcl": {"files": [{"name": "kanji.rom", "required": True, "bundled": True, "not_bundled_on": ["batocera"], "sha1": "9" * 40}]}, } - needs = provenance_report.profile_needs(profiles, {"files": {}}) + needs = acquire_provenance.profile_needs(profiles, {"files": {}}) self.assertNotIn(("sha1", "f" * 40), needs["by_hash"]) self.assertIn(("sha1", "9" * 40), needs["by_hash"]) @@ -695,7 +695,7 @@ class MissingDumpsNameTheirRomsets(unittest.TestCase): spectrum.zip: the report said MISSING and nothing about where to look.""" def _index(self, entries: list[dict]) -> dict: - from scripts.provenance_report import romset_index + from scripts.acquire.provenance import romset_index with tempfile.TemporaryDirectory() as tmp: Path(tmp, "mame.json").write_text( @@ -704,7 +704,7 @@ class MissingDumpsNameTheirRomsets(unittest.TestCase): return romset_index(Path(tmp)) def test_versions_of_one_set_merge(self): - from scripts.provenance_report import romsets_holding + from scripts.acquire.provenance import romsets_holding member = {"name": "1986es.rom", "size": 16384, "crc32": "aaaa0001", "sha1": "f9"} index = self._index([ @@ -718,7 +718,7 @@ class MissingDumpsNameTheirRomsets(unittest.TestCase): self.assertEqual(hits[0]["dats"], ["MAME mame0190", "MAME mame0220", "MAME mame0289"]) def test_a_disagreeing_sha1_is_not_the_dump(self): - from scripts.provenance_report import romsets_holding + from scripts.acquire.provenance import romsets_holding member = {"name": "a.rom", "size": 8, "crc32": "00000001", "sha1": "aa"} index = self._index([{"name": "set.zip", "members": [member], "dats": ["MAME mame0190"]}]) diff --git a/tests/test_romset_recipes.py b/tests/test_romset_recipes.py index 08cd75fd3..6e9586b9c 100644 --- a/tests/test_romset_recipes.py +++ b/tests/test_romset_recipes.py @@ -13,13 +13,11 @@ import zipfile import zlib from pathlib import Path -from romset_recipes import ( - AtomPool, - collect_recipes, +from recipes.pool import AtomPool +from recipes.romsets import collect_recipes, load_dat_recipes, merge_recipes +from recipes.identify import ( identify_archive, identify_report, - load_dat_recipes, - merge_recipes, missing_report, reconstruct, write_reconstructions, @@ -717,7 +715,7 @@ class IdentificationReadsTheDirectoryFirst(unittest.TestCase): def test_a_recipe_with_other_members_is_never_built(self): from core.torrentzip import build_torrentzip - import romset_recipes + from recipes import identify rom = b"rom bytes" crc = format(zlib.crc32(rom), "08x") @@ -739,7 +737,7 @@ class IdentificationReadsTheDirectoryFirst(unittest.TestCase): return hashlib.md5(blob).hexdigest(), len(blob) pool = Pool() - label = romset_recipes.identify_archive( + label = identify.identify_archive( archive, {"other": [("b.rom", crc)], "match": [("a.rom", crc)]}, pool) self.assertEqual(label, "match") self.assertEqual(pool.built, [[("a.rom", crc)]])