Coverage for src/romfarmer/dat_parser/clonelist.py: 0%

234 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-03 11:31 -0700

1"""Clone list maintenance engine for Retool-format clone lists. 

2 

3Provides three core capabilities: 

41. dat_diff: Compare two DAT versions by hash to detect renames/adds/removes 

52. clonelist_validate: Check all searchTerms against a DAT for broken references 

63. clonelist_patch: Auto-fix clone list searchTerms from a rename manifest 

7 

8Operates on Retool's JSON format: 

9{ 

10 "description": {"name": "...", "lastUpdated": "...", "minimumVersion": "..."}, 

11 "variants": [ 

12 {"group": "Game Title", "titles": [{"searchTerm": "Regional Name"}, ...]} 

13 ] 

14} 

15""" 

16 

17import json 

18import re 

19from dataclasses import dataclass, field 

20from datetime import datetime 

21from pathlib import Path 

22 

23from .models import DATFile 

24 

25# ── Data classes ────────────────────────────────────────────────────────── 

26 

27 

28@dataclass 

29class DATRename: 

30 """A game renamed between two DAT versions, tracked by hash.""" 

31 

32 old_name: str 

33 new_name: str 

34 sha1: str | None = None 

35 md5: str | None = None 

36 crc: str | None = None 

37 

38 

39@dataclass 

40class DATDiffResult: 

41 """Result of comparing two DAT versions.""" 

42 

43 old_dat_name: str 

44 new_dat_name: str 

45 old_count: int 

46 new_count: int 

47 renames: list[DATRename] = field(default_factory=list) 

48 additions: list[str] = field(default_factory=list) 

49 removals: list[str] = field(default_factory=list) 

50 

51 @property 

52 def has_changes(self) -> bool: 

53 return bool(self.renames or self.additions or self.removals) 

54 

55 

56@dataclass 

57class ValidationIssue: 

58 """A clone list searchTerm that doesn't match any DAT entry.""" 

59 

60 group: str 

61 search_term: str 

62 suggestion: str | None = None # Best fuzzy match if found 

63 similarity: float = 0.0 

64 

65 

66@dataclass 

67class ValidationResult: 

68 """Result of validating a clone list against a DAT.""" 

69 

70 clonelist_name: str 

71 dat_name: str 

72 total_search_terms: int 

73 matched: int 

74 unmatched: list[ValidationIssue] = field(default_factory=list) 

75 

76 @property 

77 def match_rate(self) -> float: 

78 return self.matched / self.total_search_terms if self.total_search_terms else 0.0 

79 

80 

81@dataclass 

82class PatchAction: 

83 """A single searchTerm replacement in a clone list.""" 

84 

85 group: str 

86 old_search_term: str 

87 new_search_term: str 

88 reason: str # e.g., "renamed in DAT", "region change", "title correction" 

89 

90 

91@dataclass 

92class PatchResult: 

93 """Result of patching a clone list.""" 

94 

95 clonelist_name: str 

96 patches_applied: list[PatchAction] = field(default_factory=list) 

97 patches_skipped: list[PatchAction] = field(default_factory=list) 

98 

99 

100@dataclass 

101class MetadataEntry: 

102 """Auto-generated metadata for a game title.""" 

103 

104 title: str 

105 languages: list[str] = field(default_factory=list) 

106 local_name: str | None = None 

107 

108 

109# ── Region → Language mapping ───────────────────────────────────────────── 

110 

111REGION_LANGUAGE_MAP = { 

112 "Japan": ["Ja"], 

113 "USA": ["En"], 

114 "Europe": ["En"], 

115 "Korea": ["Ko"], 

116 "Germany": ["De"], 

117 "France": ["Fr"], 

118 "Spain": ["Es"], 

119 "Italy": ["It"], 

120 "Netherlands": ["Nl"], 

121 "Sweden": ["Sv"], 

122 "Norway": ["No"], 

123 "Denmark": ["Da"], 

124 "Finland": ["Fi"], 

125 "Poland": ["Pl"], 

126 "Russia": ["Ru"], 

127 "China": ["Zh"], 

128 "Taiwan": ["Zh"], 

129 "Brazil": ["Pt"], 

130 "Portugal": ["Pt"], 

131 "Australia": ["En"], 

132 "World": ["En"], 

133 "Asia": [], # Ambiguous 

134} 

