diff --git a/scripts/collection/clonemap.py b/scripts/collection/clonemap.py index 77408d8c7..0d2850ba9 100644 --- a/scripts/collection/clonemap.py +++ b/scripts/collection/clonemap.py @@ -9,26 +9,21 @@ from core.artifacts import write_text_atomic def record_clone_map( mame_clones: dict[str, dict], previous: dict, clone_path: str, dry_run: bool -) -> None: - """Write the clone map, merged with what earlier runs recorded.""" +) -> dict[str, dict]: + """Write the clone map, merged with what earlier runs recorded, and return it.""" # A group is only visible while both copies are on disk, and this run # has just deleted the clone. Writing only what was seen this time # 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 previous: + if dry_run: + return mame_clones + if previous: merged = dict(previous) merged.update(mame_clones) mame_clones = collapse_clone_chains(merged) - if dry_run: - print(f"\nWould write MAME clone map: {clone_path}") - else: - write_text_atomic(clone_path, json.dumps(mame_clones, indent=2, sort_keys=True)) - print(f"\nWrote MAME clone map: {clone_path}") - print( - f" {len(mame_clones)} canonical ZIPs with " - f"{sum(len(v['clones']) for v in mame_clones.values())} clones" - ) + write_text_atomic(clone_path, json.dumps(mame_clones, indent=2, sort_keys=True)) + return mame_clones def collapse_clone_chains(clone_map: dict[str, dict]) -> dict[str, dict]: diff --git a/scripts/collection/dedup.py b/scripts/collection/dedup.py index c6ffc72da..592a1f00a 100644 --- a/scripts/collection/dedup.py +++ b/scripts/collection/dedup.py @@ -3,37 +3,87 @@ from __future__ import annotations import os +from dataclasses import dataclass, field from pathlib import Path 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 +from model.database import clone_map_path, read_clone_map -def _remove_copies(canonical: str, true_dupes_to_remove: list[str], dry_run: bool) -> list[str]: - """Remove (or name, in a dry run) each copy beside the canonical file.""" +@dataclass(frozen=True) +class RemovalFailure: + """A copy the run meant to remove and could not.""" + + path: str + error: str + + +@dataclass +class GroupOutcome: + """What the run did with one content held by several files. + + `planned` is the plan, `removed` what left the disk (or would, in a dry + run) and `failed` what stayed against the plan. + """ + + canonical: str + planned: list[str] + removed: list[str] + failed: list[RemovalFailure] + aliases: list[str] + clone_names: list[str] + kept_names: list[str] + saved: int + + +@dataclass +class DedupResult: + """One deduplication run: each settled group and what the run wrote.""" + + dry_run: bool + clone_map_path: str + groups: dict[str, GroupOutcome] = field(default_factory=dict) + empty_dirs_removed: int = 0 + clone_map: dict[str, dict] = field(default_factory=dict) + + @property + def total_removed(self) -> int: + return sum(len(group.removed) for group in self.groups.values()) + + @property + def total_saved(self) -> int: + return sum(group.saved for group in self.groups.values()) + + @property + def failed(self) -> list[RemovalFailure]: + return [failure for group in self.groups.values() for failure in group.failed] + + +def _remove_copies( + canonical: str, true_dupes_to_remove: list[str], dry_run: bool +) -> tuple[list[str], list[RemovalFailure]]: + """Remove (or keep, in a dry run) each copy beside the canonical file.""" removed: list[str] = [] + failed: list[RemovalFailure] = [] for dup in true_dupes_to_remove: if dup == canonical: continue if not os.path.exists(dup): continue - if dry_run: - print(f" WOULD REMOVE: {dup}") - else: + if not dry_run: try: os.remove(dup) except OSError as e: - print(f" WARNING: cannot remove {dup}: {e}") + failed.append(RemovalFailure(dup, str(e))) continue # Clean up empty .variants/ directories parent = os.path.dirname(dup) if os.path.basename(parent) == ".variants" and not os.listdir(parent): os.rmdir(parent) removed.append(dup) - return removed + return removed, failed def _settle_group( @@ -42,12 +92,12 @@ def _settle_group( clone_names: list[str], dry_run: bool, bios_dir: str, -) -> dict: +) -> GroupOutcome: """Keep the best copy of one content and remove the others. Only the names the clone map records are MAME clones. A removed variant is one of the copies, and another name kept beside the canonical file - is one an emulator looks for: printing either as a MAME clone named a + is one an emulator looks for: reporting either as a MAME clone named a file that stays, or a clone map entry that does not exist. """ def rank(path: str) -> tuple: @@ -68,28 +118,21 @@ def _settle_group( alias_names = sorted(all_names - {canonical_name}) size = os.path.getsize(canonical) - removed = _remove_copies(canonical, true_dupes_to_remove, dry_run) - - if alias_names or true_dupes_to_remove: - action = "Would remove" if dry_run else "Removed" - dn = os.path.basename(canonical) - print(f" {dn} (keep: {canonical})") - if true_dupes_to_remove: - print(f" {action} {len(true_dupes_to_remove)} copies") - if clone_names: - print(f" MAME clones: {clone_names}") - kept_names = sorted( - {os.path.basename(p) for p in paths if p not in true_dupes_to_remove} - - {canonical_name} - ) - if kept_names: - print(f" Kept under other names: {kept_names}") - return { - "canonical": canonical, - "removed": removed, - "aliases": alias_names, - "saved": size * len(removed), - } + removed, failed = _remove_copies(canonical, true_dupes_to_remove, dry_run) + kept_names = sorted( + {os.path.basename(p) for p in paths if p not in true_dupes_to_remove} + - {canonical_name} + ) + return GroupOutcome( + canonical=canonical, + planned=true_dupes_to_remove, + removed=removed, + failed=failed, + aliases=alias_names, + clone_names=clone_names, + kept_names=kept_names, + saved=size * len(removed), + ) def _remove_empty_dirs(bios_dir: str) -> int: @@ -102,29 +145,24 @@ def _remove_empty_dirs(bios_dir: str) -> int: return empty_cleaned -def deduplicate(bios_dir: str, dry_run: bool = False) -> dict: +def deduplicate(bios_dir: str, dry_run: bool = False) -> DedupResult: """Remove true duplicates, map MAME device clones. True duplicates (same name, different dirs): removes copies. MAME clones (different names, same content, same dir): creates mapping. - Returns dict of {sha1: {"canonical": path, "removed": [paths], "aliases": [names]}} + Raises CloneMapUnreadable before removing anything when the existing + clone map cannot be read. """ clone_path = clone_map_path(bios_dir) # 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 + previous = read_clone_map(clone_path) - sha1_groups = scan_duplicates(bios_dir) - results: dict[str, dict] = {} - total_removed = 0 - total_saved = 0 + result = DedupResult(dry_run=dry_run, clone_map_path=clone_path) mame_clones: dict[str, dict] = {} # canonical_name -> {sha1, clones: [names]} - for sha1, paths in sorted(sha1_groups.items()): + for sha1, paths in sorted(scan_duplicates(bios_dir).items()): if len(paths) <= 1: continue @@ -136,23 +174,12 @@ def deduplicate(bios_dir: str, dry_run: bool = False) -> dict: 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, bios_dir) - total_removed += len(settled["removed"]) - total_saved += settled.pop("saved") - results[sha1] = settled - - # Clean up empty directories - empty_cleaned = 0 if dry_run else _remove_empty_dirs(bios_dir) - - prefix = "Would remove" if dry_run else "Removed" - print(f"\n{prefix}: {total_removed} files") - print( - f"Space {'to save' if dry_run else 'saved'}: {size_text(total_saved)}" - ) - if not dry_run and empty_cleaned: - print(f"Cleaned {empty_cleaned} empty directories") + result.groups[sha1] = _settle_group( + paths, true_dupes_to_remove, clone_names, dry_run, bios_dir + ) + if not dry_run: + result.empty_dirs_removed = _remove_empty_dirs(bios_dir) if mame_clones: - record_clone_map(mame_clones, previous, clone_path, dry_run) - - return results + result.clone_map = record_clone_map(mame_clones, previous, clone_path, dry_run) + return result diff --git a/scripts/collection/deduptext.py b/scripts/collection/deduptext.py new file mode 100644 index 000000000..764b612fb --- /dev/null +++ b/scripts/collection/deduptext.py @@ -0,0 +1,44 @@ +"""The terminal report of a deduplication run.""" + +from __future__ import annotations + +import os +from collections.abc import Iterator + +from collection.dedup import DedupResult, GroupOutcome +from core.sizes import size_text + + +def _group_lines(group: GroupOutcome, dry_run: bool) -> Iterator[str]: + """One settled content: what went, what stayed, and why.""" + if dry_run: + for path in group.removed: + yield f" WOULD REMOVE: {path}" + for failure in group.failed: + yield f" WARNING: cannot remove {failure.path}: {failure.error}" + if not (group.aliases or group.planned): + return + action = "Would remove" if dry_run else "Removed" + yield f" {os.path.basename(group.canonical)} (keep: {group.canonical})" + if group.planned: + yield f" {action} {len(group.removed)} copies" + if group.clone_names: + yield f" MAME clones: {group.clone_names}" + if group.kept_names: + yield f" Kept under other names: {group.kept_names}" + + +def report_lines(result: DedupResult) -> Iterator[str]: + """Every line of the run's report, in order.""" + for group in result.groups.values(): + yield from _group_lines(group, result.dry_run) + prefix = "Would remove" if result.dry_run else "Removed" + yield f"\n{prefix}: {result.total_removed} files" + yield f"Space {'to save' if result.dry_run else 'saved'}: {size_text(result.total_saved)}" + if result.empty_dirs_removed: + yield f"Cleaned {result.empty_dirs_removed} empty directories" + if result.clone_map: + verb = "Would write" if result.dry_run else "Wrote" + yield f"\n{verb} MAME clone map: {result.clone_map_path}" + clones = sum(len(entry["clones"]) for entry in result.clone_map.values()) + yield f" {len(result.clone_map)} canonical ZIPs with {clones} clones" diff --git a/scripts/dedup.py b/scripts/dedup.py index 3661f6468..53c2ff400 100644 --- a/scripts/dedup.py +++ b/scripts/dedup.py @@ -26,26 +26,41 @@ import sys sys.path.insert(0, os.path.dirname(__file__)) from collection.dedup import deduplicate +from collection.deduptext import report_lines from core.cli import add_repo_inputs, require_directory +from model.database import CloneMapUnreadable -def main() -> None: +def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(allow_abbrev=False, description="Deduplicate bios/ directory") parser.add_argument( "--dry-run", action="store_true", help="Preview without deleting" ) add_repo_inputs(parser, "bios") - args = parser.parse_args() + return parser + + +def main() -> int: + args = build_parser().parse_args() require_directory(args.bios_dir) print(f"Scanning {args.bios_dir}/ for duplicates...") if args.dry_run: print("(DRY RUN)\n") - deduplicate(args.bios_dir, dry_run=args.dry_run) + try: + result = deduplicate(args.bios_dir, dry_run=args.dry_run) + except CloneMapUnreadable as e: + raise SystemExit(f"{e} before deduplicating again") from e + for line in report_lines(result): + print(line) - if not args.dry_run: + if result.total_removed and not args.dry_run: print("\nRun 'python scripts/generate_db.py --force' to rebuild database.") + if result.failed: + print(f"ERROR: {len(result.failed)} copies could not be removed", file=sys.stderr) + return 1 + return 0 if __name__ == "__main__": diff --git a/tests/sources.py b/tests/sources.py index 2affc0678..679a54841 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -49,7 +49,7 @@ COMMANDS = { "retired_files.py": ("model/retired.py", "collection/retiredhistory.py"), "region_audit.py": ("resolve/regionaudit.py",), "dedup.py": ( - "model/nodedup.py", "collection/dedup.py", + "model/nodedup.py", "collection/dedup.py", "collection/deduptext.py", "collection/duplicates.py", "core/collectionfiles.py", "collection/clonemap.py", "model/database.py", ), diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index ce318e5e2..d800cdb5f 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -3831,7 +3831,9 @@ class GeneratedModelsAreWrittenWhole(unittest.TestCase): data = (bios / "Arcade" / "MAME" / "set.zip").read_bytes() (bios / "Arcade" / "MAME" / "setclone.zip").write_bytes(data) (root / "_mame_clones.json").write_text("<<<<<<< HEAD") - with self.assertRaises(SystemExit): + from model.database import CloneMapUnreadable + + with self.assertRaises(CloneMapUnreadable): dedup.deduplicate(str(bios), dry_run=False) # Stopped before removing anything. self.assertTrue((bios / "Arcade" / "MAME" / "setclone.zip").exists()) diff --git a/tests/test_dedup.py b/tests/test_dedup.py index 039da65df..8bb89f3b9 100644 --- a/tests/test_dedup.py +++ b/tests/test_dedup.py @@ -11,14 +11,12 @@ from __future__ import annotations import tests -import contextlib -import io import os import tempfile import unittest from pathlib import Path -from collection import clonemap, dedup, duplicates +from collection import clonemap, dedup, deduptext, duplicates from collection.scan import primary_rank, scan_bios_dir from model import nodedup @@ -38,9 +36,8 @@ class _Bios(unittest.TestCase): path.write_bytes(data) return path - def run_dedup(self, dry_run: bool = False) -> dict: - with contextlib.redirect_stdout(io.StringIO()): - return dedup.deduplicate(str(self.bios), dry_run=dry_run) + def run_dedup(self, dry_run: bool = False) -> dedup.DedupResult: + return dedup.deduplicate(str(self.bios), dry_run=dry_run) def existing(self) -> set[str]: return { @@ -83,7 +80,7 @@ class TrueDuplicates(_Bios): self.write("Sega/Dreamcast/naomi.zip") results = self.run_dedup() self.assertEqual(len(self.existing()), 1) - removed = [r for entry in results.values() for r in entry["removed"]] + removed = [r for entry in results.groups.values() for r in entry.removed] self.assertEqual(len(removed), 1) def test_the_shorter_path_is_kept(self): @@ -127,10 +124,8 @@ class TrueDuplicates(_Bios): self.assertEqual(len(self.existing()), 2) def report(self) -> str: - out = io.StringIO() - with contextlib.redirect_stdout(out): - dedup.deduplicate(str(self.bios), dry_run=True) - return out.getvalue() + result = dedup.deduplicate(str(self.bios), dry_run=True) + return "\n".join(deduptext.report_lines(result)) def test_a_removed_variant_is_not_reported_as_a_mame_clone(self): # The run printed "MAME clones: ['x.bin.1234']" for a variant copy, @@ -158,7 +153,7 @@ class TrueDuplicates(_Bios): def test_a_lone_file_is_left_alone(self): self.write("Sony/PS/only.bin") - self.assertEqual(self.run_dedup(), {}) + self.assertEqual(self.run_dedup().groups, {}) self.assertEqual(len(self.existing()), 1) @@ -198,7 +193,7 @@ class DryRun(_Bios): results = self.run_dedup(dry_run=True) self.assertEqual(self.existing(), before, "dry run removed a file") self.assertTrue( - any(entry["removed"] for entry in results.values()), + any(entry.removed for entry in results.groups.values()), "dry run should still report what it would remove", ) @@ -206,12 +201,12 @@ class DryRun(_Bios): self.write("Arcade/MAME/naomi.zip") self.write("Sega/Dreamcast/naomi.zip") planned = { - r for entry in self.run_dedup(dry_run=True).values() - for r in entry["removed"] + r for entry in self.run_dedup(dry_run=True).groups.values() + for r in entry.removed } done = { - r for entry in self.run_dedup(dry_run=False).values() - for r in entry["removed"] + r for entry in self.run_dedup(dry_run=False).groups.values() + for r in entry.removed } self.assertEqual(planned, done) @@ -353,6 +348,80 @@ class DedupKeepsTheIndexedCopy(_Bios): self.assert_kept_is_primary("Arcade/MAME/naomi.zip", "Sega/Dreamcast/naomi.zip") +class OnlyCollectionFilesAreCandidates(_Bios): + """The dedup walked bios/.cache/ and hidden files, which the database + scan leaves out, and the shared rank could keep that copy: a real run + deleted the only copy the index, manifests and packs knew.""" + + def test_a_copy_under_a_skipped_directory_is_never_kept(self): + self.write("Sony/PlayStation/scph1001.bin") + self.write(".cache/scph1001.bin") + result = self.run_dedup(dry_run=True) + self.assertEqual(result.groups, {}) + + def test_the_dedup_walks_the_files_the_scan_indexes(self): + for relative in ("Sony/PS/a.bin", ".cache/a.bin", "Sony/.hidden.bin", + "Sony/PS/.variants/a.bin.1234"): + self.write(relative) + files, aliases, _cache = scan_bios_dir(self.bios, {}, True) + indexed = {entry["path"] for entry in files.values()} | { + alias["path"] for group in aliases.values() for alias in group + } + walked = { + os.path.relpath(path, self.bios.parent) + for paths in duplicates.scan_duplicates(str(self.bios)).values() + for path in paths + } + self.assertEqual(walked, indexed) + + +@unittest.skipIf(os.name == "nt" or os.geteuid() == 0, "needs POSIX permissions") +class AFailedRemovalIsReported(_Bios): + """A copy that os.remove refused was printed as a warning, counted as + removed by its group line, and the command exited 0 and asked for a + database rebuild.""" + + def setUp(self): + super().setUp() + self.write("A/f.bin") + self.locked = self.write("B/X/f.bin").parent + self.locked.chmod(0o555) + + def tearDown(self): + self.locked.chmod(0o755) + super().tearDown() + + def test_the_failure_is_in_the_result_not_in_removed(self): + result = self.run_dedup() + (group,) = result.groups.values() + self.assertEqual(group.removed, []) + self.assertEqual([f.path for f in group.failed], [str(self.locked / "f.bin")]) + self.assertEqual(result.total_removed, 0) + + def test_the_report_counts_what_was_removed(self): + report = "\n".join(deduptext.report_lines(self.run_dedup())) + self.assertIn("WARNING: cannot remove", report) + self.assertIn("Removed 0 copies", report) + self.assertNotIn("Removed 1 copies", report) + + def test_the_command_exits_non_zero_without_the_rebuild_hint(self): + import contextlib + import io + import sys + from unittest import mock + + import dedup as command + + out, err = io.StringIO(), io.StringIO() + argv = ["dedup.py", "--bios-dir", str(self.bios)] + with mock.patch.object(sys, "argv", argv), contextlib.redirect_stdout(out), \ + contextlib.redirect_stderr(err): + code = command.main() + self.assertEqual(code, 1) + self.assertIn("1 copies could not be removed", err.getvalue()) + self.assertNotIn("generate_db.py", out.getvalue()) + + 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