Coverage for src/romfarmer/config/target_loader.py: 75%
106 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"""Target, Frontend, and Device configuration loaders.
3This module provides functions to load and compose target configurations
4from their constituent frontend and device configs.
5"""
7import os
8from pathlib import Path
9from typing import Any
11import yaml
13from .device import DeviceConfig, DisplayConfig, MediaSizingConfig
14from .frontend import FrontendConfig, FrontendDefaults, FrontendPlatformConfig, MediaType
15from .target import ComposedTarget, TargetConfig, TargetOverrides
18class TargetConfigLoader:
19 """Load and compose target configurations."""
21 def __init__(self, config_root: Path | None = None):
22 """Initialize target config loader.
24 Args:
25 config_root: Root directory for config files. Defaults to workspace/config.
26 """
27 if config_root is None:
28 config_root = Path(__file__).parent.parent.parent.parent / "config"
29 self.config_root = config_root
31 # Cache loaded configs to avoid reloading
32 self._frontend_cache: dict[str, FrontendConfig] = {}
33 self._device_cache: dict[str, DeviceConfig] = {}
34 self._target_cache: dict[str, TargetConfig] = {}
36 def _load_yaml(self, path: Path) -> dict[str, Any]:
37 """Load YAML file with environment variable substitution.
39 Args:
40 path: Path to YAML file
42 Returns:
43 Parsed YAML as dictionary
45 Raises:
46 FileNotFoundError: If file doesn't exist
47 yaml.YAMLError: If YAML is invalid
48 """
49 if not path.exists():
50 raise FileNotFoundError(f"Config file not found: {path}")
52 with open(path) as f:
53 content = f.read()
55 # Substitute environment variables
56 content = os.path.expandvars(content)
58 return yaml.safe_load(content)
60 def load_frontend(self, name: str) -> FrontendConfig:
61 """Load a frontend configuration.
63 Args:
64 name: Frontend name (e.g., 'batocera', 'rocknix')
66 Returns:
67 Validated FrontendConfig
69 Raises:
70 FileNotFoundError: If frontend config doesn't exist
71 ValidationError: If config is invalid
72 """
73 # Check cache first
74 if name in self._frontend_cache:
75 return self._frontend_cache[name]
77 config_path = self.config_root / "frontends" / f"{name}.yaml"
78 raw_config = self._load_yaml(config_path)
80 # Parse media_support as MediaType enum values
81 if "media_support" in raw_config:
82 raw_config["media_support"] = [
83 MediaType(m) if isinstance(m, str) else m for m in raw_config["media_support"]
84 ]
86 # Parse platform configs
87 if "platforms" in raw_config:
88 platforms = {}
89 for platform_name, platform_data in raw_config["platforms"].items():
90 platforms[platform_name] = FrontendPlatformConfig(**platform_data)
91 raw_config["platforms"] = platforms
93 # Parse defaults
94 if "defaults" in raw_config:
95 raw_config["defaults"] = FrontendDefaults(**raw_config["defaults"])
97 frontend = FrontendConfig(**raw_config)
98 self._frontend_cache[name] = frontend
99 return frontend
101 def load_device(self, name: str) -> DeviceConfig:
102 """Load a device configuration.
104 Args:
105 name: Device name (e.g., 'pc', 'r36s', 'steamdeck')
107 Returns:
108 Validated DeviceConfig
110 Raises:
111 FileNotFoundError: If device config doesn't exist
112 ValidationError: If config is invalid
113 """
114 # Check cache first
115 if name in self._device_cache:
116 return self._device_cache[name]
118 config_path = self.config_root / "devices" / f"{name}.yaml"
119 raw_config = self._load_yaml(config_path)
121 # Parse nested configs
122 if "display" in raw_config:
123 raw_config["display"] = DisplayConfig(**raw_config["display"])
125 if "media_sizing" in raw_config:
126 raw_config["media_sizing"] = MediaSizingConfig(**raw_config["media_sizing"])
128 device = DeviceConfig(**raw_config)
129 self._device_cache[name] = device
130 return device
132 def load_target(self, name: str) -> TargetConfig:
133 """Load a target configuration (without composing frontend/device).
135 Args:
136 name: Target name (e.g., 'rocknix-r36s', 'batocera-pc')
138 Returns:
139 Validated TargetConfig
141 Raises:
142 FileNotFoundError: If target config doesn't exist
143 ValidationError: If config is invalid
144 """
145 # Check cache first
146 if name in self._target_cache:
147 return self._target_cache[name]
149 config_path = self.config_root / "targets" / f"{name}.yaml"
150 raw_config = self._load_yaml(config_path)
152 # Parse overrides
153 if "overrides" in raw_config:
154 raw_config["overrides"] = TargetOverrides(**raw_config["overrides"])
156 target = TargetConfig(**raw_config)
157 self._target_cache[name] = target
158 return target
160 def load_composed_target(self, name: str) -> ComposedTarget:
161 """Load and compose a target with its frontend and device configs.
163 This is the main entry point for getting a fully resolved target
164 configuration that can be used for builds.
166 Args:
167 name: Target name (e.g., 'rocknix-r36s', 'batocera-pc')
169 Returns:
170 ComposedTarget with frontend and device loaded
172 Raises:
173 FileNotFoundError: If any config doesn't exist
174 ValidationError: If any config is invalid
175 """
176 # Load the target config
177 target_config = self.load_target(name)
179 # Load referenced frontend and device
180 frontend = self.load_frontend(target_config.frontend)
181 device = self.load_device(target_config.device)
183 # Compose into a ComposedTarget
184 return ComposedTarget(
185 name=target_config.name,
186 description=target_config.description,
187 frontend=frontend,
188 device=device,
189 target_config=target_config,
190 )
192 def list_frontends(self) -> list[str]:
193 """List all available frontend configurations.
195 Returns:
196 List of frontend names (without .yaml extension)
197 """
198 frontends_dir = self.config_root / "frontends"
199 if not frontends_dir.exists():
200 return []
201 return sorted([f.stem for f in frontends_dir.glob("*.yaml")])
203 def list_devices(self) -> list[str]:
204 """List all available device configurations.
206 Returns:
207 List of device names (without .yaml extension)
208 """
209 devices_dir = self.config_root / "devices"
210 if not devices_dir.exists():
211 return []
212 return sorted([f.stem for f in devices_dir.glob("*.yaml")])
214 def list_targets(self) -> list[str]:
215 """List all available target configurations.
217 Returns:
218 List of target names (without .yaml extension)
219 """
220 targets_dir = self.config_root / "targets"
221 if not targets_dir.exists():
222 return []
223 return sorted([f.stem for f in targets_dir.glob("*.yaml")])
225 def clear_cache(self):
226 """Clear all cached configurations."""
227 self._frontend_cache.clear()
228 self._device_cache.clear()
229 self._target_cache.clear()
232# Convenience functions for direct usage
235def load_frontend(name: str, config_root: Path | None = None) -> FrontendConfig:
236 """Load frontend configuration (convenience function).
238 Args:
239 name: Frontend name
240 config_root: Config root directory
242 Returns:
243 Validated FrontendConfig
244 """
245 loader = TargetConfigLoader(config_root)
246 return loader.load_frontend(name)
249def load_device(name: str, config_root: Path | None = None) -> DeviceConfig:
250 """Load device configuration (convenience function).
252 Args:
253 name: Device name
254 config_root: Config root directory
256 Returns:
257 Validated DeviceConfig
258 """
259 loader = TargetConfigLoader(config_root)
260 return loader.load_device(name)
263def load_target(name: str, config_root: Path | None = None) -> TargetConfig:
264 """Load target configuration without composition (convenience function).
266 Args:
267 name: Target name
268 config_root: Config root directory
270 Returns:
271 Validated TargetConfig
272 """
273 loader = TargetConfigLoader(config_root)
274 return loader.load_target(name)
277def load_composed_target(name: str, config_root: Path | None = None) -> ComposedTarget:
278 """Load and compose target configuration (convenience function).
280 This is the main function to use when you need a fully resolved
281 target configuration.
283 Args:
284 name: Target name
285 config_root: Config root directory
287 Returns:
288 ComposedTarget with frontend and device loaded
289 """
290 loader = TargetConfigLoader(config_root)
291 return loader.load_composed_target(name)
294def list_frontends(config_root: Path | None = None) -> list[str]:
295 """List available frontends (convenience function)."""
296 loader = TargetConfigLoader(config_root)
297 return loader.list_frontends()
300def list_devices(config_root: Path | None = None) -> list[str]:
301 """List available devices (convenience function)."""
302 loader = TargetConfigLoader(config_root)
303 return loader.list_devices()
306def list_targets(config_root: Path | None = None) -> list[str]:
307 """List available targets (convenience function)."""
308 loader = TargetConfigLoader(config_root)
309 return loader.list_targets()