Coverage for src/romfarmer/config/loader.py: 17%

89 statements  

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

1"""Configuration file loader with YAML support and validation.""" 

2 

3import os 

4from pathlib import Path 

5from typing import Any 

6 

7import yaml 

8 

9from romfarmer.core.paths import get_paths 

10 

11from .models import BuildConfig, PlatformConfig 

12 

13 

14class ConfigLoader: 

15 """Load and validate configuration files.""" 

16 

17 def __init__(self, config_root: Path | None = None): 

18 """Initialize config loader. 

19 

20 Args: 

21 config_root: Root directory for config files. Defaults to workspace/config. 

22 """ 

23 if config_root is None: 

24 config_root = Path(__file__).parent.parent.parent.parent / "config" 

25 self.config_root = config_root 

26 self.workspace_root = get_paths().workspace_root 

27 

28 def _load_yaml(self, path: Path) -> dict[str, Any]: 

29 """Load YAML file with environment variable substitution. 

30 

31 Args: 

32 path: Path to YAML file 

33 

34 Returns: 

35 Parsed YAML as dictionary 

36 

37 Raises: 

38 FileNotFoundError: If file doesn't exist 

39 yaml.YAMLError: If YAML is invalid 

40 """ 

41 if not path.exists(): 

42 raise FileNotFoundError(f"Config file not found: {path}") 

43 

44 with open(path) as f: 

45 content = f.read() 

46 

47 # Substitute environment variables 

48 content = os.path.expandvars(content) 

49 

50 return yaml.safe_load(content) 

51 

52 def _resolve_paths(self, config: dict[str, Any]) -> dict[str, Any]: 

53 """Resolve relative paths in configuration. 

54 

55 Args: 

56 config: Configuration dictionary 

57 

58 Returns: 

59 Configuration with resolved paths 

60 """ 

61 

62 def _resolve(obj: Any, parent_key: str = "") -> Any: 

63 """Recursively resolve paths.""" 

64 if isinstance(obj, dict): 

65 return {k: _resolve(v, k) for k, v in obj.items()} 

66 elif isinstance(obj, list): 

67 return [_resolve(item, parent_key) for item in obj] 

68 elif isinstance(obj, str): 

69 # Convert path-like strings to Path objects 

70 if parent_key in [ 

71 "path", 

72 "file", 

73 "directory", 

74 "output_path", 

75 "workspace", 

76 "dat_directory", 

77 ]: 

78 path = Path(obj) 

79 # Resolve relative paths 

80 if not path.is_absolute(): 

81 # These paths should resolve against workspace root, not config root 

82 # 'file' for DAT configs is relative to workspace root (dats/ folder) 

83 workspace_relative_keys = ["directory", "output_path", "workspace", "file"] 

84 if parent_key in workspace_relative_keys: 

85 path = (self.workspace_root / path).resolve() 

86 else: 

87 path = (self.config_root / path).resolve() 

88 return path 

89 return obj 

90 

91 return _resolve(config) 

92 

93 def load_build_config(self, name: str, _seen: set | None = None) -> BuildConfig: 

94 """Load master build configuration with nested orchestration support. 

95 

96 Args: 

97 name: Build config name (without .yaml extension) 

98 _seen: Internal set to detect circular includes 

99 

100 Returns: 

101 Validated BuildConfig with resolved includes 

102 

103 Raises: 

104 FileNotFoundError: If config file doesn't exist 

105 ValidationError: If config is invalid 

106 ValueError: If circular include detected 

107 """ 

108 # Detect circular includes 

109 if _seen is None: 

110 _seen = set() 

111 if name in _seen: 

112 raise ValueError(f"Circular orchestration include detected: {name}") 

113 _seen.add(name) 

114 

115 config_path = self.config_root / "builds" / f"{name}.yaml" 

116 raw_config = self._load_yaml(config_path) 

