Coverage for src/romfarmer/targets/profiles/loader.py: 83%

139 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-05 02:19 -0700

1"""TargetProfile loader — reads config/frontends/*.yaml + config/devices/*.yaml. 

2 

3The YAML schema is **unchanged** from the legacy config — zero user migration. 

4A ``ConcreteTargetProfile`` combines one frontend definition with one optional 

5device definition (device adds unsupported-platform gates and media-sizing caps). 

6 

7Relationships: 

8 frontend — emulator front-end (Batocera, RocknIX, RetroArch, …) 

9 device — hardware target (r36s, steamdeck, pc, …) 

10 

11Phase 5 also wires ``format_preferences`` into ``negotiation.py`` — the 

12``preferred_compression`` field from frontend platform definitions is read here 

13and stored as a tuple of ``FormatChain`` for the negotiation pass. 

14""" 

15 

16from __future__ import annotations 

17 

18import logging 

19from dataclasses import dataclass, field 

20from pathlib import Path 

21from typing import Any 

22 

23from romfarmer.ir.catalog import PlatformId 

24from romfarmer.ir.chain import FormatChain 

25from romfarmer.ir.layout import LayoutConstraints, MediaPolicy, MetadataDialect, PlatformCapability 

26 

27logger = logging.getLogger(__name__) 

28 

29 

30class TargetProfileError(RuntimeError): 

31 """A frontend/device profile is missing or unparseable. 

32 

33 Raised instead of returning an empty profile: an empty profile silently 

34 disables metadata and format negotiation for the whole build (review 

35 G4 #6 — bug-5 class re-entering through the back door). 

36 """ 

37 

38 

39# Compression label → FormatChain mapping (mirrors negotiation.py convention) 

40_COMPRESSION_TO_CHAIN: dict[str, FormatChain] = { 

41 "chd": ("chd",), 

42 "rvz": ("rvz",), 

43 "wux": ("wux",), 

44 "xiso": ("xiso",), 

45 "squashfs": ("xiso", "squashfs"), 

46 "7z": ("7z",), 

47 "zip": ("zip",), 

48 "none": ("passthrough",), 

49 "passthrough": ("passthrough",), 

50} 

51 

52# Output extension a chain produces → the chain(s) a frontend listing that 

53# extension can therefore load. 

54_EXTENSION_TO_CHAINS: dict[str, tuple[FormatChain, ...]] = { 

55 ".7z": (("7z",),), 

56 ".zip": (("zip",), ("passthrough",)), 

57 ".chd": (("chd",),), 

58 ".cue": (("cue_bin",),), 

59 ".bin": (("cue_bin",),), 

60 ".iso": (("iso",), ("xiso",), ("passthrough",)), 

61 ".xiso": (("xiso",),), 

62 ".squashfs": (("xiso", "squashfs"),), 

63 ".rvz": (("rvz",),), 

64 ".wux": (("wux",),), 

65 ".wud": (("wux",),), 

66 ".wad": (("passthrough",),), 

67 ".ps3": (("ps3",),), 

68 ".m3u": (), 

69} 

70 

71 

72def _chains_from_extensions(extensions: list[str], preferred: str) -> list[FormatChain]: 

73 """Ordered chains a frontend supports, given its extension list. 

74 

75 ``preferred`` (the YAML ``preferred_compression``) moves its chain to the 

76 front. Extensions with no compressed counterpart (e.g. ``.nes``) imply the 

77 frontend also accepts the raw file, i.e. ``passthrough``. 

78 """ 

79 chains: list[FormatChain] = [] 

80 for ext in extensions: 

81 for chain in _EXTENSION_TO_CHAINS.get(ext, (("passthrough",),)): 

82 if chain not in chains: 

83 chains.append(chain) 

84 pref_chain = _COMPRESSION_TO_CHAIN.get(preferred) 

85 if pref_chain is not None: 

86 if pref_chain in chains: 

87 chains.remove(pref_chain) 

88 chains.insert(0, pref_chain) 

89 return chains 

90 

91 

92@dataclass(frozen=True) 

93class ConcreteTargetProfile: 

94 """A fully resolved target profile combining frontend + optional device. 

95 

96 This class implements the ``TargetProfile`` protocol from 

97 ``docs/compiler-refactor/02-ir-contracts.md §5``. 

98 """ 

99 

100 name: str 

101 description: str = "" 

102 # folder_mapping: internal platform id → frontend folder name 

103 folder_mapping: dict[str, str] = field(default_factory=dict) 

104 # platform_preferences: platform id → ordered list of FormatChains 

105 platform_preferences: dict[str, list[FormatChain]] = field(default_factory=dict) 

106 # unsupported_platforms: set of platform ids this target cannot run 

107 unsupported_platforms: frozenset[str] = frozenset() 

108 # layout 

109 layout_constraints: LayoutConstraints = field(default_factory=LayoutConstraints) 

