Coverage for src/romfarmer/cli/dat.py: 0%

434 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-01 23:08 -0700

1""" 

2CLI commands for DAT file management. 

3""" 

4 

5from pathlib import Path 

6 

7import click 

8from rich import box 

9from rich.console import Console 

10from rich.panel import Panel 

11from rich.table import Table 

12 

13from romfarmer.catalog.database import RomGroomerDatabase 

14from romfarmer.dat.filter import OneGameOneRomFilter 

15from romfarmer.dat.importer import DatImportService 

16 

17console = Console() 

18 

19 

20@click.group(name="dat") 

21def dat_group(): 

22 """Manage DAT files (import, query, analyze).""" 

23 pass 

24 

25 

26@dat_group.command(name="import") 

27@click.argument("dat_files", type=click.Path(exists=True, path_type=Path), nargs=-1, required=True) 

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( 

35 "--update", "-u", is_flag=True, default=False, help="Update existing DATs instead of skipping" 

36) 

37def import_dats(dat_files, database, update): 

38 """ 

39 Import one or more DAT files into the database. 

40 

41 Examples: 

42 romfarmer dat import nointro.dat 

43 romfarmer dat import *.dat --update 

44 romfarmer dat import nointro.dat redump.dat -d custom.db 

45 """ 

46 db_path = database or Path("romfarmer.db") 

47 db = RomGroomerDatabase(db_path) 

48 service = DatImportService(db) 

49 

50 console.print(f"\n[bold blue]Importing {len(dat_files)} DAT file(s)...[/bold blue]\n") 

51 

52 results = service.import_dats(list(dat_files), update_existing=update) 

53 

54 # Display results 

55 table = Table(title="Import Results", box=box.ROUNDED) 

56 table.add_column("DAT Name", style="cyan") 

57 table.add_column("Status", style="yellow") 

58 table.add_column("Games", justify="right", style="green") 

59 table.add_column("Size", justify="right", style="blue") 

60 

61 for result in results: 

62 status = result.get("status", "success") 

63 if status == "error": 

64 table.add_row(result["dat_name"], f"[red]{status}[/red]", "-", "-") 

65 else: 

66 dat_name = result.get("dat_name", "Unknown") 

67 games = result.get("games_imported", result.get("total_games", 0)) 

68 size_mb = result.get("total_size", 0) / (1024 * 1024) 

69 

70 status_str = ( 

71 "[green]imported[/green]" if status == "success" else f"[yellow]{status}[/yellow]" 

72 ) 

73 table.add_row(dat_name, status_str, str(games), f"{size_mb:.1f} MB") 

74 

75 console.print(table) 

76 console.print() 

77 

78 

79@dat_group.command(name="list") 

80@click.option( 

81 "--database", 

82 "-d", 

83 type=click.Path(path_type=Path), 

84 help="Database file (default: romfarmer.db)", 

85) 

86def list_dats(database): 

87 """ 

88 List all imported DAT files. 

89 

90 Examples: 

91 romfarmer dat list 

92 romfarmer dat list -d custom.db 

93 """ 

94 db_path = database or Path("romfarmer.db") 

95 db = RomGroomerDatabase(db_path) 

96 service = DatImportService(db) 

97 

98 dats = service.list_imported_dats() 

99 

100 if not dats: 

101 console.print("\n[yellow]No DAT files imported yet.[/yellow]\n") 

102 return 

103 

104 table = Table(title=f"Imported DATs ({len(dats)})", box=box.ROUNDED) 

105 table.add_column("Name", style="cyan") 

106 table.add_column("Version", style="yellow") 

107 table.add_column("Author", style="magenta") 

108 table.add_column("Games", justify="right", style="green") 

109 table.add_column("Size", justify="right", style="blue") 

110 table.add_column("Imported", style="dim") 

111 

112 for dat in dats: 

113 size_mb = (dat.total_size or 0) / (1024 * 1024) 

114 imported = dat.imported_at.strftime("%Y-%m-%d %H:%M") if dat.imported_at else "Unknown" 

115 

116 table.add_row( 

117 dat.name, 

118 dat.version or "-", 

119 dat.author or "-", 

120 str(dat.total_games or 0), 

121 f"{size_mb:.1f} MB", 

122 imported, 

123 ) 

124 

125 console.print() 

126 console.print(table) 

127 console.print() 

128 

129 

130@dat_group.command(name="info") 

131@click.argument("dat_name") 

132@click.option( 

133 "--database", 

134 "-d", 

135 type=click.Path(path_type=Path), 

136 help="Database file (default: romfarmer.db)", 

137) 

138def dat_info(dat_name, database): 

