Coverage for src/romfarmer/cli/scan.py: 0%
177 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-01 23:08 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-01 23:08 -0700
1"""
2CLI commands for ROM scanning and validation.
3"""
5from pathlib import Path
7import click
8from rich import box
9from rich.console import Console
10from rich.panel import Panel
11from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn
12from rich.table import Table
14from romfarmer.catalog.database import RomGroomerDatabase
15from romfarmer.scanner import RomScanner
17console = Console()
20@click.group(name="scan")
21def scan_group():
22 """Scan and validate ROM collections."""
23 pass
26@scan_group.command(name="directory")
27@click.argument("directory", type=click.Path(exists=True, path_type=Path))
28@click.option(
29 "--database",
30 "-d",
31 type=click.Path(path_type=Path),
32 help="Database file (default: romfarmer.db)",
33)
34@click.option("--dat", help="Validate against specific DAT")
35@click.option(
36 "--recursive/--no-recursive",
37 default=True,
38 help="Scan subdirectories recursively (default: recursive)",
39)
40@click.option(
41 "--extensions", "-e", multiple=True, help="File extensions to scan (e.g., -e .nes -e .sfc)"
42)
43@click.option("--md5", is_flag=True, default=False, help="Calculate MD5 hashes (slower)")
44@click.option("--sha1", is_flag=True, default=False, help="Calculate SHA1 hashes (slower)")
45@click.option(
46 "--workers", "-w", type=int, default=4, help="Number of parallel workers (default: 4)"
47)
48@click.option("--report", "-r", type=click.Path(path_type=Path), help="Output report to file")
49@click.option(
50 "--show-unmatched", is_flag=True, default=False, help="Show unmatched files in output"
51)
52def scan_directory(
53 directory, database, dat, recursive, extensions, md5, sha1, workers, report, show_unmatched
54):
55 """
56 Scan a directory for ROM files and validate against DAT.
58 Examples:
59 romfarmer scan directory /path/to/roms
60 romfarmer scan directory /roms --dat "Nintendo - NES"
61 romfarmer scan directory /roms --recursive --md5 --sha1
62 romfarmer scan directory /roms -e .nes -e .sfc --workers 8
63 romfarmer scan directory /roms --report scan_report.txt
64 """
65 db_path = database or Path("romfarmer.db")
67 # Check if database exists
68 if not db_path.exists():
69 console.print(f"\n[red]Database not found: {db_path}[/red]")
70 console.print(
71 "[yellow]Please import DAT files first using: romfarmer dat import[/yellow]\n"
72 )
73 return
75 db = RomGroomerDatabase(db_path)
77 # Create scanner with options
78 scanner_options = {
79 "database": db,
80 "calculate_md5": md5,
81 "calculate_sha1": sha1,
82 "num_workers": workers,
83 }
85 if extensions:
86 scanner_options["extensions"] = set(extensions)
88 scanner = RomScanner(**scanner_options)
90 # Scan with progress indicator
91 console.print(f"\n[bold blue]Scanning directory: {directory}[/bold blue]")
92 console.print(f"[dim]Recursive: {recursive} | Workers: {workers} | DAT: {dat or 'All'}[/dim]\n")
94 with Progress(
95 SpinnerColumn(),
96 TextColumn("[progress.description]{task.description}"),
97 BarColumn(),
98 TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
99 console=console,
100 ) as progress:
101 task = progress.add_task("Scanning files...", total=None)
103 results, stats = scanner.scan_directory(directory, recursive=recursive, dat_name=dat)
105 progress.update(task, completed=True)
107 # Display statistics
108 _display_scan_statistics(stats)
110 # Display matched files
111 matched = [r for r in results if r.is_matched]
112 if matched:
113 _display_matched_files(matched)
115 # Display unmatched files if requested
116 if show_unmatched:
117 unmatched = [r for r in results if not r.is_matched]
118 if unmatched:
119 _display_unmatched_files(unmatched)
121 # Generate and save report if requested
122 if report:
123 scanner.generate_report(results, stats, output_path=report)
124 console.print(f"\n[green]Report saved to: {report}[/green]\n")
127@scan_group.command(name="missing")
128@click.argument("dat_name")
129@click.argument("directory", type=click.Path(exists=True, path_type=Path))
130@click.option(
131 "--database",
132 "-d",
133 type=click.Path(path_type=Path),
134 help="Database file (default: romfarmer.db)",
135)
136@click.option(
137 "--recursive/--no-recursive",
138 default=True,
139 help="Scan subdirectories recursively (default: recursive)",
140)
141@click.option(
142 "--limit", "-n", type=int, default=50, help="Maximum missing games to display (default: 50)"
143)
144@click.option(
145 "--output", "-o", type=click.Path(path_type=Path), help="Output missing games list to file"
146)
147def find_missing(dat_name, directory, database, recursive, limit, output):
148 """
149 Find games missing from your collection.
151 Scans your ROM directory and compares against a DAT to identify
152 which games you don't have.
154 Examples:
155 romfarmer scan missing "Nintendo - NES" /path/to/roms
156 romfarmer scan missing "Sega - Genesis" /roms --limit 100
157 romfarmer scan missing "Sony - PlayStation" /roms -o missing.txt
158 """
159 db_path = database or Path("romfarmer.db")
161 if not db_path.exists():
162 console.print(f"\n[red]Database not found: {db_path}[/red]\n")
163 return
165 db = RomGroomerDatabase(db_path)
166 scanner = RomScanner(db)
168 console.print(f"\n[bold blue]Finding missing games for: {dat_name}[/bold blue]")
169 console.print(f"[dim]Scanning: {directory}[/dim]\n")
171 # Scan directory
172 with Progress(
173 SpinnerColumn(),
174 TextColumn("[progress.description]{task.description}"),
175 console=console,
176 ) as progress:
177 task = progress.add_task("Scanning collection...", total=None)
178 results, stats = scanner.scan_directory(directory, recursive=recursive, dat_name=dat_name)
179 progress.update(task, completed=True)
181 # Find missing games
182 missing = scanner.find_missing_games(dat_name, results)
184 if not missing:
185 console.print("\n[green]✓ No missing games! Your collection is complete![/green]\n")
186 return
188 # Display summary
189 total_games = stats.files_matched + len(missing)
190 completion_rate = (stats.files_matched / total_games * 100) if total_games > 0 else 0
192 summary_lines = [
193 f"[bold cyan]Games in DAT:[/bold cyan] {total_games:,}",
194 f"[bold green]Games Found:[/bold green] {stats.files_matched:,}",
195 f"[bold red]Games Missing:[/bold red] {len(missing):,}",
196 f"[bold yellow]Completion:[/bold yellow] {completion_rate:.1f}%",
197 ]
199 panel = Panel(
200 "\n".join(summary_lines),
201 title=f"Collection Status: {dat_name}",
202 border_style="yellow",
203 box=box.ROUNDED,
204 )
206 console.print()
207 console.print(panel)
208 console.print()
210 # Display missing games
211 console.print(
212 f"[bold]Missing Games (showing {min(limit, len(missing))} of {len(missing)}):[/bold]\n"
213 )
215 table = Table(box=box.ROUNDED)
216 table.add_column("Game", style="cyan", max_width=50)
217 table.add_column("ROM File", style="yellow", max_width=30)
218 table.add_column("CRC", style="red")
219 table.add_column("Size", justify="right", style="blue")
221 for game in missing[:limit]:
222 size_kb = (game.size or 0) / 1024
223 size_mb = size_kb / 1024
224 size_str = f"{size_mb:.1f} MB" if size_mb >= 1 else f"{size_kb:.1f} KB"
226 table.add_row(game.name or "Unknown", game.rom_name or "-", game.crc or "-", size_str)
228 console.print(table)
230 if len(missing) > limit:
231 console.print(
232 f"\n[dim]... and {len(missing) - limit} more missing games. Use --limit to see more.[/dim]"
233 )
235 console.print()
237 # Write to output file if requested
238 if output:
239 try:
240 with open(output, "w") as f:
241 for game in missing:
242 f.write(f"{game.name}\t{game.rom_name}\t{game.crc}\t{game.size}\n")
243 console.print(f"[green]Missing games list written to: {output}[/green]\n")
244 except Exception as e:
245 console.print(f"[red]Failed to write output file: {e}[/red]\n")
248@scan_group.command(name="verify")
249@click.argument("file_path", type=click.Path(exists=True, path_type=Path))
250@click.option(
251 "--database",
252 "-d",
253 type=click.Path(path_type=Path),
254 help="Database file (default: romfarmer.db)",
255)
256@click.option("--dat", help="Validate against specific DAT")
257@click.option("--md5", is_flag=True, default=False, help="Calculate MD5 hash")
258@click.option("--sha1", is_flag=True, default=False, help="Calculate SHA1 hash")
259def verify_file(file_path, database, dat, md5, sha1):
260 """
261 Verify a single ROM file against DAT.
263 Calculates hashes and checks if the file matches any game in the database.
265 Examples:
266 romfarmer scan verify /path/to/game.nes
267 romfarmer scan verify game.sfc --dat "Nintendo - SNES"
268 romfarmer scan verify game.gba --md5 --sha1
269 """
270 db_path = database or Path("romfarmer.db")
272 if not db_path.exists():
273 console.print(f"\n[red]Database not found: {db_path}[/red]\n")
274 return
276 db = RomGroomerDatabase(db_path)
277 scanner = RomScanner(db, calculate_md5=md5, calculate_sha1=sha1)
279 console.print(f"\n[bold blue]Verifying file: {file_path.name}[/bold blue]\n")
281 # Scan single file
282 with Progress(
283 SpinnerColumn(),
284 TextColumn("Calculating hashes..."),
285 console=console,
286 ) as progress:
287 task = progress.add_task("Processing", total=None)
288 result = scanner._scan_file(file_path, dat_name=dat)
289 progress.update(task, completed=True)
291 if not result:
292 console.print("[red]Failed to scan file[/red]\n")
293 return
295 # Display file info
296 info_lines = [
297 f"[bold cyan]File:[/bold cyan] {result.file_path.name}",
298 f"[bold cyan]Size:[/bold cyan] {result.file_size:,} bytes ({result.file_size / 1024:.2f} KB)",
299 f"[bold cyan]CRC32:[/bold cyan] {result.crc32}",
300 ]
302 if result.md5:
303 info_lines.append(f"[bold cyan]MD5:[/bold cyan] {result.md5}")
304 if result.sha1:
305 info_lines.append(f"[bold cyan]SHA1:[/bold cyan] {result.sha1}")
307 console.print("\n".join(info_lines))
308 console.print()
310 # Display match status
311 if result.is_matched and result.matched_game:
312 console.print("[bold green]✓ MATCH FOUND![/bold green]\n")
314 match_lines = [
315 f"[bold cyan]Game:[/bold cyan] {result.matched_game.name}",
316 f"[bold cyan]DAT:[/bold cyan] {result.dat_name}",
317 f"[bold cyan]ROM:[/bold cyan] {result.matched_game.rom_name}",
318 ]
320 if result.matched_game.description:
321 match_lines.append(
322 f"[bold cyan]Description:[/bold cyan] {result.matched_game.description}"
323 )
325 panel = Panel(
326 "\n".join(match_lines), title="Match Details", border_style="green", box=box.ROUNDED
327 )
329 console.print(panel)
330 else:
331 console.print("[bold yellow]⚠ No match found in database[/bold yellow]\n")
332 console.print("[dim]This file doesn't match any known ROM in your imported DATs.[/dim]")
334 console.print()
337def _display_scan_statistics(stats):
338 """Display scan statistics in a panel."""
339 stats_lines = [
340 f"[bold cyan]Files Scanned:[/bold cyan] {stats.total_files_scanned:,}",
341 f"[bold blue]Total Size:[/bold blue] {stats.total_bytes_scanned / (1024**3):.2f} GB",
342 f"[bold green]Files Matched:[/bold green] {stats.files_matched:,}",
343 f"[bold yellow]Files Unmatched:[/bold yellow] {stats.files_unmatched:,}",
344 f"[bold magenta]Unique Games:[/bold magenta] {stats.unique_games_found:,}",
345 "",
346 f"[bold]Match Rate:[/bold] {stats.files_matched / max(stats.total_files_scanned, 1) * 100:.1f}%",
347 f"[bold]Scan Time:[/bold] {stats.scan_duration_seconds:.2f}s",
348 ]
350 panel = Panel(
351 "\n".join(stats_lines), title="Scan Results", border_style="cyan", box=box.ROUNDED
352 )
354 console.print()
355 console.print(panel)
356 console.print()
359def _display_matched_files(matched_results, limit=20):
360 """Display matched files in a table."""
361 console.print(
362 f"[bold green]✓ Matched Files (showing {min(limit, len(matched_results))} of {len(matched_results)}):[/bold green]\n"
363 )
365 table = Table(box=box.ROUNDED)
366 table.add_column("File", style="yellow", max_width=30)
367 table.add_column("Game", style="cyan", max_width=40)
368 table.add_column("DAT", style="magenta", max_width=25)
369 table.add_column("CRC", style="green")
371 for result in matched_results[:limit]:
372 table.add_row(
373 result.file_path.name,
374 result.matched_game.name if result.matched_game else "-",
375 result.dat_name or "-",
376 result.crc32,
377 )
379 console.print(table)
381 if len(matched_results) > limit:
382 console.print(f"\n[dim]... and {len(matched_results) - limit} more matched files.[/dim]")
384 console.print()
387def _display_unmatched_files(unmatched_results, limit=20):
388 """Display unmatched files in a table."""
389 console.print(
390 f"[bold yellow]⚠ Unmatched Files (showing {min(limit, len(unmatched_results))} of {len(unmatched_results)}):[/bold yellow]\n"
391 )
393 table = Table(box=box.ROUNDED)
394 table.add_column("File", style="yellow", max_width=40)
395 table.add_column("CRC", style="red")
396 table.add_column("Size", justify="right", style="blue")
398 for result in unmatched_results[:limit]:
399 size_mb = result.file_size / (1024**2)
400 size_str = f"{size_mb:.2f} MB" if size_mb >= 1 else f"{result.file_size / 1024:.2f} KB"
402 table.add_row(result.file_path.name, result.crc32, size_str)
404 console.print(table)
406 if len(unmatched_results) > limit:
407 console.print(
408 f"\n[dim]... and {len(unmatched_results) - limit} more unmatched files.[/dim]"
409 )
411 console.print()