110 # metadata 

111 metadata_dialect: MetadataDialect = MetadataDialect.NONE 

112 metadata_enabled: bool = False 

113 # media 

114 media_policy: MediaPolicy = field(default_factory=MediaPolicy) 

115 # organisation style ("flat" | "balanced" | "minimal" | "rich") 

116 organisation_style: str = "flat" 

117 # capability facts from the device profile (intent layer reads these) 

118 capabilities: dict[str, PlatformCapability] = field(default_factory=dict) 

119 capability_default: PlatformCapability | None = None 

120 reserve_bytes: int | None = None 

121 

122 # TargetProfile protocol 

123 def supports(self, platform: PlatformId) -> bool: 

124 cap = self.capabilities.get(str(platform)) 

125 if cap is not None and cap.tier == "X": 

126 return False 

127 return str(platform) not in self.unsupported_platforms 

128 

129 def capability(self, platform: PlatformId) -> PlatformCapability: 

130 """Capability for *platform*; raises ``KeyError`` when the device profile is silent. 

131 

132 An absent platform is an error, not an invitation to guess (brief §5). 

133 """ 

134 cap = self.capabilities.get(str(platform)) 

135 if cap is not None: 

136 return cap 

137 if self.capability_default is not None: 

138 return self.capability_default 

139 raise KeyError(f"device profile has no capability entry for platform {platform!r}") 

140 

141 def format_preferences(self, platform: PlatformId) -> list[FormatChain]: 

142 return self.platform_preferences.get(str(platform), []) 

143 

144 def folder_name(self, platform: PlatformId) -> str: 

145 """Return the folder name for *platform* (falls back to platform id).""" 

146 return self.folder_mapping.get(str(platform), str(platform)) 

147 

148 

149# --------------------------------------------------------------------------- 

150# Loader 

151# --------------------------------------------------------------------------- 

152 

153 

154class TargetProfileLoader: 

155 """Loads and caches ``ConcreteTargetProfile`` instances from YAML files. 

156 

157 Args: 

158 config_dir: Root directory containing ``frontends/`` and ``devices/`` 

159 subdirectories. Defaults to ``config/`` relative to the cwd. 

160 """ 

161 

162 def __init__(self, config_dir: Path | None = None) -> None: 

163 self._config_dir = config_dir or Path("config") 

164 self._cache: dict[str, ConcreteTargetProfile] = {} 

165 

166 def load(self, target_name: str) -> ConcreteTargetProfile: 

167 """Return the profile for *target_name* (``frontend`` or ``frontend/device``). 

168 

169 Examples:: 

170 

171 loader.load("batocera") # frontend only 

172 loader.load("batocera/r36s") # frontend + device 

173 loader.load("rocknix") # frontend only 

174 """ 

175 if target_name in self._cache: 

176 return self._cache[target_name] 

177 

178 parts = target_name.split("/", 1) 

179 frontend_name = parts[0] 

180 device_name = parts[1] if len(parts) > 1 else None 

181 

182 frontend_raw = self._load_yaml( 

183 self._config_dir / "frontends" / f"{frontend_name}.yaml", kind="frontend" 

184 ) 

185 device_raw = ( 

186 self._load_yaml(self._config_dir / "devices" / f"{device_name}.yaml", kind="device") 

187 if device_name 

188 else {} 

189 ) 

190 

191 profile = _build_profile(frontend_name, frontend_raw, device_raw) 

192 self._cache[target_name] = profile 

193 return profile 

194 

195 def available_frontends(self) -> list[str]: 

196 """Return names of available frontend configs.""" 

197 d = self._config_dir / "frontends" 

198 if not d.exists(): 

199 return [] 

200 return [p.stem for p in d.glob("*.yaml")] 

201 

202 def available_devices(self) -> list[str]: 

203 """Return names of available device configs.""" 

204 d = self._config_dir / "devices" 

205 if not d.exists(): 

206 return [] 

207 return [p.stem for p in d.glob("*.yaml")] 

208 

209 @staticmethod 

210 def _load_yaml(path: Path, kind: str = "profile") -> dict[str, Any]: 

211 """Load one profile YAML. Loud: missing or malformed → ``TargetProfileError``.""" 

212 if not path.exists(): 

213 raise TargetProfileError(f"{kind} profile not found: {path}") 

214 try: 

215 import yaml 

216 

217 with open(path) as fh: 

218 raw = yaml.safe_load(fh) 

219 except Exception as exc: 

220 raise TargetProfileError(f"{kind} profile {path} is not valid YAML: {exc}") from exc 

221 if raw is None: 

222 return {} 

223 if not isinstance(raw, dict): 

224 raise TargetProfileError( 

225 f"{kind} profile {path} must be a mapping, got {type(raw).__name__}" 

226 ) 

227 return raw 

228 

229 

230# --------------------------------------------------------------------------- 