135 

136# ISO 639-1 codes used in DAT filenames 

137_LANG_CODES = ( 

138 "En|Fr|De|Es|It|Nl|Pt|Sv|No|Da|Fi|Pl|Ru|Zh|Ko|Ja|Ro|Hu|Cs|Tr|El|Ar|He|Th|" 

139 "Vi|Uk|Hr|Sk|Bg|Lt|Lv|Et|Sl|Sr|Mk|Sq|Bs|Ca|Gl|Eu|Cy|Ga" 

140) 

141_LANG_RE = re.compile(rf"\(((?:{_LANG_CODES})(?:,(?:{_LANG_CODES}))*)\)") 

142_REGION_RE = re.compile(r"\((" + "|".join(re.escape(r) for r in REGION_LANGUAGE_MAP) + r")") 

143 

144 

145# ── Core functions ──────────────────────────────────────────────────────── 

146 

147 

148def dat_diff(old_dat: DATFile, new_dat: DATFile) -> DATDiffResult: 

149 """Compare two DATs by hash to detect renames, additions, and removals. 

150 

151 Uses SHA1 > MD5 > CRC as the hash key, falling back through the chain. 

152 Games with matching hashes but different names are renames. 

153 """ 

154 old_by_hash = _build_hash_index(old_dat) 

155 new_by_hash = _build_hash_index(new_dat) 

156 

157 result = DATDiffResult( 

158 old_dat_name=old_dat.name or "old", 

159 new_dat_name=new_dat.name or "new", 

160 old_count=len(old_dat.games), 

161 new_count=len(new_dat.games), 

162 ) 

163 

164 old_hashes = set(old_by_hash.keys()) 

165 new_hashes = set(new_by_hash.keys()) 

166 

167 # Renames: same hash, different name 

168 for h in old_hashes & new_hashes: 

169 old_name = old_by_hash[h] 

170 new_name = new_by_hash[h] 

171 if old_name != new_name: 

172 hash_type, hash_val = h 

173 rename = DATRename(old_name=old_name, new_name=new_name) 

174 if hash_type == "sha1": 

175 rename.sha1 = hash_val 

176 elif hash_type == "md5": 

177 rename.md5 = hash_val 

178 elif hash_type == "crc": 

179 rename.crc = hash_val 

180 result.renames.append(rename) 

181 

182 # Additions: hash only in new 

183 for h in new_hashes - old_hashes: 

184 result.additions.append(new_by_hash[h]) 

185 

186 # Removals: hash only in old 

187 for h in old_hashes - new_hashes: 

188 result.removals.append(old_by_hash[h]) 

189 

190 # Sort for deterministic output 

191 result.renames.sort(key=lambda r: r.old_name) 

192 result.additions.sort() 

193 result.removals.sort() 

194 

195 return result 

196 

197 

198def clonelist_validate( 

199 clonelist_path: Path, 

200 dat: DATFile, 

201) -> ValidationResult: 

202 """Validate all searchTerms in a clone list against a DAT. 

203 

204 A searchTerm matches if any game name in the DAT starts with it 

205 (Retool uses substring/prefix matching on the base name portion). 

206 """ 

207 data = _load_clonelist(clonelist_path) 

208 dat_names = _extract_base_names(dat) 

209 

210 result = ValidationResult( 

211 clonelist_name=data.get("description", {}).get("name", clonelist_path.stem), 

212 dat_name=dat.name or "unknown", 

213 total_search_terms=0, 

214 matched=0, 

215 ) 

216 

217 for variant in data.get("variants", []): 

218 group = variant.get("group", "") 

219 for title in variant.get("titles", []): 

220 search_term = title.get("searchTerm", "") 

221 if not search_term: 

222 continue 

223 

224 result.total_search_terms += 1 

225 

226 if _search_term_matches(search_term, dat_names): 

227 result.matched += 1 

228 else: 

229 # Try fuzzy suggestion 

230 suggestion, sim = _find_closest_match(search_term, dat_names) 

231 result.unmatched.append( 

232 ValidationIssue( 

233 group=group, 

234 search_term=search_term, 

235 suggestion=suggestion, 

236 similarity=sim, 

237 ) 

238 ) 

239 

240 return result 

241 

242 

