Coverage for src/romfarmer/metadata/generator.py: 14%
207 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
1"""
2Gamelist.xml generator for EmulationStation.
4This module generates gamelist.xml files from the ROM Farmer metadata database,
5with support for media type filtering and smart file matching.
6"""
8import xml.etree.ElementTree as ET
9from dataclasses import dataclass
10from pathlib import Path
12from rich.console import Console
13from rich.progress import (
14 BarColumn,
15 Progress,
16 SpinnerColumn,
17 TaskProgressColumn,
18 TextColumn,
19)
21from ..core.hashing import calculate_md5, calculate_md5_with_auto_detect
22from .database import MediaType, MetadataDatabase, ScrapedGame
24console = Console()
27@dataclass
28class GenerationStats:
29 """Statistics from gamelist generation."""
31 roms_found: int = 0
32 roms_matched: int = 0
33 roms_unmatched: int = 0
34 media_links_created: int = 0
35 media_files_copied: int = 0
36 media_bytes_copied: int = 0
39class GamelistGenerator:
40 """
41 Generate EmulationStation gamelist.xml files.
43 This generator:
44 - Scans ROM directory for files
45 - Matches ROMs to database by hash
46 - Generates gamelist.xml with metadata
47 - Filters media types based on configuration
48 - Copies media files to output directory
49 - Creates relative paths for portability
50 """
52 def __init__(self, database: MetadataDatabase):
53 """
54 Initialize gamelist generator.
56 Args:
57 database: MetadataDatabase instance
58 """
59 self.database = database
61 def generate_gamelist(
62 self,
63 roms_dir: Path,
64 output_dir: Path,
65 media_types: list[str] | None = None,
66 copy_media: bool = True,
67 media_subdir: str = "media",
68 system_name: str | None = None,
69 ) -> GenerationStats:
70 """
71 Generate gamelist.xml for a ROM directory.
73 Args:
74 roms_dir: Directory containing ROM files
75 output_dir: Directory to write gamelist.xml and media
76 media_types: List of media types to include (None = all)
77 copy_media: Copy media files to output directory
78 media_subdir: Subdirectory name for media files
79 system_name: System name for filtering (optional)
81 Returns:
82 GenerationStats with generation results
83 """
84 console.print(f"[cyan]Generating gamelist for:[/cyan] {roms_dir}")
85 console.print(f"[cyan]Output directory:[/cyan] {output_dir}")
87 stats = GenerationStats()
89 # Resolve media types
90 media_types = self._resolve_media_types(media_types)
91 console.print(f"[cyan]Media types:[/cyan] {', '.join(media_types)}")
93 # Create output directory
94 output_dir.mkdir(parents=True, exist_ok=True)
95 media_output_dir = output_dir / media_subdir
97 # Scan ROM directory
98 rom_files = self._scan_rom_directory(roms_dir)
99 stats.roms_found = len(rom_files)
100 console.print(f"[cyan]Found {stats.roms_found} ROM files[/cyan]")
102 # Detect system from directory name if not provided
103 detected_system = system_name or roms_dir.name.lower()
104 console.print(f"[cyan]System:[/cyan] {detected_system}")
106 # Build gamelist XML
107 root = ET.Element("gameList")
109 with Progress(
110 SpinnerColumn(),
111 TextColumn("[progress.description]{task.description}"),
112 BarColumn(),
113 TaskProgressColumn(),
114 ) as progress:
115 task = progress.add_task("Matching ROMs...", total=len(rom_files))
117 for rom_file in rom_files:
118 # Special handling for .m3u playlist files
119 if rom_file.suffix.lower() == ".m3u":
120 game = self._match_m3u_playlist(rom_file, roms_dir)
121 else:
122 # Calculate hash using centralized hashing (system-aware)
123 md5_hash = calculate_md5(rom_file, detected_system)
124 game = self.database.find_game_by_hash(md5=md5_hash)
126 # If no direct match, try transformation lookup
127 if not game:
128 game = self._find_game_via_transformation(md5_hash)
130 if game:
131 stats.roms_matched += 1
133 # Add game to XML
134 game_elem = self._create_game_element(
135 game,
136 rom_file,
137 roms_dir,
138 media_types,
139 media_subdir,
140 )
141 root.append(game_elem)
143 # Copy media files
144 if copy_media:
145 media_copied = self._copy_game_media(
146 game,
147 media_types,
148 media_output_dir,
149 rom_file,
150 )
151 stats.media_links_created += len(media_copied)
152 stats.media_files_copied += len(set(media_copied.values()))
153 stats.media_bytes_copied += sum(
154 Path(p).stat().st_size
155 for p in set(media_copied.values())
156 if Path(p).exists()
157 )
158 else:
159 stats.roms_unmatched += 1
161 progress.update(task, advance=1)
163 # Write gamelist.xml
164 self._write_gamelist(root, output_dir / "gamelist.xml")
166 return stats
168 def _resolve_media_types(self, media_types: list[str] | None) -> list[str]:
169 """
170 Resolve media types configuration to list of types.
172 Handles special values:
173 - None or "all": All media types
174 - "minimal": Just mix
175 - "standard": Standard set
176 - "no-videos": All except videos
177 - "no-manuals": All except manuals
178 - List: Use as-is
179 - Dict with include/exclude: Apply filters
180 """
181 if media_types is None or media_types == "all":
182 return MediaType.all_types()
184 if media_types == "minimal":
185 return MediaType.minimal_types()
187 if media_types == "standard":
188 return MediaType.standard_types()
190 if media_types == "no-videos":
191 return [t for t in MediaType.all_types() if t != MediaType.VIDEO.value]
193 if media_types == "no-manuals":
194 return [t for t in MediaType.all_types() if t != MediaType.MANUAL.value]
196 if isinstance(media_types, dict):
197 # Handle include/exclude syntax
198 include = media_types.get("include", "all")
199 exclude = media_types.get("exclude", [])
201 if include == "all":
202 types = MediaType.all_types()
203 else:
204 types = include if isinstance(include, list) else [include]
206 # Remove excluded types
207 types = [t for t in types if t not in exclude]
208 return types
210 if isinstance(media_types, list):
211 return media_types
213 # Fallback to all
214 return MediaType.all_types()
216 def _scan_rom_directory(self, roms_dir: Path) -> list[Path]:
217 """Scan directory for ROM files."""
218 rom_extensions = {
219 # Cartridge ROMs
220 ".zip",
221 ".7z",
222 ".nes",
223 ".sfc",
224 ".smc",
225 ".gb",
226 ".gbc",
227 ".gba",
228 ".n64",
229 ".z64",
230 ".v64",
231 ".md",
232 ".smd",
233 ".gen",
234 ".sms",
235 ".gg",
236 ".pce",
237 ".ws",
238 ".wsc",
239 ".ngp",
240 ".ngc",
241 ".a26",
242 ".a52",
243 ".a78",
244 ".col",
245 ".vec",
246 ".lnx",
247 # Disc images
248 ".iso",
249 ".cue",
250 ".bin",
251 ".chd",
252 ".ccd",
253 ".mds",
254 ".img",
255 # Playlists
256 ".m3u",
257 }
259 rom_files = []
260 for file_path in roms_dir.rglob("*"):
261 if file_path.is_file() and file_path.suffix.lower() in rom_extensions:
262 rom_files.append(file_path)
264 return sorted(rom_files)
266 def _match_m3u_playlist(self, m3u_file: Path, roms_dir: Path) -> ScrapedGame | None:
267 """
268 Match .m3u playlist file to metadata by finding the first disc.
270 .m3u files are playlists that reference multiple disc images. They should
271 use the metadata from the first disc in the playlist.
273 Args:
274 m3u_file: Path to the .m3u file
275 roms_dir: Base ROM directory
277 Returns:
278 ScrapedGame from first disc, or None if not found
279 """
280 try:
281 # Read m3u file to get first disc reference
282 with open(m3u_file, encoding="utf-8") as f:
283 for line in f:
284 line = line.strip()
285 # Skip comments and empty lines
286 if not line or line.startswith("#"):
287 continue
289 # Found first disc reference
290 first_disc_name = line
291 first_disc_path = roms_dir / first_disc_name
293 if first_disc_path.exists():
294 # Calculate hash of first disc (using path-based system detection)
295 md5_hash = calculate_md5_with_auto_detect(first_disc_path)
296 game = self.database.find_game_by_hash(md5=md5_hash)
298 # Try transformation lookup if no direct match
299 if not game:
300 game = self._find_game_via_transformation(md5_hash)
302 return game
303 else:
304 console.print(
305 f"[yellow]⚠ First disc not found for {m3u_file.name}: {first_disc_name}[/yellow]"
306 )
307 return None
309 except Exception as e:
310 console.print(f"[yellow]⚠ Error reading {m3u_file.name}: {e}[/yellow]")
311 return None
313 return None
315 def _find_game_via_transformation(self, final_md5: str) -> ScrapedGame | None:
316 """
317 Find game by looking up transformation chain.
319 When a ROM has been transformed (e.g., CUE → CHD), the metadata is stored
320 with the original file's hash. This method looks up the transformation to
321 find the source hash, then matches that to the game.
323 Args:
324 final_md5: MD5 hash of the transformed file (e.g., CHD)
326 Returns:
327 ScrapedGame if found via transformation, None otherwise
328 """
329 from .transformation import ROMTransformation
331 # Get a session from the database
332 session = self.database.get_session()
334 # Look up transformation by final MD5
335 transformation = session.query(ROMTransformation).filter_by(final_md5=final_md5).first()
337 if transformation and transformation.source_md5:
338 # Found transformation, now look up game by source MD5
339 return self.database.find_game_by_hash(md5=transformation.source_md5)
341 return None
343 def _create_game_element(
344 self,
345 game: ScrapedGame,
346 rom_file: Path,
347 roms_dir: Path,
348 media_types: list[str],
349 media_subdir: str,
350 ) -> ET.Element:
351 """Create XML element for a game."""
352 game_elem = ET.Element("game")
354 if game.game_id:
355 game_elem.set("id", str(game.game_id))
357 # Add metadata fields in ARRM order
358 # Order: path, name, sortname, desc, rating, releasedate, developer, publisher,
359 # genre, genreid, players, md5, region, lang, [media elements]
360 self._add_text_element(game_elem, "path", f"./{rom_file.relative_to(roms_dir)}")
361 self._add_text_element(game_elem, "name", game.name)
362 self._add_text_element(game_elem, "sortname", game.sortname)
363 self._add_text_element(game_elem, "desc", game.description)
365 if game.rating is not None:
366 # Format rating to match ARRM (always 1 decimal place, e.g., 0.8 not 0.80)
367 self._add_text_element(game_elem, "rating", str(game.rating))
369 self._add_text_element(game_elem, "releasedate", game.release_date)
370 self._add_text_element(game_elem, "developer", game.developer)
371 self._add_text_element(game_elem, "publisher", game.publisher)
372 self._add_text_element(game_elem, "genre", game.genre)
374 if game.genre_id:
375 self._add_text_element(game_elem, "genreid", str(game.genre_id))
377 self._add_text_element(game_elem, "players", game.players)
378 self._add_text_element(game_elem, "md5", game.md5)
379 self._add_text_element(game_elem, "region", game.region)
380 self._add_text_element(game_elem, "lang", game.language)
382 # Add media elements (filtered by media_types)
383 # Use ARRM format: ./media/image/Game Name-image.png (singular folders, media type suffix)
384 # Process in ARRM order: image, wheel, boxart, screenshot, cartridge, mix, marquee, video, manual
385 arrm_media_order = [
386 "image",
387 "wheel",
388 "boxart",
389 "screenshot",
390 "cartridge",
391 "mix",
392 "marquee",
393 "video",
394 "manual",
395 ]
396 game_media = self.database.get_game_media(game, media_types)
398 for media_type in arrm_media_order:
399 if media_type not in game_media:
400 continue
402 media_file = game_media[media_type]
403 # Get filename from storage path
404 storage_path = Path(media_file.file_path)
405 filename = f"{rom_file.stem}-{media_type}{storage_path.suffix}"
406 relative_path = f"./{media_subdir}/{media_type}/{filename}"
408 self._add_text_element(game_elem, media_type, relative_path)
410 return game_elem
412 def _add_text_element(self, parent: ET.Element, tag: str, text: str | None) -> None:
413 """Add text element to parent if text is not None."""
414 if text is not None and text != "":
415 elem = ET.SubElement(parent, tag)
416 elem.text = str(text)
418 def _copy_game_media(
419 self,
420 game: ScrapedGame,
421 media_types: list[str],
422 media_output_dir: Path,
423 rom_file: Path,
424 ) -> dict[str, Path]:
425 """
426 Copy media files for a game to output directory.
428 Uses hardlinks when possible for disk efficiency (same filesystem),
429 falls back to copy for cross-filesystem situations.
431 Returns:
432 Dictionary mapping media type to output path
433 """
434 import os
435 import shutil
437 copied_media = {}
438 game_media = self.database.get_game_media(game, media_types)
440 for media_type, media_file in game_media.items():
441 # Create media type subdirectory
442 type_dir = media_output_dir / media_type
443 type_dir.mkdir(parents=True, exist_ok=True)
445 # Determine output filename (use rom_file stem to match XML paths)
446 storage_path = Path(media_file.file_path)
447 output_filename = f"{rom_file.stem}-{media_type}{storage_path.suffix}"
448 output_path = type_dir / output_filename
450 # Link or copy file if not already exists
451 if not output_path.exists():
452 try:
453 # Try hardlink first (fast, no disk usage)
454 os.link(storage_path, output_path)
455 except OSError:
456 # Fall back to copy if hardlink fails (cross-filesystem)
457 shutil.copy2(storage_path, output_path)
459 copied_media[media_type] = output_path
461 return copied_media
463 def _write_gamelist(self, root: ET.Element, output_path: Path) -> None:
464 """Write gamelist XML to file with pretty formatting."""
465 # Pretty print XML
466 self._indent_xml(root)
468 tree = ET.ElementTree(root)
469 tree.write(
470 output_path,
471 encoding="utf-8",
472 xml_declaration=True,
473 )
475 console.print(f"[green]✓ Gamelist written:[/green] {output_path}")
477 def _indent_xml(self, elem: ET.Element, level: int = 0) -> None:
478 """Add indentation to XML for pretty printing."""
479 indent = "\n" + " " * level
480 if len(elem):
481 if not elem.text or not elem.text.strip():
482 elem.text = indent + " "
483 if not elem.tail or not elem.tail.strip():
484 elem.tail = indent
485 for child in elem:
486 self._indent_xml(child, level + 1)
487 if not child.tail or not child.tail.strip():
488 child.tail = indent
489 else:
490 if level and (not elem.tail or not elem.tail.strip()):
491 elem.tail = indent
494def print_generation_stats(stats: GenerationStats) -> None:
495 """Print generation statistics in a nice format."""
496 from rich.panel import Panel
497 from rich.table import Table
499 # ROMs table
500 roms_table = Table(title="ROMs")
501 roms_table.add_column("Metric", style="cyan")
502 roms_table.add_column("Count", style="green", justify="right")
504 roms_table.add_row("Found", str(stats.roms_found))
505 roms_table.add_row("Matched", str(stats.roms_matched))
506 roms_table.add_row("Unmatched", str(stats.roms_unmatched))
508 match_rate = (stats.roms_matched / stats.roms_found * 100) if stats.roms_found > 0 else 0
509 roms_table.add_row("Match Rate", f"{match_rate:.1f}%")
511 console.print(roms_table)
513 # Media table
514 media_table = Table(title="Media")
515 media_table.add_column("Metric", style="cyan")
516 media_table.add_column("Count", style="green", justify="right")
518 media_table.add_row("Links Created", str(stats.media_links_created))
519 media_table.add_row("Files Copied", str(stats.media_files_copied))
521 if stats.media_bytes_copied > 0:
522 size_mb = stats.media_bytes_copied / (1024 * 1024)
523 media_table.add_row("Total Size", f"{size_mb:.1f} MB")
525 console.print(media_table)
527 # Success message
528 if stats.roms_matched > 0:
529 console.print(
530 Panel(
531 f"[green]✓ Generated gamelist for {stats.roms_matched} games[/green]",
532 title="Success",
533 )
534 )
535 else:
536 console.print(
537 Panel(
538 "[yellow]⚠ No games matched in database[/yellow]",
539 title="Warning",
540 )
541 )