From f414a6560742ab45f592e33d1c61946fd11b52e3 Mon Sep 17 00:00:00 2001 From: 7000pctAUTO Date: Thu, 29 Jan 2026 10:50:27 +0000 Subject: [PATCH] Add formatters, utils, schemas and version --- configforge/formatters/yaml_handler.py | 54 ++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 configforge/formatters/yaml_handler.py diff --git a/configforge/formatters/yaml_handler.py b/configforge/formatters/yaml_handler.py new file mode 100644 index 0000000..4da6e21 --- /dev/null +++ b/configforge/formatters/yaml_handler.py @@ -0,0 +1,54 @@ +"""YAML format handler for ConfigForge.""" + +import yaml +from typing import Any, Dict + +from configforge.exceptions import ConversionError + + +class YAMLHandler: + """Handler for YAML configuration files.""" + + @staticmethod + def loads(content: str) -> Dict[str, Any]: + """Parse YAML content.""" + try: + result = yaml.safe_load(content) + return result if result is not None else {} + except yaml.YAMLError as e: + raise ConversionError(f"Invalid YAML: {str(e)}") from e + + @staticmethod + def dumps(data: Any, default_flow_style: bool = False) -> str: + """Serialize data to YAML string.""" + try: + return yaml.safe_dump(data, default_flow_style=default_flow_style, allow_unicode=True) + except (TypeError, ValueError) as e: + raise ConversionError(f"Failed to serialize YAML: {str(e)}") from e + + @staticmethod + def read(filepath: str) -> Dict[str, Any]: + """Read and parse YAML file.""" + try: + with open(filepath, "r", encoding="utf-8") as f: + result = yaml.safe_load(f) + return result if result is not None else {} + except FileNotFoundError: + raise ConversionError(f"File not found: {filepath}") + except PermissionError: + raise ConversionError(f"Permission denied: {filepath}") + except yaml.YAMLError as e: + raise ConversionError(f"Invalid YAML in {filepath}: {str(e)}") from e + + @staticmethod + def write(filepath: str, data: Any, default_flow_style: bool = False) -> None: + """Write data to YAML file.""" + try: + with open(filepath, "w", encoding="utf-8") as f: + yaml.safe_dump(data, f, default_flow_style=default_flow_style, allow_unicode=True) + 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 YAML: {str(e)}") from e