config_manager.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import os
  2. import shutil
  3. from typing import Any, Dict, Tuple
  4. import toml
  5. DEFAULT_CONFIG_PATH = "./config.toml"
  6. def load_config(filepath: str) -> Dict[str, Any]:
  7. """Reads and parses a TOML configuration file."""
  8. with open(filepath, "r") as f:
  9. return toml.load(f)
  10. def save_config(filepath: str, config: Dict[str, Any]) -> None:
  11. """Saves a dictionary to a TOML configuration file."""
  12. os.makedirs(os.path.dirname(filepath), exist_ok=True)
  13. with open(filepath, "w") as f:
  14. toml.dump(config, f)
  15. def handle_directory_config(work_dir: str) -> Tuple[bool, str, Dict[str, Any]]:
  16. """
  17. Checks the directory, loads an existing config, or copies the default one.
  18. Returns:
  19. Tuple containing: (Success boolean, Status message, Configuration Dictionary)
  20. """
  21. if not work_dir:
  22. return False, "Please specify a working directory.", {}
  23. config_path = os.path.join(work_dir, "config.toml")
  24. # 1. If config exists, load it
  25. if os.path.exists(config_path):
  26. try:
  27. conf = load_config(config_path)
  28. return True, f"Successfully loaded config from {config_path}", conf
  29. except Exception as e:
  30. return False, f"Failed to load config: {str(e)}", {}
  31. # 2. If it doesn't exist, create directory and copy default config
  32. else:
  33. try:
  34. os.makedirs(work_dir, exist_ok=True)
  35. if not os.path.exists(DEFAULT_CONFIG_PATH):
  36. return (
  37. False,
  38. f"Default config not found at {DEFAULT_CONFIG_PATH} to copy!",
  39. {},
  40. )
  41. shutil.copy(DEFAULT_CONFIG_PATH, config_path)
  42. conf = load_config(config_path)
  43. return (
  44. True,
  45. f"Copied default config to {config_path}. Ready for editing!",
  46. conf,
  47. )
  48. except Exception as e:
  49. return False, f"Failed to initialize directory/config: {str(e)}", {}