Add source code files
Some checks failed
CI / test (push) Has been cancelled

This commit is contained in:
2026-02-04 21:54:22 +00:00
parent 7c3750ed16
commit adedcd4332

View File

@@ -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