231# Internal builder 

232# --------------------------------------------------------------------------- 

233 

234 

235def _build_profile( 

236 name: str, 

237 frontend: dict[str, Any], 

238 device: dict[str, Any], 

239) -> ConcreteTargetProfile: 

240 """Merge frontend + device YAML into a ``ConcreteTargetProfile``.""" 

241 

242 description = frontend.get("description") or device.get("description") or name 

243 

244 # Folder mapping 

245 folder_mapping: dict[str, str] = {} 

246 fm = frontend.get("folder_mapping") or {} 

247 if isinstance(fm, dict): 

248 folder_mapping = {str(k): str(v) for k, v in fm.items()} 

249 

250 # Unsupported platforms (device gates) 

251 unsupported: set[str] = set() 

252 dev_unsupported = device.get("unsupported_platforms") or [] 

253 if isinstance(dev_unsupported, list): 

254 unsupported.update(str(p) for p in dev_unsupported) 

255 

256 # Per-platform format preferences (from frontend platform definitions). 

257 # The frontend's `extensions` list is the ground truth for what it can 

258 # load; `preferred_compression` only orders the list. A chain whose 

259 # output extension the frontend lists is supported. 

260 platform_prefs: dict[str, list[FormatChain]] = {} 

261 platform_defs = frontend.get("platforms") or {} 

262 if isinstance(platform_defs, dict): 

263 for plat, pdef in platform_defs.items(): 

264 if not isinstance(pdef, dict): 

265 continue 

266 prefs = _chains_from_extensions( 

267 [str(e).lower() for e in (pdef.get("extensions") or [])], 

268 str(pdef.get("preferred_compression") or ""), 

269 ) 

270 if prefs: 

271 platform_prefs[str(plat)] = prefs 

272 

273 # Capability tiers + storage reserve (from device) 

274 def _cap(raw: Any) -> PlatformCapability: 

275 if not isinstance(raw, dict) or "tier" not in raw: 

276 raise TargetProfileError( 

277 f"device profile {name!r}: every platforms/platforms_default entry must state " 

278 f"tier A|B|C|X, got {raw!r}" 

279 ) 

280 tier = str(raw["tier"]).upper() 

281 if tier not in ("A", "B", "C", "X"): 

282 raise TargetProfileError( 

283 f"device profile {name!r}: tier must be A|B|C|X, got {raw['tier']!r}" 

284 ) 

285 return PlatformCapability( 

286 tier=tier, 

287 quality=float(raw.get("quality", 1.0)), 

288 playable_list=str(raw["playable_list"]) if raw.get("playable_list") else None, 

289 notes=str(raw.get("notes", "")), 

290 ) 

291 

292 capabilities: dict[str, PlatformCapability] = {} 

293 dev_platforms = device.get("platforms") or {} 

294 if isinstance(dev_platforms, dict): 

295 capabilities = {str(k): _cap(v) for k, v in dev_platforms.items()} 

296 capability_default = ( 

297 _cap(device["platforms_default"]) if device.get("platforms_default") else None 

298 ) 

299 storage = device.get("storage") or {} 

300 reserve_raw = storage.get("reserve_bytes") if isinstance(storage, dict) else None 

301 reserve_bytes = int(reserve_raw) if reserve_raw is not None else None 

302 

303 # Media sizing (from device) 

304 media_sizing = device.get("media_sizing") or {} 

305 max_w = media_sizing.get("max_image_width") 

306 max_h = media_sizing.get("max_image_height") 

307 allow_video = "video" in (frontend.get("media_support") or []) 

308 media_policy = MediaPolicy( 

309 max_image_width=int(max_w) if max_w else None, 

310 max_image_height=int(max_h) if max_h else None, 

311 allow_video=allow_video, 

312 ) 

313 

314 # Metadata dialect / organisation style live under `defaults:` in the 

315 # shipped frontend YAMLs; accept a top-level key too. 

316 defaults = frontend.get("defaults") or {} 

317 metadata_enabled = bool(frontend.get("metadata", defaults.get("metadata", False))) 

318 dialect = MetadataDialect.ES_GAMELIST if metadata_enabled else MetadataDialect.NONE 

319 

320 # Organisation style 

321 org_style = str(frontend.get("organization_style") or defaults.get("organization") or "flat") 

322 

323 return ConcreteTargetProfile( 

324 name=f"{name}", 

325 description=description, 

326 folder_mapping=folder_mapping, 

327 platform_preferences=platform_prefs, 

328 unsupported_platforms=frozenset(unsupported), 

329 layout_constraints=LayoutConstraints(), 

330 metadata_dialect=dialect, 

331 metadata_enabled=metadata_enabled, 

332 media_policy=media_policy, 

333 organisation_style=org_style, 

334 capabilities=capabilities, 

335 capability_default=capability_default, 

336 reserve_bytes=reserve_bytes, 

337 )