fix: dedup keeps the copy the index names

dedup ranked copies by path_priority (variant, MAME, Arcade, length) while the scan picked the primary by _takes_primary (variant, emulator tree, walk order). Given sms.rom under bios/Other/zesarux/ and bios/Sega/Master System/, dedup removed the indexed copy and kept the foreign-tree one the resolver sets aside. Both now read collection.scan.primary_rank. The rank reproduces every primary of the current database.json, so the index does not move; dedup's tie-break follows the walk order instead of MAME and path length.
This commit is contained in:
Abdessamad Derraz committed 2026-11-21 19:50:46 +01:00
1 parent eec4ff9972
commit 05b6b9edcf
4 files changed
+75 -47

No files matched your search

+15 -6
View File
@@ -3,9 +3,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.duplicates import path_priority, plan_group_removals, scan_duplicates
from collection.duplicates import plan_group_removals, scan_duplicates
from collection.scan import primary_rank
from core.sizes import size_text
@@ -34,7 +36,11 @@ def _remove_copies(canonical: str, true_dupes_to_remove: list[str], dry_run: boo
def _settle_group(
paths: list[str], true_dupes_to_remove: list[str], clone_names: list[str], dry_run: bool
paths: list[str],
true_dupes_to_remove: list[str],
clone_names: list[str],
dry_run: bool,
bios_dir: str,
) -> dict:
"""Keep the best copy of one content and remove the others.
@@ -43,15 +49,18 @@ def _settle_group(
is one an emulator looks for: printing either as a MAME clone named a
file that stays, or a clone map entry that does not exist.
"""
def rank(path: str) -> tuple:
return primary_rank(Path(path), Path(bios_dir))
# Find the best canonical across all paths
all_paths = [p for p in paths if p not in true_dupes_to_remove]
if not all_paths:
# All copies were marked for removal: keep the best one
all_paths_sorted = sorted(paths, key=path_priority)
all_paths_sorted = sorted(paths, key=rank)
all_paths = [all_paths_sorted[0]]
true_dupes_to_remove = [p for p in paths if p != all_paths[0]]
canonical = sorted(all_paths, key=path_priority)[0]
canonical = sorted(all_paths, key=rank)[0]
canonical_name = os.path.basename(canonical)
all_names = set(os.path.basename(p) for p in paths)
@@ -114,14 +123,14 @@ def deduplicate(bios_dir: str, dry_run: bool = False) -> dict:
continue
group_clones: dict[str, dict] = {}
true_dupes_to_remove = plan_group_removals(sha1, paths, group_clones)
true_dupes_to_remove = plan_group_removals(sha1, paths, group_clones, bios_dir)
mame_clones.update(group_clones)
if not true_dupes_to_remove:
continue
clone_names = [name for entry in group_clones.values() for name in entry["clones"]]
settled = _settle_group(paths, true_dupes_to_remove, clone_names, dry_run)
settled = _settle_group(paths, true_dupes_to_remove, clone_names, dry_run, bios_dir)
total_removed += len(settled["removed"])
total_saved += settled.pop("saved")
results[sha1] = settled
+7 -15
View File
@@ -6,22 +6,11 @@ import os
from collections import defaultdict
from pathlib import Path
from collection.scan import primary_rank
from core.hashing import compute_hashes
from model.nodedup import in_nodedup_dir
def path_priority(path: str) -> tuple:
"""Lower score = better candidate to keep as canonical.
Prefers: shorter path, non-variant, non-MAME (system-specific over generic).
"""
parts = Path(path).parts
is_variant = ".variants" in parts
is_mame = "MAME" in parts
is_arcade = "Arcade" in parts
return (is_variant, is_mame, is_arcade, len(parts), path)
def _is_mame_dir(path: str) -> bool:
"""Check if a path is in a MAME-specific directory."""
parts = Path(path).parts
@@ -54,7 +43,7 @@ def scan_duplicates(bios_dir: str) -> dict[str, list[str]]:
def plan_group_removals(
sha1: str, paths: list[str], mame_clones: dict
sha1: str, paths: list[str], mame_clones: dict, bios_dir: str
) -> list[str]:
"""Decide which copies of one content hash may go.
@@ -66,6 +55,9 @@ def plan_group_removals(
Records clone groups in *mame_clones* and returns the paths to remove.
"""
def rank(path: str) -> tuple:
return primary_rank(Path(path), Path(bios_dir))
# Separate by filename: same name = true duplicate, different name = clone
by_name: dict[str, list[str]] = defaultdict(list)
for p in paths:
@@ -75,7 +67,7 @@ def plan_group_removals(
true_dupes_to_remove: list[str] = []
for name_paths in by_name.values():
if len(name_paths) > 1:
name_paths.sort(key=path_priority)
name_paths.sort(key=rank)
true_dupes_to_remove.extend(name_paths[1:])
# A variant exists to hold a content its primary does not. Once another
@@ -87,7 +79,7 @@ def plan_group_removals(
variants = [p for p in remaining if ".variants" in Path(p).parts]
if variants:
holders = [p for p in remaining if p not in variants] or [
min(variants, key=path_priority)
min(variants, key=rank)
]
true_dupes_to_remove.extend(p for p in variants if p not in holders)
+14 -18
View File
@@ -70,25 +70,19 @@ def _settled_hashes(
)
def _emulator_tree(path: str) -> bool:
"""Whether a path lies in one emulator's own tree, bios/Other/<emulator>/."""
parts = path.replace("\\", "/").split("/")
return len(parts) > 3 and parts[1] == "Other"
def _takes_primary(current: str, candidate: str) -> bool:
"""Whether another copy of the same bytes becomes the content's path.
def primary_rank(path: Path, bios_dir: Path) -> tuple:
"""Rank of one copy of a content, the lowest being its path in the index.
A .variants/ copy yields to any other one. A copy in an emulator's own
tree yields to one filed under its machine: ZEsarUX's sms.rom sorted
before bios/Sega/Master System/, the resolver set it aside as another
emulator's file, and Genesis Plus GX got a variant instead of v1.3.
tree, bios/Other/<emulator>/, yields to one filed under its machine:
ZEsarUX's sms.rom sorted before bios/Sega/Master System/, the resolver
set it aside as another emulator's file, and Genesis Plus GX got a
variant instead of v1.3. Equal copies follow the walk's order. The scan
and the dedup both read this rank, so the copy the dedup keeps is the
one the index names.
"""
if "/.variants/" in candidate.replace("\\", "/"):
return False
if "/.variants/" in current:
return True
return _emulator_tree(current) and not _emulator_tree(candidate)
parts = path.relative_to(bios_dir).parts
return (".variants" in parts, len(parts) > 2 and parts[0] == "Other", parts)
def _add_scanned(
@@ -98,6 +92,7 @@ def _add_scanned(
rel_path: str,
size: int,
hashes: dict,
root: Path,
) -> None:
"""Record a scanned file as its content's primary, or as an alias of it."""
sha1 = hashes["sha1"]
@@ -109,7 +104,7 @@ def _add_scanned(
}
if sha1 not in files:
files[sha1] = entry
elif _takes_primary(files[sha1]["path"], rel_path):
elif primary_rank(Path(rel_path), root) < primary_rank(Path(files[sha1]["path"]), root):
aliases.setdefault(sha1, []).append(
{"name": files[sha1]["name"], "path": files[sha1]["path"]}
)
@@ -138,6 +133,7 @@ def scan_bios_dir(bios_dir: Path, cache: dict, force: bool) -> tuple[dict, dict,
files: dict[str, dict] = {}
aliases: dict[str, list[dict]] = {}
new_cache = {}
root = Path(bios_dir.name)
for filepath in sorted(bios_dir.rglob("*")):
if not filepath.is_file():
@@ -154,7 +150,7 @@ def scan_bios_dir(bios_dir: Path, cache: dict, force: bool) -> tuple[dict, dict,
hashes = None if force else _cached_hashes(cache.get(cache_key), mtime, size)
if hashes is None:
hashes = _settled_hashes(filepath, cache.get(cache_key), mtime, size)
_add_scanned(files, aliases, filepath, rel_path, size, hashes)
_add_scanned(files, aliases, filepath, rel_path, size, hashes, root)
new_cache[cache_key] = {**hashes, "mtime": mtime, "size": size}
return files, aliases, new_cache
+39 -8
View File
@@ -19,6 +19,7 @@ import unittest
from pathlib import Path
from collection import clonemap, dedup, duplicates
from collection.scan import primary_rank, scan_bios_dir
from model import nodedup
@@ -305,16 +306,22 @@ class CloneMapSurvivesASecondRun(_Bios):
self.assertEqual(self._map(), {})
class PathPriority(unittest.TestCase):
def test_shorter_paths_sort_first(self):
short = duplicates.path_priority("bios/Sony/PS/a.bin")
deep = duplicates.path_priority("bios/Sony/PS/x/y/z/a.bin")
self.assertLess(short, deep)
class PrimaryRank(unittest.TestCase):
BIOS = Path("bios")
def rank(self, relative: str) -> tuple:
return primary_rank(self.BIOS / relative, self.BIOS)
def test_equal_copies_follow_the_walk_order(self):
self.assertLess(self.rank("Sony/PS/a.bin"), self.rank("Sony/PS/x/y/z/a.bin"))
def test_a_variant_sorts_after_a_primary(self):
primary = duplicates.path_priority("bios/Sony/PS/a.bin")
variant = duplicates.path_priority("bios/Sony/PS/.variants/a.bin")
self.assertLess(primary, variant)
self.assertLess(self.rank("Sony/PS/zz/a.bin"), self.rank("Sony/PS/.variants/a.bin"))
def test_an_emulator_tree_sorts_after_a_machine_folder(self):
self.assertLess(
self.rank("Sega/Master System/sms.rom"), self.rank("Other/zesarux/sms.rom")
)
def test_protected_directories_are_recognised(self):
self.assertTrue(nodedup.in_nodedup_dir("bios/RPG Maker/x/font.png"))
@@ -322,6 +329,30 @@ class PathPriority(unittest.TestCase):
self.assertFalse(nodedup.in_nodedup_dir("bios/Sony/PlayStation/scph.bin"))
class DedupKeepsTheIndexedCopy(_Bios):
"""The dedup removed bios/Sega/Master System/sms.rom, the copy the index
names, and kept ZEsarUX's, a tree the resolver sets aside as another
emulator's: two rules chose the primary of one content."""
def assert_kept_is_primary(self, *relatives: str) -> None:
for relative in relatives:
self.write(relative)
files, _aliases, _cache = scan_bios_dir(self.bios, {}, True)
(indexed,) = (entry["path"] for entry in files.values())
self.run_dedup()
(kept,) = self.existing()
self.assertEqual(f"bios/{kept}", indexed)
def test_a_machine_folder_wins_over_an_emulator_tree(self):
self.assert_kept_is_primary("Other/zesarux/sms.rom", "Sega/Master System/sms.rom")
def test_a_primary_wins_over_a_variant(self):
self.assert_kept_is_primary("Sony/PS/zz/scph.bin", "Sony/PS/.variants/scph.bin")
def test_equal_copies_keep_the_first_walked(self):
self.assert_kept_is_primary("Arcade/MAME/naomi.zip", "Sega/Dreamcast/naomi.zip")
class TheNoDedupListIsPinned(unittest.TestCase):
"""Every directory the dedup must leave alone, with the reason written
beside it in model/nodedup.py. Only RPG Maker and ScummVM were tested, so a merge