|
| 1 | +"""Configuration module for ref-utils with testable path abstraction.""" |
| 2 | +from contextlib import contextmanager |
| 3 | +from contextvars import ContextVar |
| 4 | +from dataclasses import dataclass, field |
| 5 | +from pathlib import Path |
| 6 | +from typing import Generator |
| 7 | + |
| 8 | + |
| 9 | +@dataclass |
| 10 | +class Config: |
| 11 | + """Configuration for ref-utils paths and constants. |
| 12 | +
|
| 13 | + All container-specific paths are configurable here to enable testing |
| 14 | + without requiring a container environment. |
| 15 | + """ |
| 16 | + |
| 17 | + user_environ_path: Path = field(default_factory=lambda: Path("/tmp/.user_environ")) |
| 18 | + pylint_config_path: Path = field(default_factory=lambda: Path("/etc/pylintrc")) |
| 19 | + mypy_config_path: Path = field(default_factory=lambda: Path("/etc/mypyrc")) |
| 20 | + user_home_path: Path = field(default_factory=lambda: Path("/home/user")) |
| 21 | + drop_uid: int = 9999 |
| 22 | + drop_gid: int = 9999 |
| 23 | + |
| 24 | + |
| 25 | +# Context variable for thread-safe config override |
| 26 | +_config_var: ContextVar[Config] = ContextVar("config", default=Config()) |
| 27 | + |
| 28 | + |
| 29 | +def get_config() -> Config: |
| 30 | + """Get the current configuration.""" |
| 31 | + return _config_var.get() |
| 32 | + |
| 33 | + |
| 34 | +def set_config(config: Config) -> None: |
| 35 | + """Set the global configuration.""" |
| 36 | + _config_var.set(config) |
| 37 | + |
| 38 | + |
| 39 | +@contextmanager |
| 40 | +def override_config(config: Config) -> Generator[Config, None, None]: |
| 41 | + """Context manager for temporarily overriding config (useful for testing). |
| 42 | +
|
| 43 | + Args: |
| 44 | + config: The temporary configuration to use. |
| 45 | +
|
| 46 | + Yields: |
| 47 | + The provided config object. |
| 48 | + """ |
| 49 | + token = _config_var.set(config) |
| 50 | + try: |
| 51 | + yield config |
| 52 | + finally: |
| 53 | + _config_var.reset(token) |
0 commit comments