Coverage for src/romfarmer/planner/passes/dat_dedup.py: 64%

36 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-05 02:19 -0700

1"""dat_dedup pass — one source file per DAT entry. 

2 

3When multiple source files matched the same DAT entry name (e.g. both the 

4original and a RE edition matched the same DAT game), we keep only the best 

5one. Best = highest difflib similarity between ``path.stem`` and ``dat_name`` 

6(exact match wins outright). 

7 

8Units without a ``dat_name`` on any disc are passed through unchanged. 

9""" 

10 

11from __future__ import annotations 

12 

13import difflib 

14from collections import defaultdict 

15from typing import TYPE_CHECKING 

16 

17from romfarmer.ir.catalog import Catalog, DiscRef, GameUnit, PassResult, PassTrace, UnitId 

18 

19if TYPE_CHECKING: 

20 from romfarmer.analysis.knowledge import KnowledgeBase 

21 from romfarmer.ir.manifest import BuildManifest 

22 from romfarmer.planner.costmodel import CostModel 

23 

24PASS_NAME = "dat_dedup" 

25 

26 

27def _similarity(stem: str, dat_name: str) -> float: 

28 if stem == dat_name: 

29 return 1.0 

30 return difflib.SequenceMatcher(None, stem.lower(), dat_name.lower()).ratio() 

31 

32 

33def run( 

34 catalog: Catalog, 

35 manifest: BuildManifest, 

36 kb: KnowledgeBase, 

37 cost_model: CostModel, 

38) -> PassResult: 

39 """Keep the best-matching unit per DAT entry name; pass through unmatched.""" 

40 # Group units by their primary dat_name (from disc 0 / first disc with a name) 

41 by_dat: dict[str, list[GameUnit]] = defaultdict(list) 

42 no_dat: list[GameUnit] = [] 

43 

44 for unit in catalog.units: 

45 dat_name = _primary_dat_name(unit.discs) 

46 if dat_name is None: 

47 no_dat.append(unit) 

48 else: 

49 by_dat[dat_name].append(unit) 

50 

51 removed: list[tuple[UnitId, str]] = [] 

52 keep_ids: set[UnitId] = {u.unit_id for u in no_dat} 

53 

54 for dat_name, units in by_dat.items(): 

55 if len(units) == 1: 

56 keep_ids.add(units[0].unit_id) 

57 continue 

58 # Pick the best match 

59 best = max( 

60 units, 

61 key=lambda u: _similarity(u.canonical_name, dat_name), 

62 ) 

63 keep_ids.add(best.unit_id) 

64 for unit in units: 

65 if unit.unit_id != best.unit_id: 

66 removed.append( 

67 ( 

68 unit.unit_id, 

69 f"dat_dedup: worse match for DAT entry '{dat_name}' " 

70 f"(kept '{best.canonical_name}')", 

71 ) 

72 ) 

73 

74 new_catalog = catalog.keep(keep_ids) 

75 return PassResult( 

76 catalog=new_catalog, 

77 trace=PassTrace( 

78 pass_name=PASS_NAME, 

79 removed=tuple(removed), 

80 added=(), 

81 ), 

82 ) 

83 

84 

85def _primary_dat_name(discs: tuple[DiscRef, ...]) -> str | None: 

86 """Return the dat_name from the first disc that has one.""" 

87 for disc in discs: 

88 if disc.dat_name is not None: 

89 return disc.dat_name 

90 return None