From adedcd4332ef2bc5109b704d43198de698c52969 Mon Sep 17 00:00:00 2001 From: 7000pctAUTO Date: Wed, 4 Feb 2026 21:54:22 +0000 Subject: [PATCH] Add source code files --- config_converter/converters/toml_converter.py | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 config_converter/converters/toml_converter.py diff --git a/config_converter/converters/toml_converter.py b/config_converter/converters/toml_converter.py new file mode 100644 index 0000000..e5846a9 --- /dev/null +++ b/config_converter/converters/toml_converter.py @@ -0,0 +1,56 @@ +"""TOML format converter.""" + +from pathlib import Path +from typing import Any, Dict + +import tomlkit +from tomlkit import TOMLDocument + +from config_converter.converters.base import BaseConverter, ConversionError + + +class TomlConverter(BaseConverter): + """Converter for TOML configuration files.""" + + FORMAT_NAME = "toml" + FILE_EXTENSIONS = ["toml"] + + def read(self, source: str | Path) -> Dict[str, Any]: + """Read and parse a TOML configuration file.""" + try: + with open(source, "r", encoding="utf-8") as f: + return tomlkit.parse(f.read()) + except tomlkit.exceptions.ParseError as e: + raise ConversionError(f"Invalid TOML in {source}: {e}") from e + except FileNotFoundError as e: + raise ConversionError(f"File not found: {source}") from e + except PermissionError as e: + raise ConversionError(f"Permission denied: {source}") from e + + def write(self, data: Dict[str, Any], target: str | Path) -> None: + """Write configuration data to a TOML file.""" + try: + doc: TOMLDocument = tomlkit.document() + for key, value in data.items(): + doc[key] = value + with open(target, "w", encoding="utf-8") as f: + f.write(tomlkit.dumps(doc)) + except (OSError, TypeError, tomlkit.exceptions.TypeError) as e: + raise ConversionError(f"Failed to write TOML to {target}: {e}") from e + + def parse(self, content: str) -> Dict[str, Any]: + """Parse TOML content from a string.""" + try: + return tomlkit.parse(content) + except tomlkit.exceptions.ParseError as e: + raise ConversionError(f"Invalid TOML content: {e}") from e + + def format(self, data: Dict[str, Any]) -> str: + """Format configuration data to a TOML string.""" + try: + doc: TOMLDocument = tomlkit.document() + for key, value in data.items(): + doc[key] = value + return tomlkit.dumps(doc) + except (TypeError, ValueError, tomlkit.exceptions.TypeError) as e: + raise ConversionError(f"Failed to format data as TOML: {e}") from e