|
| 1 | +"""Configuration loading and merging for CPPython |
| 2 | +
|
| 3 | +This module handles loading configuration from multiple sources: |
| 4 | +1. Global configuration (~/.cppython/config.toml) - User-wide settings for all projects |
| 5 | +2. Project configuration (pyproject.toml or cppython.toml) - Project-specific settings |
| 6 | +3. Local overrides (.cppython.toml) - Overrides for global configuration |
| 7 | +""" |
| 8 | + |
| 9 | +from pathlib import Path |
| 10 | +from tomllib import loads |
| 11 | +from typing import Any |
| 12 | + |
| 13 | + |
| 14 | +class ConfigurationLoader: |
| 15 | + """Loads and merges CPPython configuration from multiple sources""" |
| 16 | + |
| 17 | + def __init__(self, project_root: Path) -> None: |
| 18 | + """Initialize the configuration loader |
| 19 | +
|
| 20 | + Args: |
| 21 | + project_root: The root directory of the project |
| 22 | + """ |
| 23 | + self.project_root = project_root |
| 24 | + self.pyproject_path = project_root / 'pyproject.toml' |
| 25 | + self.cppython_path = project_root / 'cppython.toml' |
| 26 | + self.local_override_path = project_root / '.cppython.toml' |
| 27 | + self.global_config_path = Path.home() / '.cppython' / 'config.toml' |
| 28 | + |
| 29 | + def load_pyproject_data(self) -> dict[str, Any]: |
| 30 | + """Load complete pyproject.toml data |
| 31 | +
|
| 32 | + Returns: |
| 33 | + Dictionary containing the full pyproject.toml data |
| 34 | +
|
| 35 | + Raises: |
| 36 | + FileNotFoundError: If pyproject.toml does not exist |
| 37 | + """ |
| 38 | + if not self.pyproject_path.exists(): |
| 39 | + raise FileNotFoundError(f'pyproject.toml not found at {self.pyproject_path}') |
| 40 | + |
| 41 | + return loads(self.pyproject_path.read_text(encoding='utf-8')) |
| 42 | + |
| 43 | + def load_cppython_config(self) -> dict[str, Any] | None: |
| 44 | + """Load CPPython configuration from cppython.toml if it exists |
| 45 | +
|
| 46 | + Returns: |
| 47 | + Dictionary containing the cppython table data, or None if file doesn't exist |
| 48 | + """ |
| 49 | + if not self.cppython_path.exists(): |
| 50 | + return None |
| 51 | + |
| 52 | + data = loads(self.cppython_path.read_text(encoding='utf-8')) |
| 53 | + |
| 54 | + # Validate that it contains a cppython table |
| 55 | + if 'cppython' not in data: |
| 56 | + raise ValueError(f'{self.cppython_path} must contain a [cppython] table') |
| 57 | + |
| 58 | + return data['cppython'] |
| 59 | + |
| 60 | + def load_global_config(self) -> dict[str, Any] | None: |
| 61 | + """Load global configuration from ~/.cppython/config.toml if it exists |
| 62 | +
|
| 63 | + Returns: |
| 64 | + Dictionary containing the global configuration, or None if file doesn't exist |
| 65 | + """ |
| 66 | + if not self.global_config_path.exists(): |
| 67 | + return None |
| 68 | + |
| 69 | + data = loads(self.global_config_path.read_text(encoding='utf-8')) |
| 70 | + |
| 71 | + # Validate that it contains a cppython table |
| 72 | + if 'cppython' not in data: |
| 73 | + raise ValueError(f'{self.global_config_path} must contain a [cppython] table') |
| 74 | + |
| 75 | + return data['cppython'] |
| 76 | + |
| 77 | + def load_local_overrides(self) -> dict[str, Any] | None: |
| 78 | + """Load local overrides from .cppython.toml if it exists |
| 79 | +
|
| 80 | + These overrides only affect the global configuration, not project configuration. |
| 81 | +
|
| 82 | + Returns: |
| 83 | + Dictionary containing local override data, or None if file doesn't exist |
| 84 | + """ |
| 85 | + if not self.local_override_path.exists(): |
| 86 | + return None |
| 87 | + |
| 88 | + return loads(self.local_override_path.read_text(encoding='utf-8')) |
| 89 | + |
| 90 | + def merge_configurations(self, base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]: |
| 91 | + """Deep merge two configuration dictionaries |
| 92 | +
|
| 93 | + Args: |
| 94 | + base: Base configuration dictionary |
| 95 | + override: Override configuration dictionary |
| 96 | +
|
| 97 | + Returns: |
| 98 | + Merged configuration with overrides taking precedence |
| 99 | + """ |
| 100 | + result = base.copy() |
| 101 | + |
| 102 | + for key, value in override.items(): |
| 103 | + if key in result and isinstance(result[key], dict) and isinstance(value, dict): |
| 104 | + # Recursively merge nested dictionaries |
| 105 | + result[key] = self.merge_configurations(result[key], value) |
| 106 | + else: |
| 107 | + # Override value |
| 108 | + result[key] = value |
| 109 | + |
| 110 | + return result |
| 111 | + |
| 112 | + def load_cppython_table(self) -> dict[str, Any] | None: |
| 113 | + """Load and merge the CPPython configuration table from all sources |
| 114 | +
|
| 115 | + Priority (highest to lowest): |
| 116 | + 1. Project configuration (pyproject.toml or cppython.toml) |
| 117 | + 2. Local overrides (.cppython.toml) merged with global config |
| 118 | + 3. Global configuration (~/.cppython/config.toml) |
| 119 | +
|
| 120 | + Returns: |
| 121 | + Merged CPPython configuration dictionary, or None if no config found |
| 122 | + """ |
| 123 | + # Start with global configuration |
| 124 | + global_config = self.load_global_config() |
| 125 | + |
| 126 | + # Apply local overrides to global config |
| 127 | + local_overrides = self.load_local_overrides() |
| 128 | + if local_overrides is not None and global_config is not None: |
| 129 | + global_config = self.merge_configurations(global_config, local_overrides) |
| 130 | + elif local_overrides is not None and global_config is None: |
| 131 | + # Local overrides exist but no global config - use overrides as base |
| 132 | + global_config = local_overrides |
| 133 | + |
| 134 | + # Load project configuration (pyproject.toml or cppython.toml) |
| 135 | + pyproject_data = self.load_pyproject_data() |
| 136 | + project_config = pyproject_data.get('tool', {}).get('cppython') |
| 137 | + |
| 138 | + # Try cppython.toml as alternative |
| 139 | + cppython_toml_config = self.load_cppython_config() |
| 140 | + if cppython_toml_config is not None: |
| 141 | + if project_config is not None: |
| 142 | + raise ValueError( |
| 143 | + 'CPPython configuration found in both pyproject.toml and cppython.toml. ' |
| 144 | + 'Please use only one configuration source.' |
| 145 | + ) |
| 146 | + project_config = cppython_toml_config |
| 147 | + |
| 148 | + # Merge: global config (with local overrides) + project config |
| 149 | + # Project config has highest priority |
| 150 | + if project_config is not None and global_config is not None: |
| 151 | + return self.merge_configurations(global_config, project_config) |
| 152 | + elif project_config is not None: |
| 153 | + return project_config |
| 154 | + elif global_config is not None: |
| 155 | + return global_config |
| 156 | + |
| 157 | + return None |
| 158 | + |
| 159 | + def get_project_data(self) -> dict[str, Any]: |
| 160 | + """Get the complete pyproject data with merged CPPython configuration |
| 161 | +
|
| 162 | + Returns: |
| 163 | + Dictionary containing pyproject data with merged tool.cppython table |
| 164 | + """ |
| 165 | + pyproject_data = self.load_pyproject_data() |
| 166 | + |
| 167 | + # Load merged CPPython config |
| 168 | + cppython_config = self.load_cppython_table() |
| 169 | + |
| 170 | + # Update the pyproject data with merged config |
| 171 | + if cppython_config is not None: |
| 172 | + if 'tool' not in pyproject_data: |
| 173 | + pyproject_data['tool'] = {} |
| 174 | + pyproject_data['tool']['cppython'] = cppython_config |
| 175 | + |
| 176 | + return pyproject_data |
| 177 | + |
| 178 | + def config_source_info(self) -> dict[str, bool]: |
| 179 | + """Get information about which configuration files exist |
| 180 | +
|
| 181 | + Returns: |
| 182 | + Dictionary with boolean flags for each config file's existence |
| 183 | + """ |
| 184 | + return { |
| 185 | + 'global_config': self.global_config_path.exists(), |
| 186 | + 'pyproject': self.pyproject_path.exists(), |
| 187 | + 'cppython': self.cppython_path.exists(), |
| 188 | + 'local_overrides': self.local_override_path.exists(), |
| 189 | + } |
0 commit comments