|
| 1 | +# src/utils/config_loader.py |
| 2 | + |
| 3 | +import os |
| 4 | +import json |
| 5 | +import yaml |
| 6 | +import logging |
| 7 | + |
| 8 | +# Set up logging for the config loader |
| 9 | +logger = logging.getLogger(__name__) |
| 10 | + |
| 11 | +class ConfigLoader: |
| 12 | + def __init__(self, config_file=None): |
| 13 | + """ |
| 14 | + Initialize the ConfigLoader. |
| 15 | +
|
| 16 | + Parameters: |
| 17 | + - config_file (str): Path to the configuration file (JSON or YAML). |
| 18 | + """ |
| 19 | + self.config_file = config_file |
| 20 | + self.config = {} |
| 21 | + logger.info("ConfigLoader initialized.") |
| 22 | + |
| 23 | + if config_file: |
| 24 | + self.load_config(config_file) |
| 25 | + |
| 26 | + def load_config(self, config_file): |
| 27 | + """ |
| 28 | + Load configuration from a specified file. |
| 29 | +
|
| 30 | + Parameters: |
| 31 | + - config_file (str): Path to the configuration file (JSON or YAML). |
| 32 | +
|
| 33 | + Raises: |
| 34 | + - ValueError: If the file format is unsupported or if loading fails. |
| 35 | + """ |
| 36 | + try: |
| 37 | + if config_file.endswith('.json'): |
| 38 | + with open(config_file, 'r') as f: |
| 39 | + self.config = json.load(f) |
| 40 | + logger.info(f"Configuration loaded from JSON file: {config_file}") |
| 41 | + elif config_file.endswith('.yaml') or config_file.endswith('.yml'): |
| 42 | + with open(config_file, 'r') as f: |
| 43 | + self.config = yaml.safe_load(f) |
| 44 | + logger.info(f"Configuration loaded from YAML file: {config_file}") |
| 45 | + else: |
| 46 | + logger.error("Unsupported configuration file format. Use .json or .yaml/.yml.") |
| 47 | + raise ValueError("Unsupported configuration file format. Use .json or .yaml/.yml.") |
| 48 | + except Exception as e: |
| 49 | + logger.error(f"Failed to load configuration from {config_file}: {e}") |
| 50 | + raise |
| 51 | + |
| 52 | + def get(self, key, default=None): |
| 53 | + """ |
| 54 | + Get a configuration value by key. |
| 55 | +
|
| 56 | + Parameters: |
| 57 | + - key (str): The key of the configuration value to retrieve. |
| 58 | + - default: The default value to return if the key is not found. |
| 59 | +
|
| 60 | + Returns: |
| 61 | + - The configuration value or the default value if the key is not found. |
| 62 | + """ |
| 63 | + value = self.config.get(key, default) |
| 64 | + logger.info(f"Retrieved config value for '{key}': {value}") |
| 65 | + return value |
| 66 | + |
| 67 | + def load_env_variables(self): |
| 68 | + """ |
| 69 | + Load configuration values from environment variables. |
| 70 | +
|
| 71 | + This method assumes that environment variables are named in uppercase |
| 72 | + and match the keys in the configuration. |
| 73 | + """ |
| 74 | + for key in self.config.keys(): |
| 75 | + env_value = os.getenv(key.upper()) |
| 76 | + if env_value is not None: |
| 77 | + self.config[key] = env_value |
| 78 | + logger.info(f"Loaded environment variable for '{key}': {env_value}") |
| 79 | + |
| 80 | + def save_config(self, config_file=None): |
| 81 | + """ |
| 82 | + Save the current configuration to a specified file. |
| 83 | +
|
| 84 | + Parameters: |
| 85 | + - config_file (str): Path to the configuration file (JSON or YAML). If None, uses the original config_file. |
| 86 | + """ |
| 87 | + if config_file is None: |
| 88 | + config_file = self.config_file |
| 89 | + |
| 90 | + try: |
| 91 | + if config_file.endswith('.json'): |
| 92 | + with open(config_file, 'w') as f: |
| 93 | + json.dump(self.config, f, indent=4) |
| 94 | + logger.info(f"Configuration saved to JSON file: {config_file}") |
| 95 | + elif config_file.endswith('.yaml') or config_file.endswith('.yml'): |
| 96 | + with open(config_file, 'w') as f: |
| 97 | + yaml.dump(self.config, f) |
| 98 | + logger.info(f"Configuration saved to YAML file: {config_file}") |
| 99 | + else: |
| 100 | + logger.error("Unsupported configuration file format. Use .json or .yaml/.yml.") |
| 101 | + raise ValueError("Unsupported configuration file format. Use .json or .yaml/.yml.") |
| 102 | + except Exception as e: |
| 103 | + logger.error(f"Failed to save configuration to {config_file}: {e}") |
| 104 | + raise |
0 commit comments