| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- import os
- import shutil
- from typing import Any, Dict, Tuple
- import toml
- DEFAULT_CONFIG_PATH = "./config.toml"
- def load_config(filepath: str) -> Dict[str, Any]:
- """Reads and parses a TOML configuration file."""
- with open(filepath, "r") as f:
- return toml.load(f)
- def save_config(filepath: str, config: Dict[str, Any]) -> None:
- """Saves a dictionary to a TOML configuration file."""
- os.makedirs(os.path.dirname(filepath), exist_ok=True)
- with open(filepath, "w") as f:
- toml.dump(config, f)
- def handle_directory_config(work_dir: str) -> Tuple[bool, str, Dict[str, Any]]:
- """
- Checks the directory, loads an existing config, or copies the default one.
- Returns:
- Tuple containing: (Success boolean, Status message, Configuration Dictionary)
- """
- if not work_dir:
- return False, "Please specify a working directory.", {}
- config_path = os.path.join(work_dir, "config.toml")
- # 1. If config exists, load it
- if os.path.exists(config_path):
- try:
- conf = load_config(config_path)
- return True, f"Successfully loaded config from {config_path}", conf
- except Exception as e:
- return False, f"Failed to load config: {str(e)}", {}
- # 2. If it doesn't exist, create directory and copy default config
- else:
- try:
- os.makedirs(work_dir, exist_ok=True)
- if not os.path.exists(DEFAULT_CONFIG_PATH):
- return (
- False,
- f"Default config not found at {DEFAULT_CONFIG_PATH} to copy!",
- {},
- )
- shutil.copy(DEFAULT_CONFIG_PATH, config_path)
- conf = load_config(config_path)
- return (
- True,
- f"Copied default config to {config_path}. Ready for editing!",
- conf,
- )
- except Exception as e:
- return False, f"Failed to initialize directory/config: {str(e)}", {}
|