refactor: one recipe rule, one reconstruction

This commit is contained in:
Abdessamad Derraz committed 2026-11-18 19:58:21 +01:00
1 parent 41da592291
commit b0b505dc94
4 files changed
+32 -67

No files matched your search

+2 -23
View File
@@ -7,10 +7,10 @@ member names and their contents.
That property makes it possible to rebuild a romset ZIP that matches an
upstream-published hash exactly, and to identify which romset revision a
published hash refers to.
published hash refers to (scripts/recipes/).
Usage:
from core.torrentzip import build_torrentzip, identify_romset
from core.torrentzip import build_torrentzip
data = build_torrentzip([("sp-s2.sp1", rom_bytes), ...])
md5 = hashlib.md5(data).hexdigest()
@@ -184,24 +184,3 @@ def is_torrentzip(source: str | Path) -> bool:
"""Report whether an archive already carries the TorrentZip signature."""
with zipfile.ZipFile(source) as zf:
return zf.comment.decode("ascii", "replace").startswith(_COMMENT_PREFIX)
def identify_romset(
recipes: dict[str, list[tuple[str, str]]],
atoms: dict[str, bytes],
target_md5: str,
) -> str | None:
"""Find which recipe rebuilds to a target archive MD5.
recipes maps a label (e.g. a MAME version) to a list of
(member name, CRC32 hex) pairs, and atoms maps CRC32 hex to ROM bytes.
Returns the matching label, or None when no recipe reproduces the hash.
"""
target = target_md5.lower()
for label, recipe in recipes.items():
if any(crc.lower() not in atoms for _, crc in recipe):
continue
members = [(name, atoms[crc.lower()]) for name, crc in recipe]
if hashlib.md5(build_torrentzip(members)).hexdigest() == target:
return label
return None
+17 -19
View File
@@ -6,10 +6,21 @@ import json
from collections import defaultdict
from pathlib import Path
Recipe = list[tuple[str, str]]
def usable_recipe(members: list[dict]) -> Recipe | None:
"""The (name, crc32) list of named members, None when it is empty or a
member lacks a crc32: the pool is addressed by content, so a member
without one cannot be located."""
recipe = [
(str(member["name"]), str(member.get("crc32") or "").lower())
for member in members
if member.get("name") is not None
]
return recipe if recipe and all(crc for _name, crc in recipe) else None
def load_dat_recipes(path: str | Path) -> dict[str, dict[str, Recipe]]:
"""Recipes imported from MAME or FBNeo DATs.
@@ -34,13 +45,8 @@ def load_dat_recipes(path: str | Path) -> dict[str, dict[str, Recipe]]:
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):
recipe = usable_recipe(entry.get("members", []) or [])
if not archive or recipe is None:
continue
label = f"{source}:{entry.get('dat', 'unnamed')}"
recipes[archive][label] = recipe
@@ -57,11 +63,7 @@ def merge_recipes(*sources: dict[str, dict[str, Recipe]]) -> dict[str, dict[str,
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.
"""
"""Map each archive name to one usable recipe per profile that documents it."""
recipes: dict[str, dict[str, Recipe]] = defaultdict(dict)
for profile_name, profile in sorted(profiles.items()):
for entry in profile.get("files", []) or []:
@@ -69,11 +71,7 @@ def collect_recipes(profiles: dict) -> dict[str, dict[str, Recipe]]:
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):
recipe = usable_recipe(contents)
if recipe is not None:
recipes[archive][profile_name] = recipe
return dict(recipes)
+12
View File
@@ -135,6 +135,18 @@ class PoolAndBuild(unittest.TestCase):
self.assertEqual(found[0], "v1")
self.assertEqual(hashlib.md5(found[1]).hexdigest(), target)
def test_reconstruct_selects_the_recipe_with_every_member(self):
crc_a, crc_b = _crc(ROM_A), _crc(ROM_B)
wanted = hashlib.md5(
build_torrentzip([("a.rom", ROM_A), ("b.rom", ROM_B)])
).hexdigest()
recipes = {"v1": [("a.rom", crc_a)], "v2": [("a.rom", crc_a), ("b.rom", crc_b)]}
self.assertEqual(reconstruct(wanted, recipes, self.pool)[0], "v2")
self.assertIsNone(reconstruct("0" * 32, recipes, self.pool))
def test_reconstruct_skips_recipes_with_absent_atoms(self):
self.assertIsNone(reconstruct("0" * 32, {"v1": [("a.rom", "ffffffff")]}, self.pool))
class ReportsOverAFixture(unittest.TestCase):
"""A whole run over a synthetic collection, database and platform."""
+1 -25
View File
@@ -10,7 +10,7 @@ import tempfile
import unittest
import zipfile
from core.torrentzip import build_torrentzip, identify_romset, is_torrentzip, rebuild_torrentzip
from core.torrentzip import build_torrentzip, is_torrentzip, rebuild_torrentzip
REPO_ROOT = os.path.join(os.path.dirname(__file__), "..")
@@ -114,30 +114,6 @@ class TorrentZipTest(unittest.TestCase):
if not checked:
self.skipTest("corrected romsets not present in this checkout")
def test_identify_romset_selects_matching_recipe(self):
atoms = {"3610a686": b"alpha", "9d0d1b46": b"beta"}
import zlib
atoms = {
f"{zlib.crc32(b'alpha') & 0xffffffff:08x}": b"alpha",
f"{zlib.crc32(b'beta') & 0xffffffff:08x}": b"beta",
}
crc_a, crc_b = list(atoms)
wanted = hashlib.md5(
build_torrentzip([("a.rom", b"alpha"), ("b.rom", b"beta")])
).hexdigest()
recipes = {
"v1": [("a.rom", crc_a)],
"v2": [("a.rom", crc_a), ("b.rom", crc_b)],
}
self.assertEqual(identify_romset(recipes, atoms, wanted), "v2")
self.assertIsNone(identify_romset(recipes, atoms, "0" * 32))
def test_identify_romset_skips_recipes_with_absent_atoms(self):
atoms = {"aaaaaaaa": b"x"}
recipes = {"v1": [("a.rom", "ffffffff")]}
self.assertIsNone(identify_romset(recipes, atoms, "0" * 32))
def _as_file(test: unittest.TestCase, data: bytes) -> str:
"""Write bytes to a temp file cleaned up with the test."""