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."""
+301
View File
@@ -0,0 +1,301 @@
"""Catalog entries whose bytes a held dump already contains.
A catalog lists chips as they come off the board, while a collection often holds
the image an emulator reads. The Amiga 3.1 Kickstart pair 391773/391774 is
the high and low 16-bit words of amiga-os-310-a1200.rom, byte-swapped, and the
TOSEC "Basic V7" is basiclo and basichi end to end. Listed as missing, they
send a maintainer after files that are already here. Each transform below is
one the source boards use. A match is by sha1, never by size or name.
"""
from __future__ import annotations
import array
import functools
import hashlib
import os
import zipfile
from collections import defaultdict
from collections.abc import Callable, Iterable, Sequence
# A held file larger than this is not read: no chip image is near it.
MAX_SOURCE_SIZE = 64 * 1024 * 1024
def _swap16(data: bytes) -> bytes:
swapped = bytearray(data)
swapped[0::2], swapped[1::2] = data[1::2], data[0::2]
return bytes(swapped)
def _words(data: bytes, start: int) -> bytes:
"""Every other 16-bit word, from word `start`, bytes kept in order.
Read as an array of 2-byte units and strided: joining slices one word
at a time made this pass take most of an hour over the romset chips.
"""
words = array.array("H")
words.frombytes(data[: len(data) - len(data) % 2])
return words[start::2].tobytes()
# (name, size of the output for an input of size n or None, transform)
TRANSFORMS: tuple[tuple[str, Callable[[int], int | None], Callable[[bytes], bytes]], ...] = (
("first half", lambda n: n // 2 if n % 2 == 0 else None, lambda d: d[:len(d) // 2]),
("second half", lambda n: n // 2 if n % 2 == 0 else None, lambda d: d[len(d) // 2:]),
*(
(f"quarter {q + 1}", lambda n: n // 4 if n % 4 == 0 else None,
lambda d, q=q: d[q * len(d) // 4:(q + 1) * len(d) // 4])
for q in range(4)
),
("even bytes", lambda n: n // 2 if n % 2 == 0 else None, lambda d: d[0::2]),
("odd bytes", lambda n: n // 2 if n % 2 == 0 else None, lambda d: d[1::2]),
("even words", lambda n: n // 2 if n % 4 == 0 else None, lambda d: _words(d, 0)),
("odd words", lambda n: n // 2 if n % 4 == 0 else None, lambda d: _words(d, 1)),
("even words, byte-swapped", lambda n: n // 2 if n % 4 == 0 else None,
lambda d: _swap16(_words(d, 0))),
("odd words, byte-swapped", lambda n: n // 2 if n % 4 == 0 else None,
lambda d: _swap16(_words(d, 1))),
("byte-swapped", lambda n: n if n % 2 == 0 else None, _swap16),
("mirrored twice", lambda n: n * 2, lambda d: d + d),
)
def _gf2_times(matrix: Sequence[int], vector: int) -> int:
total, row = 0, 0
while vector:
if vector & 1:
total ^= matrix[row]
vector >>= 1
row += 1
return total
def _gf2_square(matrix: Sequence[int]) -> list[int]:
return [_gf2_times(matrix, matrix[n]) for n in range(32)]
def crc32_combine(crc1: int, crc2: int, len2: int) -> int:
"""crc32 of A + B from crc32(A), crc32(B) and len(B), as zlib computes it."""
if len2 <= 0:
return crc1
return _gf2_times(_shift_operator(len2), crc1) ^ crc2
@functools.cache
def _byte_shift(power: int) -> tuple[int, ...]:
"""The operator for 2**power zero bytes appended, as zlib squares it:
three squarings of the one-bit operator give one byte, and each power
is the square of the one before."""
if power:
return tuple(_gf2_square(list(_byte_shift(power - 1))))
operator = [0xEDB88320] + [1 << (n - 1) for n in range(1, 32)]
for _ in range(3):
operator = _gf2_square(operator)
return tuple(operator)
@functools.cache
def _shift_operator(len2: int) -> tuple[int, ...]:
"""The linear map zlib applies to crc(A) for len2 bytes appended.
The product of the power-of-two operators the set bits of len2 select.
Those powers are shared by every length, so each is squared once for the
whole pass: squaring the chain again for each of the 3 600 lengths a
romset pairs spent most of the crc work in GF(2) products.
"""
columns = [1 << bit for bit in range(32)]
power = 0
while len2:
if len2 & 1:
matrix = _byte_shift(power)
columns = [_gf2_times(matrix, column) for column in columns]
len2 >>= 1
power += 1
return tuple(columns)
def _read(held: dict, archives: dict[str, zipfile.ZipFile] | None = None) -> bytes | None:
"""The bytes of a held file, or of a member read out of its archive.
`archives` keeps each archive open across its members: reopened for
every one, a MAME set of a hundred chips parsed its directory a
hundred times.
"""
try:
if held.get("member"):
if archives is None:
with zipfile.ZipFile(held["archive"]) as zf:
return zf.read(held["member"])
opened = archives.get(held["archive"])
if opened is None:
opened = archives[held["archive"]] = zipfile.ZipFile(held["archive"])
return opened.read(held["member"])
with open(held["path"], "rb") as handle:
return handle.read()
except (OSError, KeyError, zipfile.BadZipFile):
return None
def _held_sources(db: dict) -> list[dict]:
"""Every file the collection holds, the members of its archives included.
A romset holds chips a catalog lists on their own: cdi910.rom inside
cdi910.zip is the CD-i 910 BIOS byte-swapped, and the two halves of the
Salora Manager sit in manager.zip. Read from the top level alone, they
stayed MISSING. A member's group is its archive, as a file's is its
directory: the pairs a catalog splits come from one machine.
"""
sources: list[dict] = []
for record in db.get("files", {}).values():
path = record.get("path", "")
if not os.path.exists(path):
continue
if 0 < record.get("size", 0) <= MAX_SOURCE_SIZE:
sources.append({**record, "group": os.path.dirname(path)})
if not path.lower().endswith(".zip"):
continue
try:
with zipfile.ZipFile(path) as zf:
infos = [i for i in zf.infolist() if not i.is_dir()]
except (OSError, zipfile.BadZipFile):
continue
sources.extend(
{
"path": f"{path}/{info.filename}", "archive": path,
"member": info.filename, "size": info.file_size,
"crc32": f"{info.CRC:08x}", "group": path,
}
for info in infos
if 0 < info.file_size <= MAX_SOURCE_SIZE
)
return sources
def derivable(entries: Iterable[dict], db: dict) -> dict[str, dict]:
"""Missing sha1 to the held file or member and the transform that
produce its bytes. Archives stay open for the whole pass."""
archives: dict[str, zipfile.ZipFile] = {}
try:
return _derivable(entries, db, archives)
finally:
for zf in archives.values():
zf.close()
def _derivable(
entries: Iterable[dict], db: dict, archives: dict[str, zipfile.ZipFile]
) -> dict[str, dict]:
"""Only held files whose size can produce a wanted size are read, and a
concatenation is only tried within one directory or one archive: the
chip pairs a catalog splits come from one machine.
"""
wanted: dict[tuple[int, str], str] = {}
by_size_crc: dict[tuple[int, int], list[str]] = defaultdict(list)
for entry in entries:
sha1, size = (entry.get("sha1") or "").lower(), entry.get("size")
if sha1 and isinstance(size, int) and size > 0:
wanted[(size, sha1)] = sha1
crc = entry.get("crc32")
if crc:
by_size_crc[(size, int(str(crc), 16))].append(sha1)
sizes = {size for size, _sha1 in wanted}
found: dict[str, dict] = {}
files = _held_sources(db)
_find_transformed(files, wanted, sizes, archives, found)
_find_concatenated(files, by_size_crc, sizes, archives, found)
return found
def _find_transformed(
files: list[dict],
wanted: dict[tuple[int, str], str],
sizes: set[int],
archives: dict[str, zipfile.ZipFile],
found: dict[str, dict],
) -> None:
"""Record each wanted sha1 one transform of a held file produces."""
# The same chip sits in many archives. Its transforms are a function of
# its bytes alone, and the first path read keeps the match, so a content
# already transformed has nothing left to find.
transformed: set[str] = set()
for held in files:
n = held["size"]
useful = [
(name, size_out, transform) for name, out_size, transform in TRANSFORMS
if (size_out := out_size(n)) is not None and size_out in sizes
]
if not useful:
continue
data = _read(held, archives)
if data is None:
continue
content = hashlib.sha1(data).hexdigest()
if content in transformed:
continue
transformed.add(content)
for name, size_out, transform in useful:
out = transform(data)
sha1 = wanted.get((size_out, hashlib.sha1(out).hexdigest()))
if sha1 and sha1 not in found:
found[sha1] = {"from": [held["path"]], "transform": name}
def _find_concatenated(
files: list[dict],
by_size_crc: dict[tuple[int, int], list[str]],
sizes: set[int],
archives: dict[str, zipfile.ZipFile],
found: dict[str, dict],
) -> None:
"""Record each wanted sha1 two held files of one group make end to end."""
# Romsets repeat the same chip pairs: a combined crc is computed once.
combined: dict[tuple[str, str, int], int] = {}
by_dir: dict[str, list[dict]] = defaultdict(list)
for held in files:
if held.get("crc32"):
by_dir[held["group"]].append(held)
for group in by_dir.values():
# A pair is only worth a crc when its sizes add up to a wanted one:
# indexed by size, a member is paired once per size the group
# holds, and a romset of a few hundred chips stays linear.
by_size: dict[int, list[dict]] = defaultdict(list)
for held in group:
by_size[held["size"]].append(held)
for first in group:
for second_size, seconds in by_size.items():
total = first["size"] + second_size
if total not in sizes:
continue
for second in seconds:
if first is not second:
_try_pair(first, second, total, combined, by_size_crc, archives, found)
def _try_pair(
first: dict,
second: dict,
total: int,
combined: dict[tuple[str, str, int], int],
by_size_crc: dict[tuple[int, int], list[str]],
archives: dict[str, zipfile.ZipFile],
found: dict[str, dict],
) -> None:
"""Record the wanted sha1 first + second makes, if their crc names one."""
key = (first["crc32"], second["crc32"], second["size"])
crc = combined.get(key)
if crc is None:
crc = combined[key] = crc32_combine(
int(first["crc32"], 16), int(second["crc32"], 16), second["size"])
candidates = [s for s in by_size_crc.get((total, crc), [])
if s not in found]
if not candidates:
return
a, b = _read(first, archives), _read(second, archives)
if a is None or b is None:
return
sha1 = hashlib.sha1(a + b).hexdigest()
if sha1 in candidates:
found[sha1] = {"from": [first["path"], second["path"]],
"transform": "concatenated"}
+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