Loads and manages configuration for CodeMap using Pydantic schemas.
This class handles loading configuration from files, applying defaults
from Pydantic models, with proper error handling and path
resolution.
Source code in src/codemap/config/config_loader.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222 | class ConfigLoader:
"""
Loads and manages configuration for CodeMap using Pydantic schemas.
This class handles loading configuration from files, applying defaults
from Pydantic models, with proper error handling and path
resolution.
"""
_instance = None
@classmethod
def get_instance(
cls,
) -> "ConfigLoader":
"""
Get the singleton instance of ConfigLoader.
Returns:
ConfigLoader: Singleton instance
"""
if cls._instance is None:
cls._instance = cls()
return cls._instance
def __init__(self) -> None:
"""
Initialize the configuration loader.
Args:
config_file: Path to configuration file (optional)
repo_root: Repository root path (optional)
"""
# Load configuration eagerly during initialization instead of lazy loading
self._app_config = self._load_config()
logger.debug("ConfigLoader initialized with eager configuration loading")
def _get_config_file(self) -> Path | None:
"""
Resolve the configuration file path.
look in standard locations:
1. ./.codemap.yml in the current directory
2. ./.codemap.yml in the repository root
Args:
config_file: Explicitly provided config file path (optional)
Returns:
Optional[Path]: Resolved config file path or None if no suitable file found
"""
# Import GitRepoContext here to avoid circular imports
from codemap.git.utils import GitRepoContext
# Try current directory
local_config = Path(".codemap.yml")
if local_config.exists():
self.repo_root = local_config.parent
return local_config
# Try repository root
repo_root = GitRepoContext().get_repo_root()
self.repo_root = repo_root
repo_config = repo_root / ".codemap.yml"
if repo_config.exists():
return repo_config
# If we get here, no config file was found
return None
@staticmethod
def _parse_yaml_file(file_path: Path) -> dict[str, Any]:
"""
Parse a YAML file with caching for better performance.
Args:
file_path: Path to the YAML file to parse
Returns:
Parsed YAML content as a dictionary
Raises:
yaml.YAMLError: If the file cannot be parsed as valid YAML
"""
with file_path.open(encoding="utf-8") as f:
content = yaml.safe_load(f)
if content is None: # Empty file
return {}
if not isinstance(content, dict):
msg = f"File {file_path} does not contain a valid YAML dictionary"
raise yaml.YAMLError(msg)
return content
def _load_config(self) -> AppConfigSchema:
"""
Load configuration from file and parse it into AppConfigSchema.
Returns:
AppConfigSchema: Loaded and parsed configuration.
Raises:
ConfigFileNotFoundError: If specified configuration file doesn't exist
ConfigParsingError: If configuration file exists but cannot be loaded or parsed.
"""
# Lazy imports
import yaml
from codemap.config import AppConfigSchema
file_config_dict: dict[str, Any] = {}
config_file = self._get_config_file()
if config_file:
try:
if config_file.exists():
try:
file_config_dict = self._parse_yaml_file(config_file)
logger.info("Loaded configuration from %s", config_file)
except yaml.YAMLError as e:
msg = f"Configuration file {config_file} does not contain a valid YAML dictionary."
logger.exception(msg)
raise ConfigParsingError(msg) from e
else:
msg = f"Configuration file not found: {config_file}."
logger.info("%s Using default configuration.", msg)
except OSError as e:
error_msg = f"Error accessing configuration file {config_file}: {e}"
logger.exception(error_msg)
raise ConfigParsingError(error_msg) from e
else:
logger.info("No configuration file specified or found. Using default configuration.")
file_config_dict["repo_root"] = self.repo_root
try:
# Initialize AppConfigSchema. If file_config_dict is empty, defaults will be used.
config = AppConfigSchema(**file_config_dict)
# Override github.token with env var if set
env_token = os.environ.get("GITHUB_TOKEN") or os.environ.get("CODEMAP_GITHUB_TOKEN")
if env_token:
config.github.token = env_token
return config
except Exception as e: # Catch Pydantic validation errors etc.
error_msg = f"Error parsing configuration into schema: {e}"
logger.exception(error_msg)
raise ConfigParsingError(error_msg) from e
def _merge_configs(self, base: dict[str, Any], override: dict[str, Any]) -> None:
"""
Recursively merge two configuration dictionaries.
Args:
base: Base configuration dictionary to merge into
override: Override configuration to apply
"""
for key, value in override.items():
if isinstance(value, dict) and key in base and isinstance(base[key], dict):
self._merge_configs(base[key], value)
else:
base[key] = value
@property
def get(self) -> AppConfigSchema:
"""
Get the current application configuration.
Returns:
AppConfigSchema: The current configuration
"""
# Configuration is now loaded during initialization, no need for lazy loading
return self._app_config
|
get_instance
classmethod
Get the singleton instance of ConfigLoader.
Returns:
Source code in src/codemap/config/config_loader.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71 | @classmethod
def get_instance(
cls,
) -> "ConfigLoader":
"""
Get the singleton instance of ConfigLoader.
Returns:
ConfigLoader: Singleton instance
"""
if cls._instance is None:
cls._instance = cls()
return cls._instance
|
__init__
Initialize the configuration loader.
Parameters:
Name |
Type |
Description |
Default |
config_file
|
|
Path to configuration file (optional)
|
required
|
repo_root
|
|
Repository root path (optional)
|
required
|
Source code in src/codemap/config/config_loader.py
73
74
75
76
77
78
79
80
81
82
83
84 | def __init__(self) -> None:
"""
Initialize the configuration loader.
Args:
config_file: Path to configuration file (optional)
repo_root: Repository root path (optional)
"""
# Load configuration eagerly during initialization instead of lazy loading
self._app_config = self._load_config()
logger.debug("ConfigLoader initialized with eager configuration loading")
|
get
property
Get the current application configuration.
Returns:
Name | Type |
Description |
AppConfigSchema |
AppConfigSchema
|
The current configuration
|