Coverage for src/romfarmer/config/new_loader.py: 69%
195 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"""Loaders for the new declarative config types.
3Provides functions to load:
4- SlimPlatformConfig from config/platforms/ (slim format)
5- RecipeSpec from config/recipes/
6- BuildSpec from config/builds/ (new format)
7"""
9import os
10from pathlib import Path
11from typing import Any
13import yaml
15from .build_spec import BuildSpec, DeployConfig, PostBuildHook
16from .models import (
17 DATSource,
18 ExtractionType,
19 SelectionConfig,
20 SourceConfig,
21)
22from .recipe import RecipeSpec
23from .slim_platform import (
24 ArcadeFilter,
25 DATReference,
26 ListPatterns,
27 PS3Config,
28 SlimPlatformConfig,
29 XboxConfig,
30)
33def _load_yaml(path: Path) -> dict[str, Any]:
34 """Load YAML file with environment variable substitution."""
35 if not path.exists():
36 raise FileNotFoundError(f"Config file not found: {path}")
38 with open(path) as f:
39 content = f.read()
41 content = os.path.expandvars(_with_default_env(content))
42 return yaml.safe_load(content)
45def _with_default_env(content: str) -> str:
46 """Default the source-root variables so configs resolve without a .env.
48 ``ROMFARMER_SOURCE_ROOT`` → {workspace}/source (Myrient layout)
49 ``ROMFARMER_ARCHIVE_ROOT`` → {workspace}/source/archive.org (archive.org sets)
50 ``ROMFARMER_OUTPUT_ROOT`` → {workspace}/output (build output_base)
51 """
52 from romfarmer.core.paths import get_paths
54 paths = get_paths()
55 source_dir = paths.source_dir
56 os.environ.setdefault("ROMFARMER_SOURCE_ROOT", str(source_dir))
57 os.environ.setdefault("ROMFARMER_ARCHIVE_ROOT", str(source_dir / "archive.org"))
58 os.environ.setdefault("ROMFARMER_OUTPUT_ROOT", str(paths.output_dir))
59 return content
62# ═══════════════════════════════════════════════════════════════════════════════
63# Slim Platform Loader
64# ═══════════════════════════════════════════════════════════════════════════════
67def load_slim_platform(
68 name: str,
69 config_root: Path | None = None,
70 *,
71 check_source_paths: bool = True,
72) -> SlimPlatformConfig:
73 """Load a platform config (slim or legacy fat format).
75 ``check_source_paths=False`` skips ``SourceConfig``'s path-exists check for
76 the platform's intrinsic sources — used when the caller supplies its own
77 sources (a Spec) or only needs intrinsics (capabilities). Without it,
78 RESOLVE would need this host's mounts to read a platform's extraction type.
79 """
80 from .models import CHECK_SOURCE_PATHS
82 token = CHECK_SOURCE_PATHS.set(check_source_paths)
83 try:
84 return _load_slim_platform_impl(name, config_root, check_source_paths=check_source_paths)
85 finally:
86 CHECK_SOURCE_PATHS.reset(token)
89def _load_slim_platform_impl(
90 name: str,
91 config_root: Path | None = None,
92 *,
93 check_source_paths: bool = True,
94) -> SlimPlatformConfig:
95 """Load a slim platform config from YAML.
97 Supports both the new slim format AND the old fat format (for migration).
98 When loading an old format, strips non-intrinsic fields automatically.
100 Args:
101 name: Platform name (without .yaml)
102 config_root: Config root directory (default: auto-detect)
104 Returns:
105 SlimPlatformConfig with intrinsic facts only
106 """
107 if config_root is None:
108 config_root = Path(__file__).parent.parent.parent.parent / "config"
110 config_path = config_root / "platforms" / f"{name}.yaml"
111 raw = _load_yaml(config_path)
113 # Detect format: if 'targets' key exists, it's the old fat format
114 if "targets" in raw:
115 return _convert_fat_to_slim(raw)
117 # New slim format — parse directly
118 return _parse_slim_platform(raw)
121def _parse_slim_platform(raw: dict[str, Any]) -> SlimPlatformConfig:
122 """Parse a new-format slim platform YAML."""
124 # Parse DAT reference
125 dat_data = raw.get("dat", {})
126 if isinstance(dat_data.get("source"), str):
127 dat_data["source"] = DATSource(dat_data["source"])
128 if "file" in dat_data and dat_data["file"] is not None:
129 dat_data["file"] = Path(dat_data["file"])
130 dat = DATReference(**dat_data)
132 # Parse sources
133 sources = _parse_sources(raw.get("sources", []))
134 chd_sources = _parse_sources(raw.get("chd_sources", [])) if "chd_sources" in raw else None
136 # Parse extraction type
137 extraction = ExtractionType.NONE
138 if "extraction" in raw:
139 ext = raw["extraction"]
140 if isinstance(ext, str):
141 extraction = ExtractionType(ext)
142 elif isinstance(ext, dict):
143 extraction = ExtractionType(ext.get("type", "none"))
145 # Parse list patterns
146 list_patterns = None
147 if "list_patterns" in raw:
148 list_patterns = ListPatterns(**raw["list_patterns"])
150 # Parse arcade filter
151 arcade_filter = None
152 if "arcade_filter" in raw:
153 arcade_filter = ArcadeFilter(**raw["arcade_filter"])
155 # Parse PS3 config
156 ps3 = None
157 if "ps3" in raw:
158 ps3_data = dict(raw["ps3"])
159 for path_field in ["keys_directory", "ps3dec_path", "nps_database", "pkg_archive"]:
160 if path_field in ps3_data and ps3_data[path_field] is not None:
161 ps3_data[path_field] = Path(ps3_data[path_field])
162 ps3 = PS3Config(**ps3_data)
164 # Parse Xbox config
165 xbox = None
166 if "xbox" in raw:
167 xbox_data = dict(raw["xbox"])
168 if "extract_xiso_path" in xbox_data and xbox_data["extract_xiso_path"] is not None:
169 xbox_data["extract_xiso_path"] = Path(xbox_data["extract_xiso_path"])
170 xbox = XboxConfig(**xbox_data)
172 # Parse samples sources
173 samples_sources = None
174 if "samples_sources" in raw:
175 samples_sources = _parse_sources(raw["samples_sources"])
176 elif "samples" in raw:
177 # Legacy: 'samples' key
178 samples_sources = _parse_sources(raw["samples"])
180 # Parse extras config
181 extras = None
182 if "extras" in raw:
183 from romfarmer.config.slim_platform import ExtrasConfig
185 extras = ExtrasConfig(**raw["extras"])
187 return SlimPlatformConfig(
188 name=raw["name"],
189 display_name=raw.get("display_name"),
190 type=raw.get("type"),
191 emulator=raw.get("emulator"),
192 metadata_system=raw.get("metadata_system"),
193 dat=dat,
194 sources=sources,
195 chd_sources=chd_sources,
196 extraction=extraction,
197 multi_disc=raw.get("multi_disc", raw.get("multi_disc_handling", False)),
198 list_patterns=list_patterns,
199 arcade_filter=arcade_filter,
200 bios=raw.get("bios"),
201 samples_sources=samples_sources,
202 ps3=ps3,
203 xbox=xbox,
204 extras=extras,
205 )
208def _convert_fat_to_slim(raw: dict[str, Any]) -> SlimPlatformConfig:
209 """Convert an old-format (fat) platform config to slim.
211 This is the backward compatibility shim. It reads the full old format
212 and extracts only the intrinsic fields.
213 """
214 # Parse DAT reference from old format
215 dat_data = raw.get("dat", {})
216 if isinstance(dat_data.get("source"), str):
217 dat_data["source"] = DATSource(dat_data["source"])
218 if "file" in dat_data and dat_data["file"] is not None:
219 dat_data["file"] = Path(dat_data["file"])
220 dat = DATReference(
221 source=dat_data.get("source", DATSource.RETOOL_1G1R_ENG),
222 file=dat_data.get("file"),
223 platform_name=dat_data.get("platform_name"),
224 expected_count=dat_data.get("expected_count"),
225 match_method=dat_data.get("match_method", "hash"),
226 version=dat_data.get("version"),
227 filter_driver=dat_data.get("filter_driver"),
228 filter_romof=dat_data.get("filter_romof"),
229 exclude_romof=dat_data.get("exclude_romof"),
230 name_pattern=dat_data.get("name_pattern"),
231 exclude_name_pattern=dat_data.get("exclude_name_pattern"),
232 )
234 # Parse sources
235 sources = _parse_sources(raw.get("sources", []))
236 chd_sources = _parse_sources(raw.get("chd_sources", [])) if "chd_sources" in raw else None
238 # Parse extraction type from old nested format
239 extraction = ExtractionType.NONE
240 ext_data = raw.get("extraction", {})
241 if isinstance(ext_data, dict):
242 if ext_data.get("enabled", False) and ext_data.get("type"):
243 extraction = ExtractionType(ext_data["type"])
244 elif not ext_data.get("enabled", True) and ext_data.get("type", "none") == "none":
245 extraction = ExtractionType.NONE
247 # Convert old lists format to new list_patterns
248 list_patterns = None
249 lists_data = raw.get("lists", {})
250 if lists_data and isinstance(lists_data, dict):
251 patterns = lists_data.get("patterns", {})
252 if patterns:
253 list_patterns = ListPatterns(
254 delete=patterns.get("delete"),
255 add_myrient=patterns.get("add_myrient"),
256 add_extra=patterns.get("add_extra"),
257 add=patterns.get("add"),
258 )
260 # Parse arcade filter
261 arcade_filter = None
262 if "arcade_filter" in raw:
263 arcade_filter = ArcadeFilter(**raw["arcade_filter"])
265 # Extract PS3 config from old format
266 ps3 = None
267 if extraction == ExtractionType.PS3:
268 ps3_data = {}
269 if ext_data.get("keys_directory"):
270 ps3_data["keys_directory"] = Path(ext_data["keys_directory"])
271 if ext_data.get("ps3dec_path"):
272 ps3_data["ps3dec_path"] = Path(ext_data["ps3dec_path"])
273 updates = raw.get("updates", {})
274 if updates:
275 ps3_data["nps_database"] = (
276 Path(updates["nps_database"]) if updates.get("nps_database") else None
277 )
278 ps3_data["pkg_archive"] = (
279 Path(updates["pkg_archive"]) if updates.get("pkg_archive") else None
280 )
281 ps3_data["use_sony_psn"] = updates.get("use_sony_psn", True)
282 dlc = raw.get("dlc", {})
283 if dlc:
284 ps3_data["dlc_enabled"] = dlc.get("enabled", False)
285 ps3_data["dlc_mode"] = dlc.get("mode", "copy")
286 if ps3_data:
287 ps3 = PS3Config(**ps3_data)
289 # Extract Xbox config from old format
290 xbox = None
291 if extraction == ExtractionType.XISO:
292 xbox_data = {}
293 if ext_data.get("extract_xiso_path"):
294 xbox_data["extract_xiso_path"] = Path(ext_data["extract_xiso_path"])
295 if xbox_data:
296 xbox = XboxConfig(**xbox_data)
298 # Parse samples sources
299 samples_sources = None
300 if "samples" in raw:
301 samples_sources = _parse_sources(raw["samples"])
303 # Parse extras config (also supported in fat format)
304 extras = None
305 if "extras" in raw:
306 from romfarmer.config.slim_platform import ExtrasConfig
308 extras = ExtrasConfig(**raw["extras"])
310 return SlimPlatformConfig(
311 name=raw["name"],
312 display_name=raw.get("display_name"),
313 type=raw.get("type"),
314 emulator=raw.get("emulator"),
315 metadata_system=raw.get("metadata_system"),
316 dat=dat,
317 sources=sources,
318 chd_sources=chd_sources,
319 extraction=extraction,
320 multi_disc=raw.get("multi_disc_handling", raw.get("multi_disc", False)),
321 list_patterns=list_patterns,
322 arcade_filter=arcade_filter,
323 bios=raw.get("bios"),
324 samples_sources=samples_sources,
325 ps3=ps3,
326 xbox=xbox,
327 extras=extras,
328 )
331def _parse_sources(sources_data: list) -> list[SourceConfig]:
332 """Parse source configuration list."""
333 sources = []
334 for src in sources_data:
335 if isinstance(src, dict):
336 data = dict(src)
337 if "path" in data and data["path"] is not None:
338 data["path"] = Path(data["path"])
339 sources.append(SourceConfig(**data))
340 return sources
343# ═══════════════════════════════════════════════════════════════════════════════
344# Recipe Loader
345# ═══════════════════════════════════════════════════════════════════════════════
348def load_recipe(
349 name: str,
350 config_root: Path | None = None,
351) -> RecipeSpec:
352 """Load a recipe from YAML.
354 Args:
355 name: Recipe name (without .yaml)
356 config_root: Config root directory
358 Returns:
359 Validated RecipeSpec
360 """
361 if config_root is None:
362 config_root = Path(__file__).parent.parent.parent.parent / "config"
364 config_path = config_root / "recipes" / f"{name}.yaml"
365 raw = _load_yaml(config_path)
367 # Parse selection if present
368 if "selection" in raw and raw["selection"] is not None:
369 raw["selection"] = SelectionConfig(**raw["selection"])
371 return RecipeSpec(**raw)
374def load_all_recipes(
375 config_root: Path | None = None,
376) -> dict[str, RecipeSpec]:
377 """Load all recipes from the recipes directory.
379 Returns:
380 Dict mapping recipe name to RecipeSpec
381 """
382 if config_root is None:
383 config_root = Path(__file__).parent.parent.parent.parent / "config"
385 recipes_dir = config_root / "recipes"
386 if not recipes_dir.exists():
387 return {}
389 recipes = {}
390 for yaml_file in sorted(recipes_dir.glob("*.yaml")):
391 name = yaml_file.stem
392 try:
393 recipes[name] = load_recipe(name, config_root)
394 except Exception as e:
395 raise ValueError(f"Failed to load recipe '{name}': {e}") from e
397 return recipes
400# ═══════════════════════════════════════════════════════════════════════════════
401# Build Spec Loader
402# ═══════════════════════════════════════════════════════════════════════════════
405def load_build_spec(
406 name: str,
407 config_root: Path | None = None,
408) -> BuildSpec:
409 """Load a build spec from YAML.
411 Searches for the build config in:
412 1. config/builds/new/{name}.yaml (new-format builds)
413 2. config/builds/{name}.yaml (may be old or new format)
415 Detects whether the YAML is new-format (has 'recipes' key) or
416 old-format (has 'includes' or 'platform_overrides'). Only loads
417 new-format files as BuildSpec.
419 Args:
420 name: Build name (without .yaml)
421 config_root: Config root directory
423 Returns:
424 Validated BuildSpec
426 Raises:
427 ValueError: If the config is old-format (use load_build_config instead)
428 FileNotFoundError: If no config found
429 """
430 if config_root is None:
431 config_root = Path(__file__).parent.parent.parent.parent / "config"
433 # Search in new/ subdirectory first, then builds/
434 candidates = [
435 config_root / "builds" / "new" / f"{name}.yaml",
436 config_root / "builds" / f"{name}.yaml",
437 ]
439 config_path = None
440 for candidate in candidates:
441 if candidate.exists():
442 config_path = candidate
443 break
445 if config_path is None:
446 raise FileNotFoundError(
447 f"Build config not found: {name}\nSearched: {', '.join(str(c) for c in candidates)}"
448 )
450 raw = _load_yaml(config_path)
452 # Detect old format
453 if "includes" in raw or "platform_overrides" in raw:
454 raise ValueError(
455 f"Build config '{name}' is in old format (has 'includes' or 'platform_overrides'). "
456 "Use load_build_config() for legacy configs, or migrate to new recipe-based format."
457 )
459 # Parse nested objects
460 if "selection" in raw and raw["selection"] is not None:
461 raw["selection"] = SelectionConfig(**raw["selection"])
463 if "generation_filter" in raw and raw["generation_filter"] is not None:
464 from .models import GenerationFilterConfig
466 raw["generation_filter"] = GenerationFilterConfig(**raw["generation_filter"])
468 if "deploy" in raw and raw["deploy"] is not None:
469 raw["deploy"] = DeployConfig(**raw["deploy"])
471 if "post_build" in raw:
472 raw["post_build"] = [
473 PostBuildHook(**hook) if isinstance(hook, dict) else hook for hook in raw["post_build"]
474 ]
476 return BuildSpec(**raw)