refactor: read the clone map in one place

This commit is contained in:
Abdessamad Derraz committed 2026-11-22 02:26:45 +01:00
1 parent 758bc76b6f
commit 12c8d66163
5 files changed
+66 -45

No files matched your search

+3 -30
View File
@@ -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)
+8 -2
View File
@@ -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] = {}
+40 -12
View File
@@ -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
+1 -1
View File
@@ -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",),
+14
View File
@@ -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_<name>.txt beside the slot it