Coverage for src/romfarmer/dat_parser/generator.py: 0%
221 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"""Generate Logiqx XML DAT files from source ROM directories.
3Scans a source directory of ROM files (ZIPs, ISOs, WUX, RVZ, etc.),
4collects metadata (filename, size, optionally hashes), and outputs a
5standard Logiqx XML DAT file.
7Can optionally enrich entries by fuzzy-matching against a reference DAT
8to borrow category, description, serial, and other metadata.
9"""
11import hashlib
12import os
13import re
14import xml.etree.ElementTree as ET
15import zipfile
16from concurrent.futures import ProcessPoolExecutor, as_completed
17from datetime import datetime
18from pathlib import Path
19from xml.dom import minidom
21from .models import DATFile, DATGame, DATRom
24def _normalize_name(name: str) -> str:
25 """Normalize a game name for fuzzy matching.
27 Strips file extension, removes common format suffixes,
28 normalizes whitespace and punctuation.
29 """
30 # Remove file extension
31 stem = Path(name).stem
33 # Lowercase for comparison
34 s = stem.lower()
36 # Remove common parenthetical tags that vary between sources
37 # Keep region/language tags for matching accuracy
38 s = re.sub(r"\s*\(rev\s*\d+\)", "", s)
40 # Normalize punctuation
41 s = re.sub(r"[&]", "and", s)
42 s = re.sub(r"[^\w\s()-]", "", s)
44 # Collapse whitespace
45 s = re.sub(r"\s+", " ", s).strip()
47 return s
50def _normalize_aggressive(name: str) -> str:
51 """More aggressive normalization for fallback matching.
53 Strips all spaces and punctuation for cases like
54 'ZhuZhu' vs 'Zhu Zhu', 'LEGO' vs 'Lego', etc.
55 """
56 s = _normalize_name(name)
57 # Remove all spaces and non-alphanumeric (except parens for regions)
58 s = re.sub(r"[\s\-_]", "", s)
59 return s
62def _build_reference_index(ref_dat: DATFile) -> tuple[dict[str, DATGame], dict[str, DATGame]]:
63 """Build normalized-name → DATGame lookups from a reference DAT.
65 Returns a tuple of (exact_index, aggressive_index) where:
66 - exact_index maps standard-normalized names to DATGame entries
67 - aggressive_index maps aggressively-normalized names (no spaces) for fallback
68 """
69 exact: dict[str, DATGame] = {}
70 aggressive: dict[str, DATGame] = {}
72 for game in ref_dat.games:
73 # Index by game name
74 norm = _normalize_name(game.name)
75 if norm not in exact:
76 exact[norm] = game
78 agg = _normalize_aggressive(game.name)
79 if agg not in aggressive:
80 aggressive[agg] = game
82 # Also index by description if different
83 if game.description and game.description != game.name:
84 desc_norm = _normalize_name(game.description)
85 if desc_norm not in exact:
86 exact[desc_norm] = game
87 desc_agg = _normalize_aggressive(game.description)
88 if desc_agg not in aggressive:
89 aggressive[desc_agg] = game
91 return exact, aggressive
94def _match_reference(
95 name: str,
96 ref_exact: dict[str, DATGame],
97 ref_aggressive: dict[str, DATGame],
98) -> DATGame | None:
99 """Try to find a matching game in the reference indices.
101 Attempts exact normalized match first, then aggressive (no-space)
102 match, then progressively looser matches.
103 """
104 norm = _normalize_name(name)
106 # Exact normalized match
107 if norm in ref_exact:
108 return ref_exact[norm]
110 # Aggressive match (handles ZhuZhu vs Zhu Zhu, etc.)
111 agg = _normalize_aggressive(name)
112 if agg in ref_aggressive:
113 return ref_aggressive[agg]
115 # Try without region/language tags entirely
116 no_parens = re.sub(r"\s*\([^)]*\)", "", norm).strip()
117 for ref_norm, game in ref_exact.items():
118 ref_no_parens = re.sub(r"\s*\([^)]*\)", "", ref_norm).strip()
119 if no_parens and no_parens == ref_no_parens:
120 return game
122 return None
125def scan_source_directory(
126 source_dir: Path,
127 *,
128 compute_hashes: bool = False,
129 hash_zip_contents: bool = False,
130 crc_from_zip: bool = False,
131 recursive: bool = False,
132 extensions: set[str] | None = None,
133 progress_callback=None,
134 workers: int | None = None,
135) -> list[DATGame]:
136 """Scan a source directory and build DATGame entries.
138 Args:
139 source_dir: Directory containing ROM files
140 compute_hashes: Whether to compute MD5/SHA1/CRC for outer files
141 hash_zip_contents: Whether to open ZIPs and hash inner files
142 crc_from_zip: Whether to extract CRC32 from ZIP central directory
143 (instant, no file I/O needed beyond reading the header)
144 recursive: Whether to scan subdirectories
145 extensions: File extensions to include (default: common ROM formats)
146 progress_callback: Called with (current, total, filename) for progress
147 workers: Number of parallel workers (default: CPU count)
149 Returns:
150 List of DATGame entries with ROM metadata
151 """
152 if extensions is None:
153 extensions = {
154 ".zip",
155 ".7z",
156 ".rvz",
157 ".wux",
158 ".iso",
159 ".wad",
160 ".nsp",
161 ".xci",
162 ".chd",
163 ".cso",
164 ".pbp",
165 ".pkg",
166 }
168 # Collect files
169 if recursive:
170 files = sorted(
171 f for f in source_dir.rglob("*") if f.is_file() and f.suffix.lower() in extensions
172 )
173 else:
174 files = sorted(
175 f for f in source_dir.iterdir() if f.is_file() and f.suffix.lower() in extensions
176 )
178 total = len(files)
180 # Use parallel processing when hashing is involved and we have many files
181 use_parallel = (compute_hashes or hash_zip_contents) and total > 1
182 if workers is None:
183 workers = min(os.cpu_count() or 1, total)
185 if use_parallel and workers > 1:
186 return _scan_parallel(
187 files,
188 total,
189 compute_hashes=compute_hashes,
190 hash_zip_contents=hash_zip_contents,
191 crc_from_zip=crc_from_zip,
192 workers=workers,
193 progress_callback=progress_callback,
194 )
196 # Serial fallback (fast operations like crc_from_zip, or small file counts)
197 games: list[DATGame] = []
198 for i, file_path in enumerate(files):
199 if progress_callback:
200 progress_callback(i + 1, total, file_path.name)
202 game = _scan_file(
203 file_path,
204 compute_hashes=compute_hashes,
205 hash_zip_contents=hash_zip_contents,
206 crc_from_zip=crc_from_zip,
207 )
208 if game:
209 games.append(game)
211 return games
214def _scan_file_worker(args: tuple) -> DATGame | None:
215 """Worker function for parallel scanning (must be top-level for pickling)."""
216 file_path, compute_hashes, hash_zip_contents, crc_from_zip = args
217 return _scan_file(
218 Path(file_path),
219 compute_hashes=compute_hashes,
220 hash_zip_contents=hash_zip_contents,
221 crc_from_zip=crc_from_zip,
222 )
225def _scan_parallel(
226 files: list[Path],
227 total: int,
228 *,
229 compute_hashes: bool,
230 hash_zip_contents: bool,
231 crc_from_zip: bool,
232 workers: int,
233 progress_callback=None,
234) -> list[DATGame]:
235 """Scan files in parallel using a process pool."""
236 # Prepare args as tuples (Path objects need to be passed as strings for pickling)
237 work_items = [(str(f), compute_hashes, hash_zip_contents, crc_from_zip) for f in files]
239 # Map file paths to original index for sorted output
240 results: list[DATGame | None] = [None] * total
241 completed = 0
243 with ProcessPoolExecutor(max_workers=workers) as executor:
244 future_to_idx = {
245 executor.submit(_scan_file_worker, item): i for i, item in enumerate(work_items)
246 }
248 for future in as_completed(future_to_idx):
249 idx = future_to_idx[future]
250 completed += 1
251 try:
252 results[idx] = future.result()
253 except Exception:
254 results[idx] = None
256 if progress_callback:
257 progress_callback(completed, total, files[idx].name)
259 return [g for g in results if g is not None]
262def _scan_file(
263 file_path: Path,
264 *,
265 compute_hashes: bool = False,
266 hash_zip_contents: bool = False,
267 crc_from_zip: bool = False,
268) -> DATGame | None:
269 """Scan a single file and create a DATGame entry.
271 For ZIP files, records the outer ZIP as a single ROM entry
272 (matching how Myrient distributes files). If hash_zip_contents
273 is True, also records inner file metadata.
274 If crc_from_zip is True, extracts CRC32 from the ZIP central
275 directory (no file data reading needed).
276 """
277 try:
278 stat = file_path.stat()
279 except OSError:
280 return None
282 game_name = file_path.stem # Strip extension for game name
283 outer_size = stat.st_size
285 # Compute hashes of the outer file if requested
286 md5 = None
287 sha1 = None
288 crc = None
290 if compute_hashes:
291 md5, sha1, crc = _compute_hashes(file_path)
293 # For ZIP files, extract CRC from central directory (free operation)
294 zip_inner_crc = None
295 if crc_from_zip and not compute_hashes and file_path.suffix.lower() == ".zip":
296 try:
297 with zipfile.ZipFile(file_path, "r") as zf:
298 # Get the largest inner file's CRC (the actual ROM)
299 entries = [i for i in zf.infolist() if not i.is_dir()]
300 if entries:
301 biggest = max(entries, key=lambda x: x.file_size)
302 zip_inner_crc = format(biggest.CRC, "08x")
303 except (zipfile.BadZipFile, OSError):
304 pass
306 # For ZIP files, try to get inner file info
307 inner_roms: list[DATRom] = []
308 if hash_zip_contents and file_path.suffix.lower() == ".zip":
309 inner_roms = _scan_zip_contents(file_path, compute_hashes=compute_hashes)
311 if inner_roms:
312 # Use inner ROM entries (more useful for matching)
313 return DATGame(
314 name=game_name,
315 roms=inner_roms,
316 description=game_name,
317 category="Games",
318 )
319 else:
320 # Single ROM entry for the outer file
321 rom = DATRom(
322 name=file_path.name,
323 size=outer_size,
324 md5=md5,
325 sha1=sha1,
326 crc=crc or zip_inner_crc,
327 )
328 return DATGame(
329 name=game_name,
330 roms=[rom],
331 description=game_name,
332 category="Games",
333 )
336def _scan_zip_contents(
337 zip_path: Path,
338 *,
339 compute_hashes: bool = False,
340) -> list[DATRom]:
341 """Scan contents of a ZIP file and return ROM entries for inner files."""
342 roms: list[DATRom] = []
343 try:
344 with zipfile.ZipFile(zip_path, "r") as zf:
345 for info in zf.infolist():
346 if info.is_dir():
347 continue
349 crc_hex = format(info.CRC, "08x") if info.CRC else None
351 md5 = None
352 sha1 = None
353 if compute_hashes:
354 data = zf.read(info.filename)
355 md5 = hashlib.md5(data).hexdigest()
356 sha1 = hashlib.sha1(data).hexdigest()
358 roms.append(
359 DATRom(
360 name=info.filename,
361 size=info.file_size,
362 crc=crc_hex,
363 md5=md5,
364 sha1=sha1,
365 )
366 )
367 except (zipfile.BadZipFile, OSError):
368 pass
370 return roms
373def _compute_hashes(file_path: Path) -> tuple[str, str, str]:
374 """Compute MD5, SHA1, and CRC32 of a file."""
375 import zlib
377 md5 = hashlib.md5()
378 sha1 = hashlib.sha1()
379 crc = 0
381 with open(file_path, "rb") as f:
382 while chunk := f.read(1024 * 1024): # 1MB chunks
383 md5.update(chunk)
384 sha1.update(chunk)
385 crc = zlib.crc32(chunk, crc)
387 crc_hex = format(crc & 0xFFFFFFFF, "08x")
388 return md5.hexdigest(), sha1.hexdigest(), crc_hex
391def enrich_from_reference(
392 games: list[DATGame],
393 ref_dat: DATFile,
394 *,
395 progress_callback=None,
396) -> tuple[int, int]:
397 """Enrich game entries with metadata from a reference DAT.
399 Fuzzy-matches game names and copies over category, description,
400 year, manufacturer, and other metadata from the reference.
402 Args:
403 games: Games to enrich (modified in place)
404 ref_dat: Reference DAT to pull metadata from
405 progress_callback: Called with (matched, total)
407 Returns:
408 Tuple of (matched_count, total_count)
409 """
410 ref_exact, ref_aggressive = _build_reference_index(ref_dat)
411 matched = 0
412 total = len(games)
414 for game in games:
415 ref_game = _match_reference(game.name, ref_exact, ref_aggressive)
416 if ref_game:
417 matched += 1
418 # Borrow metadata but keep our ROM entries (our hashes/sizes)
419 if ref_game.category:
420 game.category = ref_game.category
421 if ref_game.description:
422 game.description = ref_game.description
423 if ref_game.year:
424 game.year = ref_game.year
425 if ref_game.manufacturer:
426 game.manufacturer = ref_game.manufacturer
427 if ref_game.cloneof:
428 game.cloneof = ref_game.cloneof
429 if ref_game.region:
430 game.region = ref_game.region
432 if progress_callback:
433 progress_callback(matched, total)
435 return matched, total
438def write_dat_xml(
439 games: list[DATGame],
440 output_path: Path,
441 *,
442 dat_name: str,
443 description: str | None = None,
444 version: str | None = None,
445 author: str = "rom-farmer (generated)",
446 homepage: str = "https://github.com/rom-farmer",
447) -> Path:
448 """Write games to a Logiqx XML DAT file.
450 Args:
451 games: Game entries to write
452 output_path: Output .dat file path
453 dat_name: Name for the DAT header
454 description: Description (defaults to name + game count)
455 version: Version string (defaults to current timestamp)
456 author: Author string
457 homepage: Homepage URL
459 Returns:
460 Path to the written file
461 """
462 if version is None:
463 version = datetime.now().strftime("%Y-%m-%d %H-%M-%S")
465 if description is None:
466 description = f"{dat_name} ({len(games)}) ({version})"
468 # Build XML
469 root = ET.Element("datafile")
471 # Header
472 header = ET.SubElement(root, "header")
473 ET.SubElement(header, "name").text = dat_name
474 ET.SubElement(header, "description").text = description
475 ET.SubElement(header, "version").text = version
476 ET.SubElement(header, "author").text = author
477 ET.SubElement(header, "homepage").text = homepage
478 ET.SubElement(header, "url").text = homepage
480 # Games
481 for game in sorted(games, key=lambda g: g.name.lower()):
482 game_elem = ET.SubElement(root, "game", name=game.name)
484 if game.category:
485 ET.SubElement(game_elem, "category").text = game.category
486 ET.SubElement(game_elem, "description").text = game.description or game.name
488 if game.year:
489 ET.SubElement(game_elem, "year").text = game.year
490 if game.manufacturer:
491 ET.SubElement(game_elem, "manufacturer").text = game.manufacturer
492 if game.cloneof:
493 game_elem.set("cloneof", game.cloneof)
495 for rom in game.roms:
496 rom_attrs = {
497 "name": rom.name,
498 "size": str(rom.size),
499 }
500 if rom.crc:
501 rom_attrs["crc"] = rom.crc
502 if rom.md5:
503 rom_attrs["md5"] = rom.md5
504 if rom.sha1:
505 rom_attrs["sha1"] = rom.sha1
506 if rom.sha256:
507 rom_attrs["sha256"] = rom.sha256
509 ET.SubElement(game_elem, "rom", **rom_attrs)
511 # Write with pretty-printing
512 xml_str = ET.tostring(root, encoding="unicode")
513 pretty = minidom.parseString(xml_str).toprettyxml(indent="\t", encoding=None)
515 # Remove extra XML declaration that minidom adds (we add our own)
516 lines = pretty.split("\n")
517 if lines[0].startswith("<?xml"):
518 lines = lines[1:]
519 content = "\n".join(lines)
521 # Write with proper XML declaration and DOCTYPE
522 output_path.parent.mkdir(parents=True, exist_ok=True)
523 with open(output_path, "w", encoding="utf-8") as f:
524 f.write('<?xml version="1.0"?>\n')
525 f.write(
526 '<!DOCTYPE datafile PUBLIC "-//Logiqx//DTD ROM Management Datafile//EN" '
527 '"http://www.logiqx.com/Dats/datafile.dtd">\n'
528 )
529 f.write(content)
531 return output_path