139 """ 

140 Show detailed information about a DAT file. 

141 

142 Examples: 

143 romfarmer dat info "Nintendo - NES" 

144 romfarmer dat info "Sony - PlayStation" -d custom.db 

145 """ 

146 db_path = database or Path("romfarmer.db") 

147 db = RomGroomerDatabase(db_path) 

148 service = DatImportService(db) 

149 

150 dat = service.get_dat_info(dat_name) 

151 

152 if not dat: 

153 console.print(f"\n[red]DAT not found: {dat_name}[/red]\n") 

154 return 

155 

156 # Build info text 

157 info_lines = [ 

158 f"[bold cyan]Name:[/bold cyan] {dat.name}", 

159 f"[bold cyan]Description:[/bold cyan] {dat.description or 'N/A'}", 

160 f"[bold cyan]Version:[/bold cyan] {dat.version or 'N/A'}", 

161 f"[bold cyan]Author:[/bold cyan] {dat.author or 'N/A'}", 

162 f"[bold cyan]Date:[/bold cyan] {dat.date or 'N/A'}", 

163 "", 

164 f"[bold green]Total Games:[/bold green] {dat.total_games or 0:,}", 

165 f"[bold blue]Total Size:[/bold blue] {(dat.total_size or 0) / (1024 * 1024):.1f} MB", 

166 "", 

167 f"[bold yellow]Imported:[/bold yellow] {dat.imported_at.strftime('%Y-%m-%d %H:%M:%S') if dat.imported_at else 'Unknown'}", 

168 f"[bold yellow]Updated:[/bold yellow] {dat.updated_at.strftime('%Y-%m-%d %H:%M:%S') if dat.updated_at else 'N/A'}", 

169 ] 

170 

171 panel = Panel( 

172 "\n".join(info_lines), 

173 title=f"DAT Information: {dat.name}", 

174 border_style="cyan", 

175 box=box.ROUNDED, 

176 ) 

177 

178 console.print() 

179 console.print(panel) 

180 console.print() 

181 

182 

183@dat_group.command(name="games") 

184@click.argument("dat_name") 

185@click.option( 

186 "--database", 

187 "-d", 

188 type=click.Path(path_type=Path), 

189 help="Database file (default: romfarmer.db)", 

190) 

191@click.option( 

192 "--limit", "-n", type=int, default=50, help="Maximum number of games to display (default: 50)" 

193) 

194def list_games(dat_name, database, limit): 

195 """ 

196 List games from a DAT file. 

197 

198 Examples: 

199 romfarmer dat games "Nintendo - NES" 

200 romfarmer dat games "Sony - PlayStation" --limit 100 

201 romfarmer dat games "Sega - Genesis" -n 10 -d custom.db 

202 """ 

203 db_path = database or Path("romfarmer.db") 

204 db = RomGroomerDatabase(db_path) 

205 service = DatImportService(db) 

206 

207 games = service.get_dat_games(dat_name, limit=limit) 

208 

209 if not games: 

210 console.print(f"\n[yellow]No games found in DAT: {dat_name}[/yellow]\n") 

211 return 

212 

213 table = Table(title=f"Games in {dat_name} (showing {len(games)})", box=box.ROUNDED) 

214 table.add_column("Name", style="cyan", max_width=50) 

215 table.add_column("ROM", style="yellow", max_width=30) 

216 table.add_column("Size", justify="right", style="blue") 

217 table.add_column("CRC", style="green") 

218 

219 for game in games: 

220 size_kb = (game.size or 0) / 1024 

221 size_mb = size_kb / 1024 

222 size_str = f"{size_mb:.1f} MB" if size_mb >= 1 else f"{size_kb:.1f} KB" 

223 

224 table.add_row(game.name or "Unknown", game.rom_name or "-", size_str, game.crc or "-") 

225 

226 console.print() 

227 console.print(table) 

228 

229 # Show total count if limited 

230 total_count = service.get_statistics(dat_name).get("total_games", 0) 

231 if total_count > len(games): 

232 console.print( 

233 f"\n[dim]Showing {len(games)} of {total_count} games. Use --limit to see more.[/dim]" 

234 ) 

235 

236 console.print() 

237 

238 

239@dat_group.command(name="search") 

240@click.argument("query") 

241@click.option( 

242 "--database", 

243 "-d", 

244 type=click.Path(path_type=Path), 

245 help="Database file (default: romfarmer.db)", 

246) 

247@click.option("--dat", help="Search within specific DAT") 

248@click.option("--by-crc", is_flag=True, default=False, help="Search by CRC instead of name") 

249def search_games(query, database, dat, by_crc): 

