Coverage for src/romfarmer/scanner/__init__.py: 0%
197 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"""
2ROM scanning and validation against DAT files.
4Scans directories for ROM files, calculates hashes, and validates against
5imported DAT data to identify matches, missing games, and collection status.
6"""
8import hashlib
9import threading
10import zlib
11from concurrent.futures import ThreadPoolExecutor, as_completed
12from dataclasses import dataclass, field
13from pathlib import Path
15from romfarmer.catalog.database import DatGame, RomGroomerDatabase
16from romfarmer.core.logger import get_logger
18logger = get_logger()
21@dataclass
22class RomScanResult:
23 """Result of scanning a single ROM file."""
25 file_path: Path
26 file_size: int
27 crc32: str
28 md5: str | None = None
29 sha1: str | None = None
30 matched_game: DatGame | None = None
31 dat_name: str | None = None
32 is_matched: bool = False
35@dataclass
36class ScanStatistics:
37 """Statistics from ROM scanning operation."""
39 total_files_scanned: int = 0
40 total_bytes_scanned: int = 0
41 files_matched: int = 0
42 files_unmatched: int = 0
43 unique_games_found: int = 0
44 scan_duration_seconds: float = 0.0
45 errors: list[str] = field(default_factory=list)
48class RomScanner:
49 """
50 Scan directories for ROM files and validate against DAT data.
52 Features:
53 - Recursive directory scanning
54 - Multiple hash algorithms (CRC32, MD5, SHA1)
55 - DAT validation and matching
56 - Parallel processing for performance
57 - Extension filtering
58 - Progress tracking
59 """
61 DEFAULT_EXTENSIONS = {
62 ".nes",
63 ".smc",
64 ".sfc",
65 ".gb",
66 ".gbc",
67 ".gba",
68 ".gen",
69 ".md",
70 ".sms",
71 ".gg",
72 ".n64",
73 ".z64",
74 ".v64",
75 ".nds",
76 ".3ds",
77 ".cia",
78 ".min",
79 ".bin",
80 ".cue",
81 ".iso",
82 ".chd",
83 ".cso",
84 ".pbp",
85 ".zip",
86 ".7z",
87 ".rar",
88 }
90 def __init__(
91 self,
92 database: RomGroomerDatabase,
93 extensions: set[str] | None = None,
94 calculate_md5: bool = False,
95 calculate_sha1: bool = False,
96 num_workers: int = 4,
97 ):
98 """
99 Initialize ROM scanner.
101 Args:
102 database: Database instance for DAT lookups
103 extensions: File extensions to scan (default: common ROM extensions)
104 calculate_md5: Calculate MD5 hashes (slower but more accurate)
105 calculate_sha1: Calculate SHA1 hashes (slower but more accurate)
106 num_workers: Number of parallel workers for scanning
107 """
108 self.db = database
109 self.extensions = extensions or self.DEFAULT_EXTENSIONS
110 self.calculate_md5 = calculate_md5
111 self.calculate_sha1 = calculate_sha1
112 self.num_workers = num_workers
113 # SQLite connections (esp. StaticPool :memory:) are not thread-safe
114 self._db_lock = threading.Lock()
116 def scan_directory(
117 self,
118 directory: Path,
119 recursive: bool = True,
120 dat_name: str | None = None,
121 ) -> tuple[list[RomScanResult], ScanStatistics]:
122 """
123 Scan a directory for ROM files and validate against DAT.
125 Args:
126 directory: Directory to scan
127 recursive: Scan subdirectories recursively
128 dat_name: Optional DAT name to validate against (default: all DATs)
130 Returns:
131 Tuple of (scan results, statistics)
132 """
133 import time
135 start_time = time.time()
137 stats = ScanStatistics()
138 results = []
140 # Find all ROM files
141 rom_files = self._find_rom_files(directory, recursive)
142 stats.total_files_scanned = len(rom_files)
144 if not rom_files:
145 logger.warning(f"No ROM files found in {directory}")
146 stats.scan_duration_seconds = time.time() - start_time
147 return results, stats
149 logger.info(f"Found {len(rom_files)} ROM files to scan")
151 # Process files in parallel
152 with ThreadPoolExecutor(max_workers=self.num_workers) as executor:
153 future_to_file = {
154 executor.submit(self._scan_file, file_path, dat_name): file_path
155 for file_path in rom_files
156 }
158 for future in as_completed(future_to_file):
159 file_path = future_to_file[future]
160 try:
161 result = future.result()
162 if result:
163 results.append(result)
164 stats.total_bytes_scanned += result.file_size
166 if result.is_matched:
167 stats.files_matched += 1
168 else:
169 stats.files_unmatched += 1
170 except Exception as e:
171 error_msg = f"Error scanning {file_path}: {e}"
172 logger.error(error_msg)
173 stats.errors.append(error_msg)
175 # Calculate unique games
176 unique_games = {r.matched_game.name for r in results if r.matched_game}
177 stats.unique_games_found = len(unique_games)
179 stats.scan_duration_seconds = time.time() - start_time
181 logger.info(
182 f"Scan complete: {stats.files_matched}/{stats.total_files_scanned} files matched "
183 f"({stats.unique_games_found} unique games) in {stats.scan_duration_seconds:.2f}s"
184 )
186 return results, stats
188 def _find_rom_files(self, directory: Path, recursive: bool) -> list[Path]:
189 """Find all ROM files in directory."""
190 if not directory.exists():
191 raise ValueError(f"Directory does not exist: {directory}")
193 if not directory.is_dir():
194 raise ValueError(f"Not a directory: {directory}")
196 files = []
198 if recursive:
199 for ext in self.extensions:
200 files.extend(directory.rglob(f"*{ext}"))
201 else:
202 for ext in self.extensions:
203 files.extend(directory.glob(f"*{ext}"))
205 # Filter out directories and non-files
206 files = [f for f in files if f.is_file()]
208 # Sort for consistent ordering
209 files.sort()
211 return files
213 def _scan_file(self, file_path: Path, dat_name: str | None = None) -> RomScanResult | None:
214 """
215 Scan a single ROM file and validate against DAT.
217 Args:
218 file_path: Path to ROM file
219 dat_name: Optional DAT name for validation
221 Returns:
222 RomScanResult or None if file couldn't be scanned
223 """
224 try:
225 # Get file size
226 file_size = file_path.stat().st_size
228 # Calculate hashes
229 crc32, md5, sha1 = self._calculate_hashes(file_path)
231 # Create result
232 result = RomScanResult(
233 file_path=file_path,
234 file_size=file_size,
235 crc32=crc32,
236 md5=md5,
237 sha1=sha1,
238 )
240 # Try to match against DAT
241 with self._db_lock:
242 matched_game = self._match_game(crc32, md5, sha1, dat_name)
244 if matched_game:
245 result.matched_game = matched_game
246 result.dat_name = matched_game.dat_file.name if matched_game.dat_file else None
247 result.is_matched = True
248 logger.debug(f"Matched {file_path.name} -> {matched_game.name}")
249 else:
250 logger.debug(f"No match found for {file_path.name} (CRC: {crc32})")
252 return result
254 except Exception as e:
255 logger.error(f"Failed to scan {file_path}: {e}")
256 return None
258 def _calculate_hashes(self, file_path: Path) -> tuple[str, str | None, str | None]:
259 """
260 Calculate file hashes.
262 Returns:
263 Tuple of (crc32, md5, sha1)
264 """
265 crc32_hash = 0
266 md5_hash = hashlib.md5() if self.calculate_md5 else None
267 sha1_hash = hashlib.sha1() if self.calculate_sha1 else None
269 # Read file in chunks for memory efficiency
270 chunk_size = 1024 * 1024 # 1MB chunks
272 with open(file_path, "rb") as f:
273 while True:
274 chunk = f.read(chunk_size)
275 if not chunk:
276 break
278 # Update CRC32
279 crc32_hash = zlib.crc32(chunk, crc32_hash)
281 # Update MD5 if requested
282 if md5_hash:
283 md5_hash.update(chunk)
285 # Update SHA1 if requested
286 if sha1_hash:
287 sha1_hash.update(chunk)
289 # Convert CRC32 to hex string (8 characters, lowercase)
290 crc32_str = f"{crc32_hash & 0xFFFFFFFF:08x}"
292 # Get hex digests for MD5 and SHA1
293 md5_str = md5_hash.hexdigest() if md5_hash else None
294 sha1_str = sha1_hash.hexdigest() if sha1_hash else None
296 return crc32_str, md5_str, sha1_str
298 def _match_game(
299 self,
300 crc32: str,
301 md5: str | None,
302 sha1: str | None,
303 dat_name: str | None,
304 ) -> DatGame | None:
305 """
306 Match a ROM against DAT database.
308 Tries matching in order: CRC32, MD5, SHA1
309 """
310 session = self.db.get_session()
311 try:
312 # Get DAT file ID if specified
313 dat_file_id = None
314 if dat_name:
315 dat_file = self.db.get_dat_file(session, dat_name)
316 if dat_file:
317 dat_file_id = dat_file.id
319 # Try CRC32 match first (fastest)
320 game = self.db.find_game_by_crc(session, crc32, dat_file_id=dat_file_id)
321 if game:
322 return game
324 # Try MD5 if available
325 if md5:
326 # MD5 matching would require additional database support
327 # For now, we rely on CRC32
328 pass
330 # Try SHA1 if available
331 if sha1:
332 # SHA1 matching would require additional database support
333 # For now, we rely on CRC32
334 pass
336 return None
338 finally:
339 session.close()
341 def find_missing_games(
342 self,
343 dat_name: str,
344 scanned_results: list[RomScanResult],
345 ) -> list[DatGame]:
346 """
347 Find games in DAT that are missing from scanned collection.
349 Args:
350 dat_name: DAT name to check against
351 scanned_results: Results from scanning
353 Returns:
354 List of missing DatGame entries
355 """
356 session = self.db.get_session()
357 try:
358 # Get all games from DAT
359 dat_file = self.db.get_dat_file(session, dat_name)
360 if not dat_file:
361 logger.error(f"DAT not found: {dat_name}")
362 return []
364 all_games = self.db.get_dat_games(session, dat_file.id, limit=None)
366 # Get CRCs of matched games
367 matched_crcs = {r.matched_game.crc for r in scanned_results if r.matched_game}
369 # Find missing games
370 missing_games = [g for g in all_games if g.crc not in matched_crcs]
372 return missing_games
374 finally:
375 session.close()
377 def generate_report(
378 self,
379 results: list[RomScanResult],
380 stats: ScanStatistics,
381 output_path: Path | None = None,
382 ) -> str:
383 """
384 Generate a text report of scan results.
386 Args:
387 results: Scan results
388 stats: Scan statistics
389 output_path: Optional path to write report
391 Returns:
392 Report text
393 """
394 lines = []
395 lines.append("=" * 80)
396 lines.append("ROM SCAN REPORT")
397 lines.append("=" * 80)
398 lines.append("")
400 # Statistics
401 lines.append("STATISTICS:")
402 lines.append(f" Total Files Scanned: {stats.total_files_scanned:,}")
403 lines.append(f" Total Size: {stats.total_bytes_scanned / (1024**3):.2f} GB")
404 lines.append(f" Files Matched: {stats.files_matched:,}")
405 lines.append(f" Files Unmatched: {stats.files_unmatched:,}")
406 lines.append(f" Unique Games: {stats.unique_games_found:,}")
407 lines.append(
408 f" Match Rate: {stats.files_matched / max(stats.total_files_scanned, 1) * 100:.1f}%"
409 )
410 lines.append(f" Scan Duration: {stats.scan_duration_seconds:.2f}s")
411 lines.append("")
413 # Matched files
414 matched = [r for r in results if r.is_matched]
415 if matched:
416 lines.append(f"MATCHED FILES ({len(matched)}):")
417 for result in matched[:50]: # Limit to first 50
418 lines.append(f" {result.file_path.name}")
419 lines.append(f" -> {result.matched_game.name}")
420 lines.append(f" CRC: {result.crc32} | Size: {result.file_size:,} bytes")
421 lines.append("")
423 if len(matched) > 50:
424 lines.append(f" ... and {len(matched) - 50} more matched files")
425 lines.append("")
427 # Unmatched files
428 unmatched = [r for r in results if not r.is_matched]
429 if unmatched:
430 lines.append(f"UNMATCHED FILES ({len(unmatched)}):")
431 for result in unmatched[:30]: # Limit to first 30
432 lines.append(f" {result.file_path.name}")
433 lines.append(f" CRC: {result.crc32} | Size: {result.file_size:,} bytes")
435 if len(unmatched) > 30:
436 lines.append(f" ... and {len(unmatched) - 30} more unmatched files")
437 lines.append("")
439 # Errors
440 if stats.errors:
441 lines.append(f"ERRORS ({len(stats.errors)}):")
442 for error in stats.errors[:20]:
443 lines.append(f" {error}")
444 if len(stats.errors) > 20:
445 lines.append(f" ... and {len(stats.errors) - 20} more errors")
446 lines.append("")
448 lines.append("=" * 80)
450 report = "\n".join(lines)
452 # Write to file if requested
453 if output_path:
454 output_path.write_text(report)
455 logger.info(f"Report written to {output_path}")
457 return report