Files
Py-Backup/config_manager.py

75 lines
2.2 KiB
Python

import json
from pathlib import Path
from typing import Any, Dict
class ConfigManager:
"""Manages loading and saving of application settings in a JSON file."""
def __init__(self, file_path: Path):
"""
Initializes the ConfigManager.
Args:
file_path: The path to the configuration file.
"""
self.file_path = file_path
self.settings: Dict[str, Any] = {}
self.load()
def load(self) -> None:
"""Loads the settings from the JSON file."""
if self.file_path.exists():
try:
with open(self.file_path, 'r', encoding='utf-8') as f:
self.settings = json.load(f)
except (IOError, json.JSONDecodeError) as e:
print(f"Error loading config file {self.file_path}: {e}")
self.settings = {}
else:
self.settings = {}
def save(self) -> None:
"""Saves the current settings to the JSON file."""
try:
# Ensure the parent directory exists
self.file_path.parent.mkdir(parents=True, exist_ok=True)
with open(self.file_path, 'w', encoding='utf-8') as f:
json.dump(self.settings, f, indent=4)
except IOError as e:
print(f"Error saving config file {self.file_path}: {e}")
def get_setting(self, key: str, default: Any = None) -> Any:
"""
Gets a setting value.
Args:
key: The key of the setting.
default: The default value to return if the key is not found.
Returns:
The value of the setting or the default value.
"""
return self.settings.get(key, default)
def set_setting(self, key: str, value: Any) -> None:
"""
Sets a setting value and immediately saves it to the file.
Args:
key: The key of the setting.
value: The value to set.
"""
self.settings[key] = value
self.save()
def remove_setting(self, key: str) -> None:
"""
Removes a setting from the configuration.
Args:
key: The key of the setting to remove.
"""
if key in self.settings:
del self.settings[key]
self.save()