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.
This commit is contained in:
Abdessamad Derraz committed 2026-11-23 21:02:47 +01:00
1 parent 9491c02887
commit d676991502
9 files changed
+107 -56

No files matched your search

+9 -9
View File
@@ -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(
+16 -8
View File
@@ -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))
+15
View File
@@ -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
+20 -13
View File
@@ -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
+6 -3
View File
@@ -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:
+5 -3
View File
@@ -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):