243def clonelist_patch( 

244 clonelist_path: Path, 

245 diff_result: DATDiffResult, 

246 output_path: Path | None = None, 

247 dry_run: bool = False, 

248) -> PatchResult: 

249 """Patch clone list searchTerms based on a DAT diff rename manifest. 

250 

251 For each rename in the diff, find matching searchTerms and update them. 

252 Writes the patched JSON to output_path (or overwrites in place if None). 

253 """ 

254 data = _load_clonelist(clonelist_path) 

255 cl_name = data.get("description", {}).get("name", clonelist_path.stem) 

256 result = PatchResult(clonelist_name=cl_name) 

257 

258 # Build rename lookup: old_base_name → (new_base_name, DATRename) 

259 rename_map = {} 

260 for rename in diff_result.renames: 

261 old_base = _strip_tags(rename.old_name) 

262 new_base = _strip_tags(rename.new_name) 

263 if old_base != new_base: 

264 rename_map[old_base.lower()] = (new_base, rename) 

265 

266 if not rename_map: 

267 return result 

268 

269 # Scan and patch 

270 for variant in data.get("variants", []): 

271 group = variant.get("group", "") 

272 for title in variant.get("titles", []): 

273 search_term = title.get("searchTerm", "") 

274 if not search_term: 

275 continue 

276 

277 key = search_term.lower() 

278 if key in rename_map: 

279 new_term, rename = rename_map[key] 

280 action = PatchAction( 

281 group=group, 

282 old_search_term=search_term, 

283 new_search_term=new_term, 

284 reason=_classify_rename(rename.old_name, rename.new_name), 

285 ) 

286 

287 if not dry_run: 

288 title["searchTerm"] = new_term 

289 result.patches_applied.append(action) 

290 else: 

291 result.patches_skipped.append(action) 

292 

293 # Update metadata 

294 if not dry_run and result.patches_applied: 

295 if "description" in data: 

