diff --git a/configforge/formatters/toml_handler.py b/configforge/formatters/toml_handler.py new file mode 100644 index 0000000..08cd0c1 --- /dev/null +++ b/configforge/formatters/toml_handler.py @@ -0,0 +1,52 @@ +"""TOML format handler for ConfigForge.""" + +import tomlkit +from typing import Any, Dict + +from configforge.exceptions import ConversionError + + +class TOMLHandler: + """Handler for TOML configuration files.""" + + @staticmethod + def loads(content: str) -> Dict[str, Any]: + """Parse TOML content.""" + try: + return tomlkit.loads(content) + except tomlkit.exceptions.ParseError as e: + raise ConversionError(f"Invalid TOML: {str(e)}") from e + + @staticmethod + def dumps(data: Any) -> str: + """Serialize data to TOML string.""" + try: + return tomlkit.dumps(data) + except (TypeError, ValueError) as e: + raise ConversionError(f"Failed to serialize TOML: {str(e)}") from e + + @staticmethod + def read(filepath: str) -> Dict[str, Any]: + """Read and parse TOML file.""" + try: + with open(filepath, "r", encoding="utf-8") as f: + return tomlkit.load(f) + except FileNotFoundError: + raise ConversionError(f"File not found: {filepath}") + except PermissionError: + raise ConversionError(f"Permission denied: {filepath}") + except tomlkit.exceptions.ParseError as e: + raise ConversionError(f"Invalid TOML in {filepath}: {str(e)}") from e + + @staticmethod + def write(filepath: str, data: Any) -> None: + """Write data to TOML file.""" + try: + with open(filepath, "w", encoding="utf-8") as f: + tomlkit.dump(data, f) + except FileNotFoundError: + raise ConversionError(f"Directory not found for: {filepath}") + except PermissionError: + raise ConversionError(f"Permission denied to write: {filepath}") + except (TypeError, ValueError) as e: + raise ConversionError(f"Failed to write TOML: {str(e)}") from e