117 resolved_config = self._resolve_paths(raw_config) 

118 

119 # Process includes recursively 

120 includes = resolved_config.get("includes", []) 

121 if includes: 

122 # Collect platforms and overrides from all included orchestrations 

123 all_platforms = [] 

124 merged_overrides = {} 

125 merged_settings = resolved_config.get("settings", {}).copy() 

126 merged_storage = resolved_config.get("storage", {}).copy() 

127 

128 for include_name in includes: 

129 included_config = self.load_build_config(include_name, _seen.copy()) 

130 

131 # Add platforms (preserving order, avoiding duplicates) 

132 for platform in included_config.platforms: 

133 if platform not in all_platforms: 

134 all_platforms.append(platform) 

135 

136 # Merge platform_overrides (later includes override earlier) 

137 if included_config.platform_overrides: 

138 merged_overrides.update(included_config.platform_overrides) 

139 

140 # Merge settings (parent overrides children) 

141 for key, value in included_config.settings.items(): 

142 if key not in merged_settings: 

143 merged_settings[key] = value 

144 

145 # Merge storage (parent overrides children) 

146 for key, value in included_config.storage.items(): 

147 if key not in merged_storage: 

148 merged_storage[key] = value 

149 

150 # Add this config's platforms after includes 

151 for platform in resolved_config.get("platforms", []): 

152 if platform not in all_platforms: 

153 all_platforms.append(platform) 

154 

155 # Parent overrides take precedence 

156 merged_overrides.update(resolved_config.get("platform_overrides", {})) 

157 

158 # Update resolved config with merged values 

159 resolved_config["platforms"] = all_platforms 

160 resolved_config["platform_overrides"] = merged_overrides 

161 resolved_config["settings"] = merged_settings 

162 resolved_config["storage"] = merged_storage 

163 

164 # Apply excludes - remove platforms from the final list 

165 excludes = resolved_config.get("excludes", []) 

166 if excludes: 

167 resolved_config["platforms"] = [ 

168 p for p in resolved_config.get("platforms", []) if p not in excludes 

169 ] 

170 

171 return BuildConfig(**resolved_config) 

172 

173 def load_platform_config(self, name: str) -> PlatformConfig: 

174 """Load platform configuration. 

175 

176 Args: 

177 name: Platform config name (without .yaml extension) 

178 

179 Returns: 

180 Validated PlatformConfig 

181 

182 Raises: 

183 FileNotFoundError: If config file doesn't exist 

184 ValidationError: If config is invalid 

185 """ 

186 config_path = self.config_root / "platforms" / f"{name}.yaml" 

187 raw_config = self._load_yaml(config_path) 

188 resolved_config = self._resolve_paths(raw_config) 

189 

190 return PlatformConfig(**resolved_config) 

191 

192 def load_platform_configs(self, platform_names: list[str]) -> list[PlatformConfig]: 

193 """Load multiple platform configurations. 

194 

195 Args: 

196 platform_names: List of platform config names 

197 

198 Returns: 

199 List of validated PlatformConfig objects 

200 """ 

201 return [self.load_platform_config(name) for name in platform_names] 

202 

203 

204def load_build_config(name: str, config_root: Path | None = None) -> BuildConfig: 

205 """Load build configuration (convenience function). 

206 

207 Args: 

208 name: Build config name 

209 config_root: Config root directory 

210 

211 Returns: 

212 Validated BuildConfig 

213 """ 

214 loader = ConfigLoader(config_root) 

215 return loader.load_build_config(name) 

216 

217 

218def load_platform_config(name: str, config_root: Path | None = None) -> PlatformConfig: 

219 """Load platform configuration (convenience function). 

220 

221 Args: 

222 name: Platform config name 

223 config_root: Config root directory 

224 

225 Returns: 

226 Validated PlatformConfig 

227 """ 

228 loader = ConfigLoader(config_root) 

229 return loader.load_platform_config(name)