From d6769915029f0794e12eb867d8c70771c5484cbc Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sun, 22 Nov 2026 03:18:02 +0100 Subject: [PATCH] fix: root database paths at the bios parent Identification, the atom pool and capture opened database paths against the working directory while the build read them under the parent of --bios-dir. Against a worktree copy the pool dropped every loose ROM and the survey read the main checkout. romrecipes.collection now holds the one rule and every reader goes through it, select included. --- scripts/romrecipes/build.py | 18 ++++++++--------- scripts/romrecipes/capture.py | 24 ++++++++++++++-------- scripts/romrecipes/collection.py | 15 ++++++++++++++ scripts/romrecipes/identify.py | 33 +++++++++++++++++++------------ scripts/romrecipes/pool.py | 9 ++++++--- scripts/romrecipes/runs.py | 8 +++++--- tests/sources.py | 2 +- tests/test_archive_build.py | 20 +------------------ tests/test_romset_recipes.py | 34 ++++++++++++++++++++++++++++++++ 9 files changed, 107 insertions(+), 56 deletions(-) create mode 100644 scripts/romrecipes/collection.py diff --git a/scripts/romrecipes/build.py b/scripts/romrecipes/build.py index a9c5ccdb2..4e328ac66 100644 --- a/scripts/romrecipes/build.py +++ b/scripts/romrecipes/build.py @@ -9,9 +9,9 @@ from dataclasses import dataclass, field from pathlib import Path from core.hashing import compute_hashes -from core.paths import REPO_ROOT from core.torrentzip import write_torrentzip, zlib_ng_version from core.ziptools import is_archive_path, zip_members +from romrecipes.collection import on_disk from romrecipes.members import member_sha1, member_opener @@ -35,11 +35,11 @@ class AtomIndex: 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", "") + path = on_disk(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 + path = on_disk(root, archive) if not path.is_file(): continue for member in record.get("members", []): @@ -97,7 +97,7 @@ def build_archive( record: dict, atoms: AtomIndex, output_dir: Path, - root: Path = REPO_ROOT, + root: Path, attempts: int = 2, ) -> BuildResult: """Build *record* from held members into *output_dir*, verified. @@ -109,7 +109,7 @@ def build_archive( checked by its members only and never reported exact. """ path = record["path"] - own = root / path + own = on_disk(root, path) sources: list[tuple[str, Source]] = [] missing: list[dict] = [] for member in record["members"]: @@ -155,7 +155,7 @@ def build_archive( return BuildResult(path, "failed", detail=detail, own_members=own_members) -def select(ledger: dict[str, dict], wanted: str, root: Path = REPO_ROOT) -> list[dict]: +def select(ledger: dict[str, dict], wanted: str, root: Path) -> list[dict]: """Records named by a path (relative or absolute) or by a file name.""" candidate = Path(wanted) if candidate.is_absolute(): @@ -169,11 +169,11 @@ def select(ledger: dict[str, dict], wanted: str, root: Path = REPO_ROOT) -> list return [record for path, record in sorted(ledger.items()) if Path(path).name == wanted] -def build_targets(ledger: dict[str, dict], wanted: str | None) -> list[dict]: - """Every record in path order when *wanted* is None, else those it names.""" +def build_targets(ledger: dict[str, dict], wanted: str | None, root: Path) -> list[dict]: + """Every record in path order when *wanted* is None, else those it names under *root*.""" if wanted is None: return [ledger[path] for path in sorted(ledger)] - return select(ledger, wanted) + return select(ledger, wanted, root) def build_records( diff --git a/scripts/romrecipes/capture.py b/scripts/romrecipes/capture.py index 74bc27fee..3e0c51a8b 100644 --- a/scripts/romrecipes/capture.py +++ b/scripts/romrecipes/capture.py @@ -13,6 +13,7 @@ from typing import BinaryIO from core.hashing import parse_hash_list from core.torrentzip import has_torrentzip_comment, write_torrentzip, zlib_ng_version +from romrecipes.collection import on_disk from romrecipes.ledger import database_archives, load_ledger, write_ledger from romrecipes.members import member_sha1, member_opener from romrecipes.pins import container_entries @@ -89,10 +90,10 @@ def read_archive(path: Path, sha1: str) -> dict: return record -def _read_job(job: tuple[str, str]) -> tuple[str, dict | str]: - path, sha1 = job +def _read_job(job: tuple[str, str, Path]) -> tuple[str, dict | str]: + path, sha1, root = job try: - return path, read_archive(Path(path), sha1) + return path, read_archive(on_disk(root, path), sha1) except (OSError, zipfile.BadZipFile, UnicodeEncodeError) as exc: return path, f"{type(exc).__name__}: {exc}" @@ -145,10 +146,11 @@ def capture( previous: dict[str, dict], index: dict[MemberList, set[str]], pins: dict[str, set[str]], + root: Path, 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 record for every archive in *db*, read under *root*, and those 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 @@ -158,13 +160,13 @@ def capture( raise ZlibNgError(zlib_ng_version()) archives = database_archives(db) reused: dict[str, dict] = {} - jobs: list[tuple[str, str]] = [] + jobs: list[tuple[str, str, Path]] = [] 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"])) + jobs.append((path, entry["sha1"], root)) read: dict[str, dict] = {} failed: dict[str, str] = {} if jobs: @@ -234,13 +236,19 @@ class CaptureRun: def capture_ledger( - archives: Path, db: dict, emulators_dir: str, dat_recipes: str, platforms_dir: str, + archives: Path, + db: dict, + root: Path, + emulators_dir: str, + dat_recipes: str, + platforms_dir: str, ) -> CaptureRun: - """Capture every archive of *db* against the ledger at *archives* and write it back.""" + """Capture every archive of *db* under *root* against the ledger at *archives*, written back.""" records, failed = capture( db, load_ledger(archives), recipe_index(emulators_dir, dat_recipes), container_pins(platforms_dir, emulators_dir), + root, ) return CaptureRun(records, failed, write_ledger(records, archives)) diff --git a/scripts/romrecipes/collection.py b/scripts/romrecipes/collection.py new file mode 100644 index 000000000..625c9f35f --- /dev/null +++ b/scripts/romrecipes/collection.py @@ -0,0 +1,15 @@ +"""Where a database.json path lands on disk: under the folder that holds the BIOS tree.""" + +from __future__ import annotations + +from pathlib import Path + + +def collection_root(bios_dir: Path) -> Path: + """The folder database paths (``bios/...``) are relative to: *bios_dir*'s parent.""" + return bios_dir.resolve().parent + + +def on_disk(root: Path, path: str) -> Path: + """The file a database *path* names under *root*. An absolute path stays as written.""" + return root / path diff --git a/scripts/romrecipes/identify.py b/scripts/romrecipes/identify.py index 13fe4fc5e..06531b192 100644 --- a/scripts/romrecipes/identify.py +++ b/scripts/romrecipes/identify.py @@ -10,6 +10,7 @@ from pathlib import Path from core.torrentzip import is_torrentzip from core.ziptools import zip_members +from romrecipes.collection import on_disk from romrecipes.pins import container_entries from romrecipes.pool import AtomPool from romrecipes.romsets import Recipe @@ -87,12 +88,14 @@ def _is_archive(path: Path) -> bool: return True -def _local_paths(archive: str, db: dict) -> list[Path]: +def _local_paths(archive: str, db: dict, root: Path) -> list[tuple[str, Path]]: + """(database path, file under *root*) of each readable archive named *archive*.""" 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)] + paths = [db["files"][sha1]["path"] for sha1 in matches if sha1 in db["files"]] + held = ((path, on_disk(root, path)) for path in paths) + return [(path, file) for path, file in held if file.is_file() and _is_archive(file)] def identify_report( @@ -102,12 +105,12 @@ def identify_report( 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) + for path, file in _local_paths(archive, db, pool.root): + label = identify_archive(file, per_profile, pool) record = { "archive": archive, - "path": str(path), - "torrentzip": is_torrentzip(path), + "path": str(Path(path)), + "torrentzip": is_torrentzip(file), } if label: record["recipe"] = label @@ -187,10 +190,14 @@ def write_reconstructions( 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)) + siblings = _local_paths(archive, db, pool.root) + name = f"{archive}.{entry['md5'][:8]}" + if siblings: + shown = Path(siblings[0][0]).parent / ".variants" / name + target = siblings[0][1].parent / ".variants" / name + else: + shown = target = bios_dir / ".variants" / name + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(blob) + written.append(str(shown)) return written diff --git a/scripts/romrecipes/pool.py b/scripts/romrecipes/pool.py index c80e744e7..b6a777858 100644 --- a/scripts/romrecipes/pool.py +++ b/scripts/romrecipes/pool.py @@ -11,6 +11,7 @@ from pathlib import Path from core.paths import REPO_ROOT from core.torrentzip import build_torrentzip from core.ziptools import is_archive_path, zip_members +from romrecipes.collection import collection_root, on_disk from romrecipes.romsets import Recipe @@ -26,6 +27,8 @@ class AtomPool: ) -> None: # crc32 -> (archive, member), or (file, None) for a loose ROM. self._index: dict[str, tuple[Path, str | None]] = {} + # Where every database path is read, by identification as by the pool. + self.root = collection_root(bios_dir) # (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 @@ -48,13 +51,13 @@ class AtomPool: 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() + tree = 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 is_archive_path(path): continue - loose = Path(path) - if root in loose.resolve().parents and loose.is_file(): + loose = on_disk(self.root, path) + if tree in loose.resolve().parents and loose.is_file(): self._index.setdefault(crc, (loose, None)) def __len__(self) -> int: diff --git a/scripts/romrecipes/runs.py b/scripts/romrecipes/runs.py index e4ea96704..04fbdb942 100644 --- a/scripts/romrecipes/runs.py +++ b/scripts/romrecipes/runs.py @@ -9,6 +9,7 @@ from pathlib import Path from core.torrentzip import zlib_ng_version from romrecipes.build import AtomIndex, BuildTally, build_records, build_targets from romrecipes.capture import ZlibNgError, capture_ledger +from romrecipes.collection import collection_root from romrecipes.ledger import load_ledger from romrecipes.text import print_build_result, print_build_totals, print_capture @@ -17,7 +18,8 @@ def run_capture(args: argparse.Namespace, db: dict) -> int: """Write recipes/archives.json for every archive the database lists.""" try: run = capture_ledger( - Path(args.archives), db, args.emulators_dir, args.dat_recipes, args.platforms_dir, + Path(args.archives), db, collection_root(Path(args.bios_dir)), + args.emulators_dir, args.dat_recipes, args.platforms_dir, ) except ZlibNgError as exc: print(f"ERROR: {exc}", file=sys.stderr) @@ -32,7 +34,8 @@ def run_build(args: argparse.Namespace, db: dict) -> int: print("ERROR: --build and --build-all need --output-dir", file=sys.stderr) return 2 ledger = load_ledger(Path(args.archives)) - records = build_targets(ledger, None if args.build_all else args.build) + root = collection_root(Path(args.bios_dir)) + records = build_targets(ledger, None if args.build_all else args.build, root) if not records and not args.build_all: print(f"ERROR: no archive recipe named {args.build}", file=sys.stderr) return 2 @@ -42,7 +45,6 @@ def run_build(args: argparse.Namespace, db: dict) -> int: 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 = AtomIndex.from_collection(ledger, db, root) tally = BuildTally() for result in build_records(records, atoms, Path(args.output_dir), root, args.discard): diff --git a/tests/sources.py b/tests/sources.py index c9ce9c28c..644909c98 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -99,7 +99,7 @@ COMMANDS = { "romrecipes/romsets.py", "romrecipes/pool.py", "romrecipes/pins.py", "romrecipes/identify.py", "romrecipes/ledger.py", "romrecipes/members.py", "romrecipes/capture.py", "romrecipes/build.py", "romrecipes/survey.py", - "romrecipes/text.py", "romrecipes/runs.py", + "romrecipes/text.py", "romrecipes/runs.py", "romrecipes/collection.py", ), "provenance_report.py": ("acquire/provenance.py",), "auto_fetch.py": ("acquire/fetch.py", "acquire/fetchtext.py", "acquire/placement.py"), diff --git a/tests/test_archive_build.py b/tests/test_archive_build.py index c2f04d021..628362f2e 100644 --- a/tests/test_archive_build.py +++ b/tests/test_archive_build.py @@ -142,26 +142,13 @@ class Fixture(unittest.TestCase): def capture(self, **kwargs) -> dict[str, dict]: records, failed = romrecipes_capture.capture( self.db, kwargs.get("previous", {}), kwargs.get("index", {}), - kwargs.get("pins", {}), workers=1, log=lambda _line: None, + kwargs.get("pins", {}), self.root, workers=1, log=lambda _line: None, ) self.assertEqual(failed, {}) return records class Capture(Fixture): - def setUp(self): - super().setUp() - self._cwd = Path.cwd() - import os - - os.chdir(self.root) - - def tearDown(self): - import os - - os.chdir(self._cwd) - super().tearDown() - def test_a_torrentzip_archive_is_exact_and_another_canonical(self): records = self.capture() exact, other = records["bios/set.zip"], records["bios/other.zip"] @@ -237,12 +224,7 @@ class Capture(Fixture): class Build(Fixture): def setUp(self): super().setUp() - import os - - self._cwd = Path.cwd() - os.chdir(self.root) self.ledger = self.capture() - os.chdir(self._cwd) self.atoms = romrecipes_build.AtomIndex.from_collection(self.ledger, self.db, self.root) self.out = self.root / "out" diff --git a/tests/test_romset_recipes.py b/tests/test_romset_recipes.py index 4f51801e9..b353e6afc 100644 --- a/tests/test_romset_recipes.py +++ b/tests/test_romset_recipes.py @@ -1004,5 +1004,39 @@ class LooseRomsAreAtoms(unittest.TestCase): self.assertIsNotNone(pool.build([("nmk004.bin", loopback.crc(ROM_A))])) +class DatabasePathsRootedAtTheCollection(unittest.TestCase): + """Database paths are relative (``bios/...``). The build read them under + the parent of --bios-dir, the pool and identification under the working + directory: a worktree copy lost every loose ROM and every archive.""" + + def test_the_pool_and_identification_read_under_the_bios_parent(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) / "copy" + bios = root / "bios" + (bios / "M").mkdir(parents=True) + (bios / "M" / "nmk004.bin").write_bytes(ROM_A) + recipe = [("nmk004.bin", loopback.crc(ROM_A))] + blob = build_torrentzip([("nmk004.bin", ROM_A)]) + (bios / "M" / "set.zip").write_bytes(blob) + sha1 = hashlib.sha1(blob).hexdigest() + db = { + "files": { + "x": {"path": "bios/M/nmk004.bin", "crc32": loopback.crc(ROM_A)}, + sha1: {"path": "bios/M/set.zip"}, + }, + "indexes": {"by_name": {"set.zip": [sha1]}}, + } + elsewhere = Path(directory) / "elsewhere" + elsewhere.mkdir() + with contextlib.chdir(elsewhere): + pool = AtomPool(bios, None, db) + self.assertIn(loopback.crc(ROM_A), pool) + report = identify_report({"set.zip": {"v1": recipe}}, pool, db) + self.assertEqual( + [(r["path"], r["recipe"]) for r in report["identified"]], + [(str(Path("bios/M/set.zip")), "v1")], + ) + + if __name__ == "__main__": unittest.main()