250 """ 

251 Search for games by name or CRC. 

252 

253 Examples: 

254 romfarmer dat search "Super Mario" 

255 romfarmer dat search "3337ec46" --by-crc 

256 romfarmer dat search "Zelda" --dat "Nintendo - NES" 

257 romfarmer dat search "mario" --dat "Nintendo - SNES" -d custom.db 

258 """ 

259 db_path = database or Path("romfarmer.db") 

260 db = RomGroomerDatabase(db_path) 

261 service = DatImportService(db) 

262 

263 if by_crc: 

264 game = service.find_game_by_crc(query, dat_name=dat) 

265 games = [game] if game else [] 

266 search_type = "CRC" 

267 else: 

268 games = service.find_games_by_name(query, dat_name=dat) 

269 search_type = "name" 

270 

271 if not games: 

272 scope = f" in {dat}" if dat else "" 

273 console.print( 

274 f"\n[yellow]No games found matching {search_type} '{query}'{scope}[/yellow]\n" 

275 ) 

276 return 

277 

278 scope_str = f" in {dat}" if dat else " (all DATs)" 

279 table = Table( 

280 title=f"Search Results for '{query}'{scope_str} ({len(games)} found)", box=box.ROUNDED 

281 ) 

282 table.add_column("DAT", style="magenta", max_width=30) 

283 table.add_column("Game", style="cyan", max_width=40) 

284 table.add_column("ROM", style="yellow", max_width=30) 

285 table.add_column("CRC", style="green") 

286 table.add_column("Size", justify="right", style="blue") 

287 

288 for game in games: 

289 size_kb = (game.size or 0) / 1024 

290 size_mb = size_kb / 1024 

291 size_str = f"{size_mb:.1f} MB" if size_mb >= 1 else f"{size_kb:.1f} KB" 

292 

293 table.add_row( 

294 game.dat_file.name if game.dat_file else "Unknown", 

295 game.name or "Unknown", 

296 game.rom_name or "-", 

297 game.crc or "-", 

298 size_str, 

299 ) 

300 

301 console.print() 

302 console.print(table) 

303 console.print() 

304 

305 

306@dat_group.command(name="delete") 

307@click.argument("dat_name") 

308@click.option( 

309 "--database", 

310 "-d", 

311 type=click.Path(path_type=Path), 

312 help="Database file (default: romfarmer.db)", 

313) 

314@click.option("--yes", "-y", is_flag=True, default=False, help="Skip confirmation prompt") 

315def delete_dat(dat_name, database, yes): 

316 """ 

317 Delete a DAT file and all its games from the database. 

318 

319 Examples: 

320 romfarmer dat delete "Nintendo - NES" 

321 romfarmer dat delete "Sony - PlayStation" --yes 

322 romfarmer dat delete "Sega - Genesis" -y -d custom.db 

323 """ 

324 db_path = database or Path("romfarmer.db") 

325 db = RomGroomerDatabase(db_path) 

326 service = DatImportService(db) 

327 

328 # Check if DAT exists 

329 dat = service.get_dat_info(dat_name) 

330 if not dat: 

331 console.print(f"\n[red]DAT not found: {dat_name}[/red]\n") 

332 return 

333 

334 # Confirm deletion 

335 if not yes: 

336 console.print("\n[yellow]This will delete:[/yellow]") 

337 console.print(f" DAT: {dat.name}") 

338 console.print(f" Games: {dat.total_games or 0:,}") 

339 console.print() 

340 

341 if not click.confirm("Are you sure you want to delete this DAT?"): 

342 console.print("[dim]Cancelled.[/dim]\n") 

343 return 

344 

345 # Delete 

346 success = service.delete_dat(dat_name) 

347 

348 if success: 

349 console.print(f"\n[green]Successfully deleted DAT: {dat_name}[/green]\n") 

350 else: 

351 console.print(f"\n[red]Failed to delete DAT: {dat_name}[/red]\n") 

352 

353 

354@dat_group.command(name="stats") 

355@click.argument("dat_name", required=False) 

356@click.option( 

357 "--database", 

358 "-d", 

359 type=click.Path(path_type=Path), 

360 help="Database file (default: romfarmer.db)", 

361) 

362def show_stats(dat_name, database): 

363 """ 

364 Show statistics for a specific DAT or all DATs. 

365 

366 Examples: 

367 romfarmer dat stats 

368 romfarmer dat stats "Nintendo - NES" 

369 romfarmer dat stats "Sony - PlayStation" -d custom.db 

370 """ 

371 db_path = database or Path("romfarmer.db") 

372 db = RomGroomerDatabase(db_path) 