296 data["description"]["lastUpdated"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S") 

297 

298 dest = output_path or clonelist_path 

299 _save_clonelist(dest, data) 

300 

301 return result 

302 

303 

304def metadata_generate(dat: DATFile) -> list[MetadataEntry]: 

305 """Auto-generate Retool-format metadata from DAT game names. 

306 

307 Extracts language codes from filename tags (En,Fr,De,...) or infers 

308 from region tags (USA → En, Japan → Ja, etc.). 

309 """ 

310 entries = [] 

311 

312 for game in dat.games: 

313 name = game.name 

314 languages = _parse_languages(name) 

315 entries.append(MetadataEntry(title=name, languages=languages)) 

316 

317 return entries 

318 

319 

320def metadata_to_retool_json(entries: list[MetadataEntry]) -> dict: 

321 """Convert metadata entries to Retool's JSON format. 

322 

323 Returns a dict keyed by title, each value containing {languages: [...]}. 

324 """ 

325 result = {} 

326 for entry in entries: 

327 val: dict = {} 

328 if entry.languages: 

329 val["languages"] = entry.languages 

330 if entry.local_name: 

331 val["localName"] = entry.local_name 

332 result[entry.title] = val 

333 return result 

334 

335 

336# ── Helper functions ────────────────────────────────────────────────────── 

337 

338 

339def _build_hash_index(dat: DATFile) -> dict[tuple[str, str], str]: 

340 """Build (hash_type, hash_value) → game_name index. 

341 

342 Prefers SHA1 > MD5 > CRC for maximum uniqueness. 

343 """ 

344 index = {} 

345 for game in dat.games: 

346 rom = game.get_primary_rom() 

347 if not rom: 

348 continue 

349 

350 # Use best available hash 

351 if rom.sha1: 

352 index[("sha1", rom.sha1)] = game.name 

353 elif rom.md5: 

354 index[("md5", rom.md5)] = game.name 

355 elif rom.crc: 

356 index[("crc", rom.crc)] = game.name 

357 

358 return index 

359 

360 

361def _extract_base_names(dat: DATFile) -> set[str]: 

362 """Extract base game names (without region/language tags) from a DAT.""" 

363 names = set() 

364 for game in dat.games: 

365 names.add(game.name) 

366 # Also add stripped version for matching 

367 base = _strip_tags(game.name) 

368 names.add(base) 

369 return names 

370 

371 

372def _strip_tags(name: str) -> str: 

373 """Strip region/language/revision parenthetical tags from a game name. 

374 

375 'Super Mario Galaxy (USA) (Rev 1)' → 'Super Mario Galaxy' 

376 """ 

377 # Remove all parenthetical groups 

378 result = re.sub(r"\s*\([^)]*\)", "", name).strip() 

379 return result 

380 

381 

382def _search_term_matches(search_term: str, dat_names: set[str]) -> bool: 

383 """Check if a searchTerm matches any DAT name. 

384 

385 Retool matches searchTerms as prefixes of the base name portion. 

386 'Super Mario Galaxy' matches 'Super Mario Galaxy (USA) (En,Fr)'. 

387 """ 

388 st_lower = search_term.lower() 

389 for name in dat_names: 

390 if name.lower() == st_lower: 

391 return True 

392 # Check if DAT name starts with the searchTerm (before first parenthetical) 

393 base = _strip_tags(name).lower() 

394 if base == st_lower: 

395 return True 

396 return False 

397 

398 

399def _find_closest_match( 

400 search_term: str, dat_names: set[str], threshold: float = 0.6 

401) -> tuple[str | None, float]: 

402 """Find the closest matching game name for a broken searchTerm. 

403 

404 Uses simple token overlap similarity (fast, no extra deps). 

405 Returns (best_match, similarity) or (None, 0.0). 

406 """ 

407 st_tokens = set(search_term.lower().split()) 

408 best_match = None 

409 best_sim = 0.0 

410 

411 for name in dat_names: 

412 base = _strip_tags(name) 

413 name_tokens = set(base.lower().split()) 

414 if not name_tokens: 

415 continue 

416 

417 # Jaccard similarity 

418 intersection = st_tokens & name_tokens 

419 union = st_tokens | name_tokens 

420 sim = len(intersection) / len(union) if union else 0.0 

421 

422 if sim > best_sim: 

423 best_sim = sim 

424 best_match = base 

425 

426 if best_sim >= threshold: 

427 return best_match, best_sim 

428 return None, 0.0 

429 

430 

431def _classify_rename(old_name: str, new_name: str) -> str: 

432 """Classify the type of rename for human-readable reporting.""" 

433 old_base = _strip_tags(old_name) 

434 new_base = _strip_tags(new_name) 

435 

436 if old_base.lower() == new_base.lower(): 

437 # Only tag changes (region, language, etc.) 

438 return "tag update" 

439 

440 # Check for capitalization-only changes 

441 if old_base.lower().replace(" ", "") == new_base.lower().replace(" ", ""): 

442 return "capitalization fix" 

443 

444 # Check for punctuation-only changes (hyphens, spaces, etc.) 

445 old_alpha = re.sub(r"[^a-zA-Z0-9]", "", old_base.lower()) 

446 new_alpha = re.sub(r"[^a-zA-Z0-9]", "", new_base.lower()) 

447 if old_alpha == new_alpha: 

448 return "punctuation fix" 

449 

450 # Check if multi-title was split ('Game A ~ Game B' → 'Game A') 

451 if "~" in old_name and "~" not in new_name: 

452 return "multi-title split" 

453 

454 return "title correction" 

455 

456 

457def _parse_languages(name: str) -> list[str]: 

458 """Extract language codes from a game name. 

459 

460 Tries explicit language tags first (En,Fr,De,...), then falls back 

461 to region → language mapping. 

462 """ 

463 # Try explicit language tags 

464 match = _LANG_RE.search(name) 

465 if match: 

466 return match.group(1).split(",") 

467 

468 # Fall back to region mapping 

469 region_match = _REGION_RE.search(name) 

470 if region_match: 

471 region = region_match.group(1) 

472 return list(REGION_LANGUAGE_MAP.get(region, [])) 

473 

474 return [] 

475 

476 

477def _load_clonelist(path: Path) -> dict: 

478 """Load a Retool clone list JSON file.""" 

479 with open(path, encoding="utf-8") as f: 

480 return json.load(f) 

481 

482 

483def _save_clonelist(path: Path, data: dict) -> None: 

484 """Save a Retool clone list JSON file with consistent formatting.""" 

485 path.parent.mkdir(parents=True, exist_ok=True) 

486 with open(path, "w", encoding="utf-8") as f: 

487 json.dump(data, f, indent=2, ensure_ascii=False) 

488 f.write("\n")