mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-12-02 06:18:51 -06:00
fix: dedup returns its outcome, failures exit 1
This commit is contained in:
1 parent
64db75a6ee
commit
2ee77a0622
7 files changed
+249
-97
No files matched your search
@@ -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]:
|
||||
|
||||
+89
-62
@@ -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
|
||||
@@ -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"
|
||||
+19
-4
@@ -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__":
|
||||
|
||||
Reference in new issue
Block a user