373 service = DatImportService(db) 

374 

375 stats = service.get_statistics(dat_name) 

376 

377 if not stats: 

378 if dat_name: 

379 console.print(f"\n[red]DAT not found: {dat_name}[/red]\n") 

380 else: 

381 console.print("\n[yellow]No DATs imported yet.[/yellow]\n") 

382 return 

383 

384 # Build stats display 

385 title = f"Statistics: {dat_name}" if dat_name else "Overall Statistics" 

386 

387 stats_lines = [ 

388 f"[bold cyan]Total DATs:[/bold cyan] {stats.get('total_dats', 0):,}", 

389 f"[bold green]Total Games:[/bold green] {stats.get('total_games', 0):,}", 

390 f"[bold blue]Total Size:[/bold blue] {stats.get('total_size', 0) / (1024 * 1024 * 1024):.2f} GB", 

391 ] 

392 

393 if "average_game_size" in stats: 

394 avg_size_mb = stats["average_game_size"] / (1024 * 1024) 

395 stats_lines.append(f"[bold yellow]Average Game Size:[/bold yellow] {avg_size_mb:.1f} MB") 

396 

397 panel = Panel("\n".join(stats_lines), title=title, border_style="cyan", box=box.ROUNDED) 

398 

399 console.print() 

400 console.print(panel) 

401 console.print() 

402 

403 

404@dat_group.command(name="filter") 

405@click.argument("dat_name") 

406@click.option( 

407 "--database", 

408 "-d", 

409 type=click.Path(path_type=Path), 

410 help="Database file (default: romfarmer.db)", 

411) 

412@click.option( 

413 "--regions", "-r", multiple=True, help="Region priority (e.g., -r USA -r Europe -r Japan)" 

414) 

415@click.option( 

416 "--languages", "-l", multiple=True, help="Language priority (e.g., -l En -l Ja -l Fr)" 

417) 

418@click.option( 

419 "--no-prefer-parents", is_flag=True, default=False, help="Don't prefer parent ROMs over clones" 

420) 

421@click.option( 

422 "--no-prefer-revisions", is_flag=True, default=False, help="Don't prefer later revisions" 

423) 

424@click.option( 

425 "--output", "-o", type=click.Path(path_type=Path), help="Output filtered game list to file" 

426) 

427def filter_1g1r( 

428 dat_name, database, regions, languages, no_prefer_parents, no_prefer_revisions, output 

429): 

430 """ 

431 Apply 1G1R (One Game One ROM) filtering to a DAT. 

432 

433 Filters games to select the best version of each game based on: 

434 - Region priorities (default: USA > World > Europe > Japan) 

435 - Language priorities (default: En > Ja > Fr > De) 

436 - Parent vs Clone preference 

437 - Revision numbers 

438 

439 Examples: 

440 romfarmer dat filter "Nintendo - NES" 

441 romfarmer dat filter "Sega - Genesis" -r Japan -r USA 

442 romfarmer dat filter "Sony - PlayStation" -l En -l Ja 

443 romfarmer dat filter "Nintendo - SNES" --no-prefer-revisions 

444 romfarmer dat filter "Nintendo - NES" -o filtered_games.txt 

445 """ 

446 db_path = database or Path("romfarmer.db") 

447 db = RomGroomerDatabase(db_path) 

448 service = DatImportService(db) 

449 

450 # Get games from DAT 

451 games = service.get_dat_games(dat_name, limit=None) 

452 

453 if not games: 

454 console.print(f"\n[yellow]No games found in DAT: {dat_name}[/yellow]\n") 

455 return 

456 

457 console.print(f"\n[bold blue]Filtering {len(games)} games from {dat_name}...[/bold blue]\n") 

458 

459 # Create filter with custom preferences 

460 filter_config = { 

461 "prefer_parents": not no_prefer_parents, 

462 "prefer_later_revisions": not no_prefer_revisions, 

463 } 

464 

465 if regions: 

466 filter_config["region_priority"] = list(regions) 

467 if languages: 

468 filter_config["language_priority"] = list(languages) 

469 

470 filter_obj = OneGameOneRomFilter(**filter_config) 

471 

472 # Apply filter 

473 filtered_games, stats = filter_obj.filter_games(games) 

474 

475 # Display statistics 

476 stats_lines = [ 

477 f"[bold cyan]Total Games:[/bold cyan] {stats.total_games:,}", 

478 f"[bold green]Unique Games:[/bold green] {stats.unique_games:,}", 

479 f"[bold yellow]Filtered Games:[/bold yellow] {stats.filtered_games:,}", 

480 f"[bold red]Duplicates Removed:[/bold red] {stats.duplicates_removed:,}", 

481 "", 

482 f"[bold blue]Parents Selected:[/bold blue] {stats.parents_selected:,}", 

483 f"[bold magenta]Clones Selected:[/bold magenta] {stats.clones_selected:,}", 

484 ] 

