refactor: move recipes and acquisition to packages

This commit is contained in:
Abdessamad Derraz committed 2026-11-18 19:49:49 +01:00
1 parent 664776ae91
commit 0e4e5f450d
35 files changed
+2186 -2071

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Acquisition: dump-catalog coverage, dumps a held file already contains, and the searches that find a missing file."""
File renamed without changes.
+67
View File
@@ -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)
+577
View File
@@ -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/<sha1>, 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)
+53
View File
@@ -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
+335
View File
@@ -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
-544
View File
@@ -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:<name>`` or ``profile:<name>``.
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
]
+1 -570
View File
@@ -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/<sha1>, 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")
+2 -59
View File
@@ -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:
+1 -46
View File
@@ -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:
+8 -327
View File
@@ -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():
+1
View File
@@ -0,0 +1 @@
"""Archive recipes: romset identification, rebuilt pinned archives, and the recipe and build of every archive the collection holds."""
+179
View File
@@ -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]
+229
View File
@@ -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:<name>`` or ``profile:<name>``.
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."
)
+213
View File
@@ -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
+122
View File
@@ -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
]
+46
View File
@@ -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()
+135
View File
@@ -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 {}
+79
View File
@@ -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)
+19 -409
View File
@@ -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))
+4 -4
View File
@@ -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)
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+2 -2
View File
@@ -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",
"",
"<details>",
+2 -2
View File
@@ -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: