Coverage for /Users/les/Projects/crackerjack/crackerjack/services/unified_config.py: 0%
236 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
1import json
2import os
3import typing as t
4from contextlib import suppress
5from pathlib import Path
6from typing import Any
8import yaml
9from pydantic import BaseModel, Field, field_validator
10from rich.console import Console
12from crackerjack.errors import ValidationError
13from crackerjack.models.protocols import OptionsProtocol
14from crackerjack.services.logging import LoggingContext, get_logger
17class CrackerjackConfig(BaseModel):
18 package_path: Path = Field(default_factory=Path.cwd)
19 cache_enabled: bool = True
20 cache_size: int = 1000
21 cache_ttl: float = 300.0
23 hook_batch_size: int = 10
24 hook_timeout: int = 300
25 max_concurrent_hooks: int = 4
26 enable_async_hooks: bool = True
28 test_timeout: int = 300
29 test_workers: int = Field(default_factory=lambda: os.cpu_count() or 1)
30 min_coverage: float = 10.11
32 log_level: str = "INFO"
33 log_json: bool = False
34 log_file: Path | None = None
35 enable_correlation_ids: bool = True
37 autofix: bool = True
38 skip_hooks: bool = False
39 experimental_hooks: bool = False
41 performance_tracking: bool = True
42 benchmark_mode: bool = False
44 publish_enabled: bool = False
45 keyring_provider: str = "subprocess"
47 batch_file_operations: bool = True
48 file_operation_batch_size: int = 10
50 precommit_mode: str = "comprehensive"
52 @field_validator("package_path", mode="before")
53 @classmethod
54 def validate_package_path(cls, v: Any) -> Path:
55 if isinstance(v, str):
56 v = Path(v)
57 return v.resolve()
59 @field_validator("log_file", mode="before")
60 @classmethod
61 def validate_log_file(cls, v: Any) -> Path | None:
62 if v is None:
63 return v
64 if isinstance(v, str):
65 v = Path(v)
66 return v
68 @field_validator("test_workers")
69 @classmethod
70 def validate_test_workers(cls, v: int) -> int:
71 return max(1, min(v, 16))
73 @field_validator("min_coverage")
74 @classmethod
75 def validate_min_coverage(cls, v: float) -> float:
76 return max(0.0, min(v, 100.0))
78 @field_validator("log_level")
79 @classmethod
80 def validate_log_level(cls, v: str) -> str:
81 valid_levels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
82 if v.upper() not in valid_levels:
83 msg = f"Invalid log level: {v}. Must be one of {valid_levels}"
84 raise ValueError(msg)
85 return v.upper()
87 class Config:
88 extra = "allow"
90 use_enum_values = True
93class ConfigSource:
94 def __init__(self, priority: int = 0) -> None:
95 self.priority = priority
96 self.logger = get_logger("crackerjack.config.source")
98 def load(self) -> dict[str, Any]:
99 raise NotImplementedError
101 def is_available(self) -> bool:
102 return True
105class EnvironmentConfigSource(ConfigSource):
106 ENV_PREFIX = "CRACKERJACK_"
108 def __init__(self, priority: int = 100) -> None:
109 super().__init__(priority)
111 def load(self) -> dict[str, Any]:
112 config: dict[str, Any] = {}
114 for key, value in os.environ.items():
115 if key.startswith(self.ENV_PREFIX):
116 config_key = key[len(self.ENV_PREFIX) :].lower()
118 config[config_key] = self._convert_value(value)
120 self.logger.debug("Loaded environment config", keys=list(config.keys()))
121 return config
123 def _convert_value(self, value: str) -> Any:
124 if value.lower() in ("true", "1", "yes", "on"):
125 return True
126 if value.lower() in ("false", "0", "no", "off"):
127 return False
129 with suppress(ValueError):
130 return int(value)
132 with suppress(ValueError):
133 return float(value)
135 return value
138class FileConfigSource(ConfigSource):
139 def __init__(self, file_path: Path, priority: int = 50) -> None:
140 super().__init__(priority)
141 self.file_path = file_path
143 def is_available(self) -> bool:
144 return self.file_path.exists() and self.file_path.is_file()
146 def load(self) -> dict[str, Any]:
147 if not self.is_available():
148 return {}
150 try:
151 content = self.file_path.read_text()
153 if self.file_path.suffix.lower() in (".yml", ".yaml"):
154 yaml_result: t.Any = yaml.safe_load(content)
155 config = (
156 t.cast("dict[str, Any]", yaml_result)
157 if yaml_result is not None
158 else {}
159 )
160 elif self.file_path.suffix.lower() == ".json":
161 json_result = json.loads(content)
162 config = (
163 t.cast("dict[str, Any]", json_result)
164 if json_result is not None
165 else {}
166 )
167 else:
168 self.logger.warning(
169 "Unknown config file format",
170 path=str(self.file_path),
171 )
172 return {}
174 self.logger.debug(
175 "Loaded file config",
176 path=str(self.file_path),
177 keys=list(config.keys()),
178 )
179 return config
181 except Exception as e:
182 self.logger.exception(
183 "Failed to load config file",
184 path=str(self.file_path),
185 error=str(e),
186 )
187 return {}
190class PyprojectConfigSource(ConfigSource):
191 def __init__(self, pyproject_path: Path, priority: int = 25) -> None:
192 super().__init__(priority)
193 self.pyproject_path = pyproject_path
195 def is_available(self) -> bool:
196 return self.pyproject_path.exists() and self.pyproject_path.is_file()
198 def load(self) -> dict[str, Any]:
199 if not self.is_available():
200 return {}
202 try:
203 import tomllib
205 with self.pyproject_path.open("rb") as f:
206 pyproject_data = tomllib.load(f)
208 config = pyproject_data.get("tool", {}).get("crackerjack", {})
210 self.logger.debug("Loaded pyproject config", keys=list(config.keys()))
211 return config
213 except ImportError:
214 try:
215 import tomllib
217 with self.pyproject_path.open("rb") as f:
218 pyproject_data = tomllib.load(f)
219 config = pyproject_data.get("tool", {}).get("crackerjack", {})
220 self.logger.debug("Loaded pyproject config", keys=list(config.keys()))
221 return config
222 except ImportError:
223 self.logger.warning(
224 "No TOML library available for pyproject.toml parsing",
225 )
226 return {}
227 except Exception as e:
228 self.logger.exception("Failed to load pyproject.toml", error=str(e))
229 return {}
232class OptionsConfigSource(ConfigSource):
233 def __init__(self, options: OptionsProtocol, priority: int = 200) -> None:
234 super().__init__(priority)
235 self.options = options
237 def load(self) -> dict[str, Any]:
238 config: dict[str, Any] = {}
240 option_mappings = {
241 "testing": "test_mode",
242 "autofix": "autofix",
243 "skip_hooks": "skip_hooks",
244 "experimental_hooks": "experimental_hooks",
245 "test_timeout": "test_timeout",
246 "test_workers": "test_workers",
247 "benchmark": "benchmark_mode",
248 "publish": "publish_enabled",
249 "log_level": "log_level",
250 }
252 for option_attr, config_key in option_mappings.items():
253 if hasattr(self.options, option_attr):
254 value = getattr(self.options, option_attr)
255 if value is not None:
256 config[config_key] = value
258 self.logger.debug("Loaded options config", keys=list(config.keys()))
259 return config
262class UnifiedConfigurationService:
263 def __init__(
264 self,
265 console: Console,
266 pkg_path: Path,
267 options: OptionsProtocol | None = None,
268 ) -> None:
269 self.console = console
270 self.pkg_path = pkg_path
271 self.logger = get_logger("crackerjack.config.unified")
273 self.sources: list[ConfigSource] = []
275 pyproject_path = pkg_path / "pyproject.toml"
276 self.sources.extend(
277 (
278 self._create_default_source(),
279 PyprojectConfigSource(pyproject_path),
280 ),
281 )
283 self.sources.append(EnvironmentConfigSource())
285 if options:
286 self.sources.append(OptionsConfigSource(options))
288 self._config: CrackerjackConfig | None = None
290 def _create_default_source(self) -> ConfigSource:
291 pkg_path = self.pkg_path
293 class DefaultConfigSource(ConfigSource):
294 def load(self) -> dict[str, Any]:
295 return {
296 "package_path": pkg_path,
297 "cache_enabled": True,
298 "autofix": True,
299 "log_level": "INFO",
300 }
302 return DefaultConfigSource(priority=0)
304 def get_config(self, reload: bool = False) -> CrackerjackConfig:
305 if self._config is None or reload:
306 with LoggingContext("load_unified_config", source_count=len(self.sources)):
307 self._config = self._load_unified_config()
309 return self._config
311 def _load_unified_config(self) -> CrackerjackConfig:
312 merged_config: dict[str, Any] = {}
314 sorted_sources = sorted(self.sources, key=lambda s: s.priority)
316 for source in sorted_sources:
317 if source.is_available():
318 try:
319 source_config = source.load()
320 if source_config:
321 merged_config.update(source_config)
322 self.logger.debug(
323 "Merged config from source",
324 source_type=type(source).__name__,
325 priority=source.priority,
326 keys=list(source_config.keys()),
327 )
328 except Exception as e:
329 self.logger.exception(
330 "Failed to load config from source",
331 source_type=type(source).__name__,
332 error=str(e),
333 )
335 try:
336 config = CrackerjackConfig(**merged_config)
338 self.logger.info(
339 "Unified configuration loaded",
340 package_path=str(config.package_path),
341 cache_enabled=config.cache_enabled,
342 autofix=config.autofix,
343 async_hooks=config.enable_async_hooks,
344 test_workers=config.test_workers,
345 log_level=config.log_level,
346 )
348 return config
350 except Exception as e:
351 self.logger.exception("Configuration validation failed", error=str(e))
352 raise ValidationError(
353 message="Invalid configuration",
354 details=str(e),
355 recovery="Check configuration files and environment variables",
356 ) from e
358 def get_precommit_config_mode(self) -> str:
359 config = self.get_config()
361 if config.experimental_hooks:
362 return "experimental"
363 if hasattr(config, "test") and getattr(config, "test", False):
364 return "comprehensive"
365 return config.precommit_mode
367 def get_logging_config(self) -> dict[str, Any]:
368 config = self.get_config()
370 return {
371 "level": config.log_level,
372 "json_output": config.log_json,
373 "log_file": config.log_file,
374 "enable_correlation_ids": config.enable_correlation_ids,
375 }
377 def get_hook_execution_config(self) -> dict[str, Any]:
378 config = self.get_config()
380 return {
381 "batch_size": config.hook_batch_size,
382 "timeout": config.hook_timeout,
383 "max_concurrent": config.max_concurrent_hooks,
384 "enable_async": config.enable_async_hooks,
385 "autofix": config.autofix,
386 "skip_hooks": config.skip_hooks,
387 }
389 def get_testing_config(self) -> dict[str, Any]:
390 config = self.get_config()
392 return {
393 "timeout": config.test_timeout,
394 "workers": config.test_workers,
395 "min_coverage": config.min_coverage,
396 }
398 def get_cache_config(self) -> dict[str, Any]:
399 config = self.get_config()
401 return {
402 "enabled": config.cache_enabled,
403 "size": config.cache_size,
404 "ttl": config.cache_ttl,
405 "batch_operations": config.batch_file_operations,
406 "batch_size": config.file_operation_batch_size,
407 }
409 def validate_current_config(self) -> bool:
410 try:
411 config = self.get_config()
413 validation_errors: list[str] = []
415 if config.test_workers <= 0:
416 validation_errors.append("test_workers must be positive")
418 if config.min_coverage < 0 or config.min_coverage > 100:
419 validation_errors.append("min_coverage must be between 0 and 100")
421 if config.cache_size <= 0:
422 validation_errors.append("cache_size must be positive")
424 if validation_errors:
425 for error in validation_errors:
426 self.logger.error("Configuration validation error", error=error)
427 return False
429 self.logger.info("Configuration validation passed")
430 return True
432 except Exception as e:
433 self.logger.exception("Configuration validation failed", error=str(e))
434 return False