config.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. """
  2. Configuration management for the Boilerplates CLI.
  3. Handles module-specific configuration stored in config.json files.
  4. """
  5. import json
  6. import os
  7. from pathlib import Path
  8. from typing import Any, Dict, Optional
  9. from .logging import setup_logging
  10. class ConfigManager:
  11. """Manages configuration for CLI modules."""
  12. def __init__(self, module_name: str):
  13. self.module_name = module_name
  14. self.config_dir = Path.home() / ".boilerplates"
  15. self.config_file = self.config_dir / f"{module_name}.json"
  16. self.logger = setup_logging()
  17. def _ensure_config_dir(self) -> None:
  18. """Ensure the configuration directory exists."""
  19. self.config_dir.mkdir(parents=True, exist_ok=True)
  20. def _load_config(self) -> Dict[str, Any]:
  21. """Load configuration from file."""
  22. if not self.config_file.exists():
  23. return {}
  24. try:
  25. with open(self.config_file, 'r', encoding='utf-8') as f:
  26. return json.load(f)
  27. except (json.JSONDecodeError, IOError) as e:
  28. self.logger.warning(f"Failed to load config for {self.module_name}: {e}")
  29. return {}
  30. def _save_config(self, config: Dict[str, Any]) -> None:
  31. """Save configuration to file."""
  32. self._ensure_config_dir()
  33. try:
  34. with open(self.config_file, 'w', encoding='utf-8') as f:
  35. json.dump(config, f, indent=2, ensure_ascii=False)
  36. except IOError as e:
  37. self.logger.error(f"Failed to save config for {self.module_name}: {e}")
  38. raise
  39. def get(self, key: str, default: Any = None) -> Any:
  40. """Get a configuration value."""
  41. config = self._load_config()
  42. return config.get(key, default)
  43. def set(self, key: str, value: Any) -> None:
  44. """Set a configuration value."""
  45. config = self._load_config()
  46. config[key] = value
  47. self._save_config(config)
  48. def delete(self, key: str) -> bool:
  49. """Delete a configuration value."""
  50. config = self._load_config()
  51. if key in config:
  52. del config[key]
  53. self._save_config(config)
  54. return True
  55. return False
  56. def list_all(self) -> Dict[str, Any]:
  57. """List all configuration values."""
  58. return self._load_config()
  59. def get_config_path(self) -> Path:
  60. """Get the path to the configuration file."""
  61. return self.config_file