From 12c8d6616348cabbee11f34d8f0f1759a9b8b9e0 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:44:32 +0100 Subject: [PATCH] refactor: read the clone map in one place --- scripts/collection/clonemap.py | 33 ++------------------- scripts/collection/dedup.py | 10 +++++-- scripts/model/database.py | 52 +++++++++++++++++++++++++-------- tests/sources.py | 2 +- tests/test_audit_regressions.py | 14 +++++++++ 5 files changed, 66 insertions(+), 45 deletions(-) diff --git a/scripts/collection/clonemap.py b/scripts/collection/clonemap.py index c8ba6a5a7..77408d8c7 100644 --- a/scripts/collection/clonemap.py +++ b/scripts/collection/clonemap.py @@ -1,41 +1,14 @@ -"""The MAME clone map _mame_clones.json: where it lives, reading, merging and writing it.""" +"""Merging and writing the MAME clone map _mame_clones.json.""" from __future__ import annotations import json -import os from core.artifacts import write_text_atomic -def clone_map_path(bios_dir: str) -> str: - """The clone map beside the scanned tree. - - That is where get_mame_clone_map() reads it for the real layout. A path - relative to the working directory let a scan of a fixture tree rewrite - the repository's own map. - """ - return os.path.join(os.path.dirname(os.path.abspath(bios_dir)), "_mame_clones.json") - - -def read_clone_map(clone_path: str) -> object: - """The clone map an earlier run wrote, {} when there is none.""" - # Read before anything is removed: the map is cumulative, and a run that - # stopped on an unreadable one after deleting clones would lose them. - try: - with open(clone_path) as f: - return json.load(f) - except FileNotFoundError: - return {} - except json.JSONDecodeError as e: - raise SystemExit( - f"{clone_path} is not valid JSON ({e}). Restore it from git " - "before deduplicating again" - ) from e - - def record_clone_map( - mame_clones: dict[str, dict], previous: object, clone_path: str, dry_run: bool + mame_clones: dict[str, dict], previous: dict, clone_path: str, dry_run: bool ) -> None: """Write the clone map, merged with what earlier runs recorded.""" # A group is only visible while both copies are on disk, and this run @@ -43,7 +16,7 @@ def record_clone_map( # therefore erases every mapping an earlier run recorded, and the # canonical zip stops answering to the names it stands in for. The # older entries stay valid: their canonical file is still here. - if not dry_run and isinstance(previous, dict): + if not dry_run and previous: merged = dict(previous) merged.update(mame_clones) mame_clones = collapse_clone_chains(merged) diff --git a/scripts/collection/dedup.py b/scripts/collection/dedup.py index f3753bd59..c6ffc72da 100644 --- a/scripts/collection/dedup.py +++ b/scripts/collection/dedup.py @@ -5,10 +5,11 @@ from __future__ import annotations import os from pathlib import Path -from collection.clonemap import clone_map_path, read_clone_map, record_clone_map +from collection.clonemap import record_clone_map from collection.duplicates import plan_group_removals, scan_duplicates from collection.scan import primary_rank from core.sizes import size_text +from model.database import CloneMapUnreadable, clone_map_path, read_clone_map def _remove_copies(canonical: str, true_dupes_to_remove: list[str], dry_run: bool) -> list[str]: @@ -110,7 +111,12 @@ def deduplicate(bios_dir: str, dry_run: bool = False) -> dict: Returns dict of {sha1: {"canonical": path, "removed": [paths], "aliases": [names]}} """ clone_path = clone_map_path(bios_dir) - previous = read_clone_map(clone_path) + # Read before anything is removed: the map is cumulative, and a run that + # stopped on an unreadable one after deleting clones would lose them. + try: + previous = read_clone_map(clone_path) + except CloneMapUnreadable as e: + raise SystemExit(f"{e} before deduplicating again") from e sha1_groups = scan_duplicates(bios_dir) results: dict[str, dict] = {} diff --git a/scripts/model/database.py b/scripts/model/database.py index 57d8ecb6e..91b3e64e3 100644 --- a/scripts/model/database.py +++ b/scripts/model/database.py @@ -6,7 +6,7 @@ import json import os from pathlib import Path -from core.cli import InputMissing +from core.cli import InputMissing, SourceUnreadable from core.hashing import cut_md5_owner from core.memo import DerivedView from core.paths import DB_FILE, REPO_ROOT @@ -129,6 +129,38 @@ def record_for_hash(db: dict, kind: str, value: object) -> str | None: _mame_clone_map_cache: dict[str, dict[str, str]] = {} +class CloneMapUnreadable(SourceUnreadable): + """_mame_clones.json exists but is not a JSON object.""" + + +def clone_map_path(bios_dir: str) -> str: + """The clone map beside the scanned tree. + + dedup writes it there and get_mame_clone_map() reads it there. A path + relative to the working directory let a scan of a fixture tree rewrite + the repository's own map. + """ + return os.path.join(os.path.dirname(os.path.abspath(bios_dir)), "_mame_clones.json") + + +def read_clone_map(clone_path: str) -> dict: + """The {canonical: {clones, ...}} map an earlier run wrote, {} when there is none.""" + try: + with open(clone_path) as f: + data = json.load(f) + except FileNotFoundError: + return {} + except json.JSONDecodeError as e: + raise CloneMapUnreadable( + f"{clone_path} is not valid JSON ({e}). Restore it from git" + ) from e + if not isinstance(data, dict): + raise CloneMapUnreadable( + f"{clone_path} is not a JSON object. Restore it from git" + ) + return data + + def get_mame_clone_map(bios_dir: str | None = None) -> dict[str, str]: """The MAME clone map (clone_name -> canonical_name) of a scanned tree. @@ -138,19 +170,15 @@ def get_mame_clone_map(bios_dir: str | None = None) -> dict[str, str]: fell out of its packs. Without a tree the repository's own is read. """ if bios_dir is None: - bios_dir = os.path.join( - REPO_ROOT, "bios" - ) - clone_path = os.path.join(os.path.dirname(os.path.abspath(bios_dir)), "_mame_clones.json") + bios_dir = os.path.join(REPO_ROOT, "bios") + clone_path = clone_map_path(bios_dir) cached = _mame_clone_map_cache.get(clone_path) if cached is not None: return cached - clone_map: dict[str, str] = {} - if os.path.exists(clone_path): - with open(clone_path) as f: - data = json.load(f) - for canonical, info in data.items(): - for clone in info.get("clones", []): - clone_map[clone] = canonical + clone_map = { + clone: canonical + for canonical, info in read_clone_map(clone_path).items() + for clone in info.get("clones", []) + } _mame_clone_map_cache[clone_path] = clone_map return clone_map diff --git a/tests/sources.py b/tests/sources.py index 015d567af..bc5f8a138 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -48,7 +48,7 @@ COMMANDS = { "region_audit.py": ("resolve/regionaudit.py",), "dedup.py": ( "model/nodedup.py", "collection/dedup.py", "collection/duplicates.py", - "collection/clonemap.py", + "collection/clonemap.py", "model/database.py", ), "release_record.py": ("model/releaserecord.py", "release/record.py"), "release_notes.py": ("release/notes.py",), diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index 4a19090bd..33c12f520 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -3831,6 +3831,20 @@ class GeneratedModelsAreWrittenWhole(unittest.TestCase): # Stopped before removing anything. self.assertTrue((bios / "Arcade" / "MAME" / "setclone.zip").exists()) + def test_the_pack_side_reads_the_same_bad_map_the_same_way(self): + from model import database + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "bios").mkdir() + (root / "_mame_clones.json").write_text("<<<<<<< HEAD") + with self.assertRaises(database.CloneMapUnreadable) as caught: + database.get_mame_clone_map(str(root / "bios")) + self.assertIn("Restore it from git", str(caught.exception)) + (root / "_mame_clones.json").write_text("[]") + with self.assertRaises(database.CloneMapUnreadable): + database.get_mame_clone_map(str(root / "bios")) + class APackNoteBesideItsSlotIsANote(unittest.TestCase): """The builder writes INSTRUCTIONS_.txt beside the slot it