485 

486 panel = Panel( 

487 "\n".join(stats_lines), 

488 title=f"1G1R Filter Results: {dat_name}", 

489 border_style="green", 

490 box=box.ROUNDED, 

491 ) 

492 

493 console.print(panel) 

494 

495 # Display sample of filtered games 

496 console.print("\n[bold]Sample of filtered games (first 20):[/bold]\n") 

497 

498 table = Table(box=box.ROUNDED) 

499 table.add_column("Game", style="cyan", max_width=50) 

500 table.add_column("ROM", style="yellow", max_width=30) 

501 table.add_column("CRC", style="green") 

502 table.add_column("Size", justify="right", style="blue") 

503 

504 for game in filtered_games[:20]: 

505 size_kb = (game.size or 0) / 1024 

506 size_mb = size_kb / 1024 

507 size_str = f"{size_mb:.1f} MB" if size_mb >= 1 else f"{size_kb:.1f} KB" 

508 

509 table.add_row(game.name or "Unknown", game.rom_name or "-", game.crc or "-", size_str) 

510 

511 console.print(table) 

512 

513 if len(filtered_games) > 20: 

514 console.print(f"\n[dim]Showing 20 of {len(filtered_games)} filtered games.[/dim]\n") 

515 

516 # Write to output file if requested 

517 if output: 

518 try: 

519 with open(output, "w") as f: 

520 for game in filtered_games: 

521 f.write(f"{game.name}\t{game.rom_name}\t{game.crc}\n") 

522 console.print(f"[green]Filtered games written to: {output}[/green]\n") 

523 except Exception as e: 

524 console.print(f"[red]Failed to write output file: {e}[/red]\n") 

525 

526 

527@dat_group.command(name="generate") 

528@click.argument("source_dir", type=click.Path(exists=True, path_type=Path)) 

529@click.option( 

530 "--output", 

531 "-o", 

532 type=click.Path(path_type=Path), 

533 help="Output DAT file path (default: dats/generated/<name>.dat)", 

534) 

535@click.option( 

536 "--name", "-n", type=str, help="DAT name (default: derived from source directory name)" 

537) 

538@click.option( 

539 "--reference", 

540 "-r", 

541 type=click.Path(exists=True, path_type=Path), 

542 multiple=True, 

543 help="Reference DAT to enrich from (can specify multiple)", 

544) 

545@click.option( 

546 "--hash-outer", 

547 is_flag=True, 

548 default=False, 

549 help="Compute MD5/SHA1/CRC of outer files (slow for large files)", 

550) 

551@click.option( 

552 "--hash-zip-contents", 

553 is_flag=True, 

554 default=False, 

555 help="Open ZIPs and record inner file metadata with CRC", 

556) 

557@click.option( 

558 "--crc-from-zip", 

559 is_flag=True, 

560 default=False, 

561 help="Extract CRC32 from ZIP central directory (instant, no I/O)", 

562) 

563@click.option("--recursive", is_flag=True, default=False, help="Scan subdirectories recursively") 

564@click.option( 

565 "--workers", 

566 "-w", 

567 type=int, 

568 default=None, 

569 help="Number of parallel workers for hashing (default: CPU count)", 

570) 

571def generate_dat( 

572 source_dir, 

573 output, 

574 name, 

575 reference, 

576 hash_outer, 

577 hash_zip_contents, 

578 crc_from_zip, 

579 recursive, 

580 workers, 

581): 

582 """Generate a DAT file from a source ROM directory. 

583 

584 Scans a directory of ROM files and creates a standard Logiqx XML DAT. 

585 Optionally enriches entries by fuzzy-matching against reference DATs 

586 to borrow category, description, and other metadata. 

587 

588 Examples: 

589 romfarmer dat generate /path/to/wii-u-wux/ 

590 romfarmer dat generate /path/to/roms/ -n "Nintendo - Wii U (WUX)" 

591 romfarmer dat generate /path/to/roms/ -r existing.dat -o custom.dat 

592 romfarmer dat generate /path/to/roms/ --hash-zip-contents 

593 """ 

594 from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElapsedColumn 

595 

596 from romfarmer.dat_parser.generator import ( 

597 enrich_from_reference, 

598 scan_source_directory, 

599 write_dat_xml, 

600 ) 

601 from romfarmer.dat_parser.parser import DATParser 

602 

