Coverage for src/romfarmer/dat_parser/matcher.py: 0%
124 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-03 11:31 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-03 11:31 -0700
1"""ROM file matcher for DAT entries."""
3import zipfile
4from dataclasses import dataclass
5from enum import Enum
6from pathlib import Path
8from .models import DATFile, DATGame, DATRom
11class MatchType(str, Enum):
12 """Type of match found."""
14 EXACT_FILENAME = "exact_filename" # ZIP name matches ROM name exactly
15 INNER_FILENAME = "inner_filename" # File inside ZIP matches ROM name
16 CRC_MATCH = "crc_match" # CRC hash matches
17 MD5_MATCH = "md5_match" # MD5 hash matches
18 SHA1_MATCH = "sha1_match" # SHA1 hash matches
19 NO_MATCH = "no_match"
22@dataclass
23class MatchResult:
24 """Result of matching a file against a DAT."""
26 file_path: Path
27 match_type: MatchType
28 dat_game: DATGame | None = None
29 dat_rom: DATRom | None = None
30 confidence: float = 0.0 # 0.0 to 1.0
32 def is_matched(self) -> bool:
33 """Check if file matched successfully."""
34 return self.match_type != MatchType.NO_MATCH
36 def get_expected_size(self) -> int | None:
37 """Get expected ROM size from DAT."""
38 return self.dat_rom.size if self.dat_rom else None
41class ROMMatcher:
42 """Match ROM files against DAT entries."""
44 def __init__(self, dat_file: DATFile):
45 """Initialize matcher with parsed DAT.
47 Args:
48 dat_file: Parsed DATFile object
49 """
50 self.dat_file = dat_file
51 self._build_indices()
53 def _build_indices(self):
54 """Build lookup indices for fast matching."""
55 # Index by ROM name (for filename matching)
56 self.rom_name_index: dict[str, tuple[DATGame, DATRom]] = {}
57 for game in self.dat_file.games:
58 for rom in game.roms:
59 self.rom_name_index[rom.name] = (game, rom)
61 # Index by ROM name without extension (zip stem vs inner-file mismatch)
62 self.stem_index: dict[str, tuple[DATGame, DATRom]] = {}
63 for name, entry in self.rom_name_index.items():
64 self.stem_index.setdefault(Path(name).stem, entry)
66 # Index by game (set) name — arcade DATs: one zip per game, many ROMs inside
67 self.game_name_index: dict[str, DATGame] = {g.name: g for g in self.dat_file.games}
69 # Index by CRC (for hash matching)
70 self.crc_index: dict[str, tuple[DATGame, DATRom]] = {}
71 for game in self.dat_file.games:
72 for rom in game.roms:
73 if rom.crc:
74 self.crc_index[rom.crc.lower()] = (game, rom)
76 # Index by MD5
77 self.md5_index: dict[str, tuple[DATGame, DATRom]] = {}
78 for game in self.dat_file.games:
79 for rom in game.roms:
80 if rom.md5:
81 self.md5_index[rom.md5.lower()] = (game, rom)
83 # Index by SHA1
84 self.sha1_index: dict[str, tuple[DATGame, DATRom]] = {}
85 for game in self.dat_file.games:
86 for rom in game.roms:
87 if rom.sha1:
88 self.sha1_index[rom.sha1.lower()] = (game, rom)
90 def match_file(self, file_path: Path) -> MatchResult:
91 """Match a file against the DAT.
93 Matching strategy:
94 1. For No-Intro ZIPs: Strip .zip, match against ROM name
95 2. For No-Intro ZIPs: Check inner filename (should match)
96 3. For extracted files: Match filename directly
97 4. For hash-based: Match CRC/MD5/SHA1 (future enhancement)
99 Args:
100 file_path: Path to ROM file
102 Returns:
103 MatchResult with match information
104 """
105 if not file_path.exists():
106 return MatchResult(
107 file_path=file_path,
108 match_type=MatchType.NO_MATCH,
109 confidence=0.0,
110 )
112 # Strategy 1: ZIP filename matching (No-Intro)
113 if file_path.suffix.lower() == ".zip":
114 return self._match_zip_file(file_path)
116 # Strategy 2: Direct filename matching (extracted files)
117 return self._match_extracted_file(file_path)
119 def _match_zip_file(self, zip_path: Path) -> MatchResult:
120 """Match ZIP file against DAT.
122 For No-Intro:
123 - Myrient has: "Contra (USA).zip"
124 - DAT expects: "Contra (USA).nes"
125 - Match: Strip .zip, check if inner file matches
127 Args:
128 zip_path: Path to ZIP file
130 Returns:
131 MatchResult
132 """
133 # Get expected ROM name by stripping .zip
134 rom_name_base = zip_path.stem # "Contra (USA)"
136 # Try matching inner file
137 try:
138 with zipfile.ZipFile(zip_path, "r") as zf:
139 namelist = zf.namelist()
141 # Look for matching file inside ZIP
142 for inner_name in namelist:
143 # Skip directories and hidden files
144 if inner_name.endswith("/") or inner_name.startswith("."):
145 continue
147 # Check if this inner file matches a ROM in DAT
148 if inner_name in self.rom_name_index:
149 game, rom = self.rom_name_index[inner_name]
150 return MatchResult(
151 file_path=zip_path,
152 match_type=MatchType.INNER_FILENAME,
153 dat_game=game,
154 dat_rom=rom,
155 confidence=1.0,
156 )
158 # If no exact match, try fuzzy matching
159 # (in case the inner filename doesn't exactly match the ZIP name)
160 for inner_name in namelist:
161 if inner_name.endswith("/") or inner_name.startswith("."):
162 continue
164 # Check if ROM base name matches
165 inner_base = Path(inner_name).stem
166 if inner_base == rom_name_base and rom_name_base in self.stem_index:
167 game, rom = self.stem_index[rom_name_base]
168 return MatchResult(
169 file_path=zip_path,
170 match_type=MatchType.INNER_FILENAME,
171 dat_game=game,
172 dat_rom=rom,
173 confidence=0.9, # Slightly lower confidence
174 )
176 except (zipfile.BadZipFile, OSError):
177 pass
179 return MatchResult(
180 file_path=zip_path,
181 match_type=MatchType.NO_MATCH,
182 confidence=0.0,
183 )
185 def match_zip_member(self, zip_path: Path, member_name: str) -> MatchResult:
186 """Match a ZIP by its (already known) dominant member name — no I/O.
188 Rules, in order:
189 1. zip stem == DAT game name (No-Intro zips are named after the game;
190 arcade sets are one zip per game and clones share chunk filenames
191 with their parents, so this must come before any member match);
192 2. exact inner-file name;
193 3. inner stem == zip stem.
194 """
195 entry: tuple[DATGame, DATRom | None] | None = None
196 confidence = 1.0
197 game_only = self.game_name_index.get(zip_path.stem)
198 if game_only is not None:
199 entry = (game_only, game_only.roms[0] if game_only.roms else None)
200 if entry is None and member_name in self.rom_name_index:
201 entry = self.rom_name_index[member_name]
202 if entry is None and Path(member_name).stem == zip_path.stem:
203 entry = self.stem_index.get(zip_path.stem)
204 confidence = 0.9
205 if entry is None:
206 return MatchResult(file_path=zip_path, match_type=MatchType.NO_MATCH, confidence=0.0)
207 game, rom = entry
208 return MatchResult(
209 file_path=zip_path,
210 match_type=MatchType.INNER_FILENAME,
211 dat_game=game,
212 dat_rom=rom,
213 confidence=confidence,
214 )
216 def _match_extracted_file(self, file_path: Path) -> MatchResult:
217 """Match extracted file directly.
219 Args:
220 file_path: Path to extracted file
222 Returns:
223 MatchResult
224 """
225 filename = file_path.name
227 # Try exact filename match
228 if filename in self.rom_name_index:
229 game, rom = self.rom_name_index[filename]
230 return MatchResult(
231 file_path=file_path,
232 match_type=MatchType.EXACT_FILENAME,
233 dat_game=game,
234 dat_rom=rom,
235 confidence=1.0,
236 )
238 return MatchResult(
239 file_path=file_path,
240 match_type=MatchType.NO_MATCH,
241 confidence=0.0,
242 )
244 def match_by_hash(
245 self,
246 file_path: Path,
247 md5: str | None = None,
248 crc: str | None = None,
249 sha1: str | None = None,
250 ) -> MatchResult:
251 """Match file by hash (MD5, CRC, or SHA1).
253 Args:
254 file_path: Path to file
255 md5: MD5 hash string
256 crc: CRC32 hash string
257 sha1: SHA1 hash string
259 Returns:
260 MatchResult
261 """
262 # Try MD5 match
263 if md5 and md5.lower() in self.md5_index:
264 game, rom = self.md5_index[md5.lower()]
265 return MatchResult(
266 file_path=file_path,
267 match_type=MatchType.MD5_MATCH,
268 dat_game=game,
269 dat_rom=rom,
270 confidence=1.0,
271 )
273 # Try SHA1 match
274 if sha1 and sha1.lower() in self.sha1_index:
275 game, rom = self.sha1_index[sha1.lower()]
276 return MatchResult(
277 file_path=file_path,
278 match_type=MatchType.SHA1_MATCH,
279 dat_game=game,
280 dat_rom=rom,
281 confidence=1.0,
282 )
284 # Try CRC match
285 if crc and crc.lower() in self.crc_index:
286 game, rom = self.crc_index[crc.lower()]
287 return MatchResult(
288 file_path=file_path,
289 match_type=MatchType.CRC_MATCH,
290 dat_game=game,
291 dat_rom=rom,
292 confidence=1.0,
293 )
295 return MatchResult(
296 file_path=file_path,
297 match_type=MatchType.NO_MATCH,
298 confidence=0.0,
299 )
301 def get_matched_count(self, file_paths: list[Path]) -> int:
302 """Count how many files match the DAT.
304 Args:
305 file_paths: List of file paths to check
307 Returns:
308 Number of matched files
309 """
310 matched = 0
311 for file_path in file_paths:
312 result = self.match_file(file_path)
313 if result.is_matched():
314 matched += 1
315 return matched
317 def get_unmatched_files(self, file_paths: list[Path]) -> list[Path]:
318 """Get list of files that don't match the DAT.
320 Args:
321 file_paths: List of file paths to check
323 Returns:
324 List of unmatched file paths
325 """
326 unmatched = []
327 for file_path in file_paths:
328 result = self.match_file(file_path)
329 if not result.is_matched():
330 unmatched.append(file_path)
331 return unmatched