SXXXXXXX_RadarDataReader/radar_data_reader/utils/config_manager.py
VALLONGOL 0399e98b79 Chore: Stop tracking files based on .gitignore update.
Untracked files matching the following rules:
- Rule "!.vscode/launch.json": 1 file
2025-06-18 11:18:36 +02:00

72 lines
2.6 KiB
Python

"""
Configuration Manager for the application.
Handles loading and saving of application settings to a JSON file.
"""
import json
from pathlib import Path
from typing import Dict, Any, Optional
from . import logger
log = logger.get_logger(__name__)
class ConfigManager:
"""Manages loading and saving configuration from/to a JSON file."""
def __init__(self, config_path: Path):
"""
Initializes the ConfigManager.
Args:
config_path: The path to the configuration file.
"""
self.config_path: Path = config_path
self.config: Dict[str, Any] = self._get_default_config()
@staticmethod
def _get_default_config() -> Dict[str, Any]:
"""Provides the default configuration structure."""
return {
"last_opened_file": ""
}
def load_config(self) -> None:
"""
Loads the configuration from the JSON file.
If the file does not exist, it starts with the default configuration.
"""
log.info(f"Attempting to load configuration from: {self.config_path}")
if self.config_path.is_file():
try:
with open(self.config_path, 'r', encoding='utf-8') as f:
loaded_data = json.load(f)
# Merge loaded data with defaults to ensure all keys exist
self.config.update(loaded_data)
log.info("Configuration loaded successfully.")
except (json.JSONDecodeError, IOError) as e:
log.error(f"Failed to load or parse config file: {e}. Using defaults.")
self.config = self._get_default_config()
else:
log.warning("Configuration file not found. Using default settings.")
self.config = self._get_default_config()
def save_config(self) -> None:
"""Saves the current configuration to the JSON file."""
log.info(f"Saving configuration to: {self.config_path}")
try:
# Ensure the parent directory exists
self.config_path.parent.mkdir(parents=True, exist_ok=True)
with open(self.config_path, 'w', encoding='utf-8') as f:
json.dump(self.config, f, indent=4)
log.info("Configuration saved successfully.")
except IOError as e:
log.error(f"Failed to save configuration file: {e}")
def get(self, key: str, default: Optional[Any] = None) -> Any:
"""Gets a value from the configuration."""
return self.config.get(key, default)
def set(self, key: str, value: Any) -> None:
"""Sets a value in the configuration."""
self.config[key] = value