603 # Derive DAT name from source directory if not specified 

604 if not name: 

605 name = source_dir.name 

606 

607 console.print(f"\n[bold blue]Generating DAT from:[/bold blue] {source_dir}") 

608 console.print(f"[bold blue]DAT name:[/bold blue] {name}\n") 

609 

610 # Scan source directory 

611 with Progress( 

612 SpinnerColumn(), 

613 TextColumn("[progress.description]{task.description}"), 

614 BarColumn(), 

615 TextColumn("{task.completed}/{task.total}"), 

616 TimeElapsedColumn(), 

617 console=console, 

618 ) as progress: 

619 task = progress.add_task("Scanning source files...", total=None) 

620 

621 def on_scan_progress(current, total, filename): 

622 progress.update( 

623 task, total=total, completed=current, description=f"Scanning: {filename[:50]}" 

624 ) 

625 

626 games = scan_source_directory( 

627 source_dir, 

628 compute_hashes=hash_outer, 

629 hash_zip_contents=hash_zip_contents, 

630 crc_from_zip=crc_from_zip, 

631 recursive=recursive, 

632 workers=workers, 

633 progress_callback=on_scan_progress, 

634 ) 

635 

636 console.print(f" [green]Found {len(games)} files[/green]") 

637 

638 # Enrich from reference DATs 

639 total_enriched = 0 

640 for ref_path in reference: 

641 ref_path = Path(ref_path) 

642 console.print(f"\n[bold cyan]Enriching from reference:[/bold cyan] {ref_path.name}") 

643 

644 # Handle ZIP-compressed reference DATs 

645 if ref_path.suffix.lower() == ".zip": 

646 import tempfile 

647 import zipfile 

648 

649 with tempfile.TemporaryDirectory() as tmpdir: 

650 with zipfile.ZipFile(ref_path, "r") as zf: 

651 dat_files = [f for f in zf.namelist() if f.endswith(".dat")] 

652 if not dat_files: 

653 console.print(f" [red]No .dat file found in {ref_path.name}[/red]") 

654 continue 

655 zf.extract(dat_files[0], tmpdir) 

656 extracted = Path(tmpdir) / dat_files[0] 

657 parser = DATParser() 

658 ref_dat = parser.parse(extracted) 

659 else: 

660 parser = DATParser() 

661 ref_dat = parser.parse(ref_path) 

662 

663 console.print(f" Reference contains {ref_dat.get_game_count()} games") 

664 

665 matched, total = enrich_from_reference(games, ref_dat) 

666 total_enriched += matched 

667 console.print( 

668 f" [green]Matched {matched}/{total} games ({matched * 100 // max(total, 1)}%)[/green]" 

669 ) 

670 

671 # Determine output path 

672 if not output: 

673 output = Path("dats/generated") / f"{name}.dat" 

674 

675 # Write DAT 

676 written = write_dat_xml( 

677 games, 

678 output, 

679 dat_name=name, 

680 ) 

681 

682 # Summary 

683 console.print(f"\n[bold green]DAT generated:[/bold green] {written}") 

684 console.print(f" Games: {len(games)}") 

685 total_size = sum(g.get_total_size() for g in games) 

686 if total_size > 0: 

687 console.print(f" Total size: {total_size / (1024**3):.2f} GB") 

688 if total_enriched: 

689 console.print(f" Enriched from reference: {total_enriched}") 

690 console.print() 

691 

692 

693# ── Clone list maintenance commands ────────────────────────────────────── 

694 

695 

696@dat_group.command(name="diff") 

697@click.argument("old_dat", type=click.Path(exists=True, path_type=Path)) 

698@click.argument("new_dat", type=click.Path(exists=True, path_type=Path)) 

699def diff_dats(old_dat, new_dat): 

700 """Compare two DAT versions by hash — detect renames, additions, removals. 

701 

702 Uses SHA1 > MD5 > CRC to track games across versions. Games with the 

703 same hash but different names are renames (title corrections, region changes). 

704 

705 Examples: 

706 romfarmer dat diff old-redump-wii.dat new-redump-wii.dat 

707 romfarmer dat diff dats/wii-2024.dat dats/wii-2026.dat 

708 """ 

709 from romfarmer.dat_parser.clonelist import dat_diff 

710 from romfarmer.dat_parser.parser import DATParser 

711 

712 parser = DATParser() 

713 console.print("\n[bold blue]Diffing DATs:[/bold blue]") 

714 console.print(f" Old: {old_dat.name}") 

715 console.print(f" New: {new_dat.name}\n") 

716 

717 old_parsed = _parse_dat(parser, old_dat) 

