From a859ed9b30f3960637c425ecfdf41f2fd201a5d2 Mon Sep 17 00:00:00 2001 From: 7000pctAUTO Date: Sun, 1 Feb 2026 22:26:07 +0000 Subject: [PATCH] Initial upload: config-converter-cli v1.0.0 --- configconverter/query.py | 74 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 configconverter/query.py diff --git a/configconverter/query.py b/configconverter/query.py new file mode 100644 index 0000000..453a26e --- /dev/null +++ b/configconverter/query.py @@ -0,0 +1,74 @@ +"""JMESPath query support for config-converter-cli.""" + +from typing import Any, Optional + +import jmespath + +from configconverter.converters import Converter +from configconverter.exceptions import ParseError, QueryError + + +class QueryEngine: + """Handles JMESPath queries on configuration data.""" + + def __init__(self): + self.converter = Converter() + + def query( + self, + content: str, + query_expression: str, + format: Optional[str] = None, + ) -> Any: + """Execute a JMESPath query on the content. + + Args: + content: The configuration content + query_expression: JMESPath expression + format: Optional format hint (json, yaml, toml) + + Returns: + Query result + """ + try: + if format: + data = self.converter._parse(content, format) + else: + detected = self.converter.detect_format(content) + data = self.converter._parse(content, detected) + + result = jmespath.search(query_expression, data) + return result + + except jmespath.exceptions.ParseError as e: + raise QueryError(f"Invalid JMESPath expression: {e}") + except jmespath.exceptions.JMESPathTypeError as e: + raise QueryError(f"JMESPath type error: {e}") + except ParseError: + raise + except Exception as e: + raise QueryError(f"Query execution failed: {e}") + + def query_json( + self, + content: str, + query_expression: str, + format: Optional[str] = None, + ) -> str: + """Execute a JMESPath query and return result as JSON string. + + Args: + content: The configuration content + query_expression: JMESPath expression + format: Optional format hint (json, yaml, toml) + + Returns: + Query result as JSON string + """ + import json + + result = self.query(content, query_expression, format) + return json.dumps(result, indent=2, ensure_ascii=False) + + +query_engine = QueryEngine()