718 new_parsed = _parse_dat(parser, new_dat) 

719 

720 result = dat_diff(old_parsed, new_parsed) 

721 

722 # Summary 

723 console.print(f" Old: {result.old_count} games") 

724 console.print(f" New: {result.new_count} games\n") 

725 

726 if not result.has_changes: 

727 console.print("[green]No changes detected.[/green]\n") 

728 return 

729 

730 # Renames 

731 if result.renames: 

732 table = Table(title=f"Renames ({len(result.renames)})", box=box.SIMPLE) 

733 table.add_column("Old Name", style="red") 

734 table.add_column("New Name", style="green") 

735 for r in result.renames: 

736 table.add_row(r.old_name, r.new_name) 

737 console.print(table) 

738 

739 # Additions 

740 if result.additions: 

741 console.print(f"\n[bold green]Additions ({len(result.additions)}):[/bold green]") 

742 for name in result.additions[:20]: 

743 console.print(f" + {name}") 

744 if len(result.additions) > 20: 

745 console.print(f" ... and {len(result.additions) - 20} more") 

746 

747 # Removals 

748 if result.removals: 

749 console.print(f"\n[bold red]Removals ({len(result.removals)}):[/bold red]") 

750 for name in result.removals[:20]: 

751 console.print(f" - {name}") 

752 if len(result.removals) > 20: 

753 console.print(f" ... and {len(result.removals) - 20} more") 

754 

755 console.print() 

756 

757 

758@dat_group.command(name="clonelist-validate") 

759@click.argument("clonelist", type=click.Path(exists=True, path_type=Path)) 

760@click.argument("dat_file", type=click.Path(exists=True, path_type=Path)) 

761def validate_clonelist(clonelist, dat_file): 

762 """Validate a Retool clone list against a DAT — find broken searchTerms. 

763 

764 Checks every searchTerm in the clone list against the DAT's game names. 

765 Reports unmatched terms with fuzzy suggestions for likely fixes. 

766 

767 Examples: 

768 romfarmer dat clonelist-validate Nintendo\\ -\\ Wii.json redump-wii.dat 

769 """ 

770 from romfarmer.dat_parser.clonelist import clonelist_validate 

771 from romfarmer.dat_parser.parser import DATParser 

772 

773 parser = DATParser() 

774 console.print(f"\n[bold blue]Validating clone list:[/bold blue] {clonelist.name}") 

775 console.print(f"[bold blue]Against DAT:[/bold blue] {dat_file.name}\n") 

776 

777 dat = _parse_dat(parser, dat_file) 

778 result = clonelist_validate(clonelist, dat) 

779 

780 console.print(f" Total searchTerms: {result.total_search_terms}") 

781 console.print(f" Matched: {result.matched}") 

782 console.print(f" Match rate: {result.match_rate:.1%}\n") 

783 

784 if result.unmatched: 

785 table = Table(title=f"Unmatched ({len(result.unmatched)})", box=box.SIMPLE) 

786 table.add_column("Group", style="cyan") 

787 table.add_column("searchTerm", style="red") 

788 table.add_column("Suggestion", style="green") 

789 table.add_column("Sim", style="dim") 

790 for u in result.unmatched: 

791 table.add_row( 

792 u.group[:40], 

793 u.search_term, 

794 u.suggestion or "-", 

795 f"{u.similarity:.0%}" if u.suggestion else "", 

796 ) 

797 console.print(table) 

798 else: 

799 console.print("[green]All searchTerms matched![/green]") 

800 

801 console.print() 

802 

803 

804@dat_group.command(name="clonelist-patch") 

805@click.argument("clonelist", type=click.Path(exists=True, path_type=Path)) 

806@click.argument("old_dat", type=click.Path(exists=True, path_type=Path)) 

807@click.argument("new_dat", type=click.Path(exists=True, path_type=Path)) 

808@click.option( 

809 "--output", 

810 "-o", 

811 type=click.Path(path_type=Path), 

812 help="Output path (default: overwrite in place)", 

813) 

814@click.option("--dry-run", is_flag=True, default=False, help="Show patches without applying") 

815def patch_clonelist(clonelist, old_dat, new_dat, output, dry_run): 

816 """Auto-patch clone list searchTerms from DAT renames. 

817 

818 Diffs two DAT versions to find renames, then updates matching 

819 searchTerms in the clone list. Dry-run shows proposed changes 

820 without writing. 

821 

822 Examples: 

823 romfarmer dat clonelist-patch wii.json old.dat new.dat --dry-run 

824 romfarmer dat clonelist-patch wii.json old.dat new.dat -o patched.json 

825 """ 

826 from romfarmer.dat_parser.clonelist import clonelist_patch, dat_diff 

827 from romfarmer.dat_parser.parser import DATParser 

828 

829 parser = DATParser() 

830 console.print(f"\n[bold blue]Patching clone list:[/bold blue] {clonelist.name}") 

831 console.print(f" Old DAT: {old_dat.name}") 

832 console.print(f" New DAT: {new_dat.name}") 

833 if dry_run: 

834 console.print(" [yellow]DRY RUN — no files will be modified[/yellow]") 

835 console.print() 

836 

837 old_parsed = _parse_dat(parser, old_dat) 

838 new_parsed = _parse_dat(parser, new_dat) 

839 

840 diff_result = dat_diff(old_parsed, new_parsed) 

841 console.print(f" DAT diff: {len(diff_result.renames)} renames found\n") 

842 

843 if not diff_result.renames: 

844 console.print("[green]No renames to patch.[/green]\n") 

845 return 

846 

847 out_path = output if output else None 

848 result = clonelist_patch(clonelist, diff_result, output_path=out_path, dry_run=dry_run) 

849 

850 patches = result.patches_applied if not dry_run else result.patches_skipped 

851 if patches: 

852 table = Table(title=f"Patches ({'proposed' if dry_run else 'applied'})", box=box.SIMPLE) 

853 table.add_column("Group", style="cyan") 

854 table.add_column("Old", style="red") 

855 table.add_column("New", style="green") 

856 table.add_column("Reason", style="dim") 

857 for p in patches: 

858 table.add_row(p.group[:40], p.old_search_term, p.new_search_term, p.reason) 

859 console.print(table) 

860 else: 

861 console.print("[yellow]No matching searchTerms found for the renames.[/yellow]") 

862 

863 console.print() 

864 

865 

866@dat_group.command(name="metadata-generate") 

867@click.argument("dat_file", type=click.Path(exists=True, path_type=Path)) 

868@click.option("--output", "-o", type=click.Path(path_type=Path), help="Output JSON path") 

869def generate_metadata(dat_file, output): 

870 """Auto-generate Retool metadata JSON from DAT game names. 

871 

872 Extracts language codes from filenames (e.g., (En,Fr,De)) or infers 

873 from region tags (USA → En, Japan → Ja). Output is Retool-compatible JSON. 

874 

875 Examples: 

876 romfarmer dat metadata-generate redump-wii.dat -o wii-metadata.json 

877 """ 

878 import json as _json 

879 

880 from romfarmer.dat_parser.clonelist import metadata_generate, metadata_to_retool_json 

881 from romfarmer.dat_parser.parser import DATParser 

882 

883 parser = DATParser() 

884 console.print(f"\n[bold blue]Generating metadata from:[/bold blue] {dat_file.name}\n") 

885 

886 dat = _parse_dat(parser, dat_file) 

887 entries = metadata_generate(dat) 

888 retool_json = metadata_to_retool_json(entries) 

889 

890 with_langs = sum(1 for e in entries if e.languages) 

891 console.print(f" Total entries: {len(entries)}") 

892 console.print(f" With languages: {with_langs} ({with_langs * 100 // max(len(entries), 1)}%)") 

893 

894 if output: 

895 output.parent.mkdir(parents=True, exist_ok=True) 

896 with open(output, "w", encoding="utf-8") as f: 

897 _json.dump(retool_json, f, indent=2, ensure_ascii=False) 

898 f.write("\n") 

899 console.print(f"\n[green]Written to: {output}[/green]") 

900 else: 

901 # Show sample 

902 sample_keys = list(retool_json.keys())[:5] 

903 console.print("\n[bold]Sample:[/bold]") 

904 for key in sample_keys: 

905 console.print(f" {key}: {retool_json[key]}") 

906 console.print(" ...") 

907 

908 console.print() 

909 

910 

911# ── Shared helper ──────────────────────────────────────────────────────── 

912 

913 

914def _parse_dat(parser, path): 

915 """Parse a DAT file, handling ZIPs.""" 

916 if path.suffix.lower() == ".zip": 

917 import tempfile 

918 import zipfile 

919 

920 with tempfile.TemporaryDirectory() as tmpdir: 

921 with zipfile.ZipFile(path, "r") as zf: 

922 dat_files = [f for f in zf.namelist() if f.endswith(".dat")] 

923 if not dat_files: 

924 console.print(f"[red]No .dat file in {path.name}[/red]") 

925 raise SystemExit(1) 

926 zf.extract(dat_files[0], tmpdir) 

927 return parser.parse(Path(tmpdir) / dat_files[0]) 

928 return parser.parse(path)