diff options
| author | Eugene Triguba <eugenetriguba@gmail.com> | 2020-11-26 13:18:44 -0600 |
|---|---|---|
| committer | Eugene Triguba <eugenetriguba@gmail.com> | 2020-11-26 13:18:44 -0600 |
| commit | d6832cd600a28c1396c67229245347c1cf9440ca (patch) | |
| tree | e216eed48e9130be1bd63d4ad0ee3c8cad68d915 /config_file/parsers | |
| parent | Add python 3.9 to pyproject and update lockfile (diff) | |
| download | config-file-d6832cd600a28c1396c67229245347c1cf9440ca.zip | |
Move parsers to parsers directory
Diffstat (limited to 'config_file/parsers')
| -rw-r--r-- | config_file/parsers/__init__.py | 0 | ||||
| -rw-r--r-- | config_file/parsers/abstract_parser.py | 131 | ||||
| -rw-r--r-- | config_file/parsers/base_parser.py | 181 | ||||
| -rw-r--r-- | config_file/parsers/ini_parser.py | 44 | ||||
| -rw-r--r-- | config_file/parsers/json_parser.py | 19 | ||||
| -rw-r--r-- | config_file/parsers/parse_value.py | 218 | ||||
| -rw-r--r-- | config_file/parsers/toml_parser.py | 31 | ||||
| -rw-r--r-- | config_file/parsers/yaml_parser.py | 31 |
8 files changed, 655 insertions, 0 deletions
diff --git a/config_file/parsers/__init__.py b/config_file/parsers/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/config_file/parsers/__init__.py diff --git a/config_file/parsers/abstract_parser.py b/config_file/parsers/abstract_parser.py new file mode 100644 index 0000000..460b238 --- /dev/null +++ b/config_file/parsers/abstract_parser.py @@ -0,0 +1,131 @@ +from abc import ABC, abstractmethod +from typing import Any + + +class AbstractParser(ABC): + """Abstract Parser is the API contract for a parser for + use in the ConfigFile object. + + Every parser in ConfigFile implements this parser, and + any user created parsers must implement this parser in + order for this package to be able to use it. + + Every key is specified in a dot (.) syntax + e.g. retrieving.some.deeply.nested.value + + If there is no dot in the key, it is assumed we are + performing an action on a top level key, which could + be an entire section. + + Args: + file_contents: The stringified version of a file. + """ + + @abstractmethod + def __init__(self, file_contents: str) -> None: + self.file_contents = file_contents + + @property + @abstractmethod + def parsed_content(self) -> dict: + """To be able to index into the ConfigFile object, + we have to expose the parsed dictionary object. + + Raises: + KeyError: If the key we are trying to index into + does not exist. + + Returns: + The internal contents parsed as a dictionary. + """ + raise NotImplementedError + + @abstractmethod + def reset_internal_contents(self, file_contents: str) -> None: + """Reset the state of this parser to a new file. + + When restoring to the original file in ConfigFile, + we need a way to reset the internal contents to this + new file. + + While this may be as simple as setting the file_contents + attribute value to the passed in file_contents argument, + it likely would not be. This is because the initial + passed in file contents would likely be parsed into some + special form for the parser to work with more easily. + + Args: + file_contents: The file contents of the new file. + """ + raise NotImplementedError + + @abstractmethod + def get(self, key: str) -> Any: + """Retrieve the value of a key from the working file. + + Args: + key: The key to retrieve. + + Returns: + Whatever value the given key happens to contain. + + Raises: + KeyError: If the key to retrieve does not exist. + """ + raise NotImplementedError + + @abstractmethod + def set(self, key: str, value: Any) -> None: + """Set the value of a key in the working file. + + If the key does not exist, it should be created. + + Args: + key: The key to set. + value: The value to set the key to. + """ + raise NotImplementedError + + @abstractmethod + def delete(self, key: str) -> None: + """Deletes a key from the working file. + + Args: + key: The key we would like to remove. + + Raises: + KeyError: If the key to remove does not exist. + """ + raise NotImplementedError + + @abstractmethod + def stringify(self) -> str: + """Stringify the working file. + + Since the ConfigFile does not write out to disk + after every operation, this method is what is + used as the output for saving the file again. + This parser should never write out to the disk. + + Returns: + The file we are working with as a string. + """ + raise NotImplementedError + + @abstractmethod + def has(self, key: str, wild: bool = False) -> bool: + """Check whether the given key is in the parsed working file. + + This should not behave like a wild card, as in check + if the key exists anywhere in the working file. Instead, + if a key is given without a dot, it should be assumed we + are checking the top level. + + Args: + key: The key to search for. + wild: Optionally search for any occurrence of key in the file. + + Returns: + True if the working file has the key. False otherwise. + """ + raise NotImplementedError diff --git a/config_file/parsers/base_parser.py b/config_file/parsers/base_parser.py new file mode 100644 index 0000000..ea94164 --- /dev/null +++ b/config_file/parsers/base_parser.py @@ -0,0 +1,181 @@ +from abc import abstractmethod +from typing import Any, Type + +from config_file.exceptions import ParsingError +from config_file.nested_lookup import get_occurrence_of_key +from config_file.parsers.abstract_parser import AbstractParser +from config_file.utils import split_on_dot + + +class BaseParser(AbstractParser): + def __init__(self, file_contents: str): + """The BaseParser implements the AbstractParser for us, as long as the + subclasses implement `loads`, `dumps`, and `decode_error` methods. + + Internally, every parser uses the BaseParser so it does not + have to re-implement common dictionary manipulation logic. However, + there is nothing about the BaseParser that is a requirement for + using ConfigFile. + + Args: + file_contents: The contents of the file to parse. + + Raises: + ParsingError: If the decode_error is raised. + """ + super().__init__(file_contents) + self.__parsed_content = self.parse_file_contents() + + @abstractmethod + def loads(self, contents: str) -> dict: + """Transforms the file contents into a dictionary. + + Args: + contents: The file contents to transform. + + Raises: + self.decode_error: If there is a decoding error + while attempting to parse the string. + + Returns: + The contents of a particular file as a dictionary + we can manipulate. + """ + raise NotImplementedError + + @abstractmethod + def dumps(self, loaded_contents: dict) -> str: + """Transform the parsed contents back into a string. + + Args: + loaded_contents: The file contents from a self.loads call. + + It doesn't necessary need to be from a loads call, could just + be a valid dictionary for the given format, but that is the + typical usecase. + + Raises: + self.decode_error: If there is a decoding error + while attempting to transform the dict back into a string. + + Returns: + The dictionary parsed back into a string. + """ + raise NotImplementedError + + @property + @abstractmethod + def decode_error(self) -> Type[Exception]: + """The decoding error raised by the subclass on loads/dumps. + + Returns: + The decoding error + """ + raise NotImplementedError + + @property + def parsed_content(self) -> dict: + return self.__parsed_content + + def parse_file_contents(self) -> dict: + """Parse the file contents by running the `loads` method on the module. + + Args: + module: The module to use to parse the file. + decode_error: The error that is raised from the module if the file + cannot be decoded. + + Raises: + ParsingError: If the decode_error is raised while running `loads`. + + Returns: + The parsed file as a dictionary. + """ + try: + return self.loads(self.file_contents) + except self.decode_error as error: + raise ParsingError(error) + + def reset_internal_contents(self, file_contents: str) -> None: + """Reset the file contents and parsed contents of the parser. + + Args: + file_contents: The new file contents. + + Raises: + ParsingError: If we're unable to parse the new file contents. + """ + self.file_contents = file_contents + self.__parsed_content = self.parse_file_contents() + + def get(self, search_key: str) -> Any: + key_causing_error = None + + try: + if "." not in search_key: + key_causing_error = search_key + return self.__parsed_content[search_key] + else: + split_keys = split_on_dot(search_key) + + content_reference = self.__parsed_content + for key in split_keys: + key_causing_error = key + content_reference = content_reference[key] + + except (KeyError, TypeError): + raise KeyError( + f"cannot `get` {search_key} because " + f"{key_causing_error} is not subscriptable." + ) + + return content_reference + + def set(self, key: str, value: Any) -> None: + if "." not in key: + self.__parsed_content[key] = value + return + + keys = split_on_dot(key) + content_reference = self.__parsed_content + for index, key in enumerate(keys): + if index == len(keys) - 1: + content_reference[key] = value + return + + try: + content_reference = content_reference[key] + except KeyError: + content_reference[key] = {} + content_reference = content_reference[key] + + def delete(self, key: str) -> None: + try: + if "." not in key: + del self.__parsed_content[key] + else: + indexes = split_on_dot(key) + indexes_length = len(indexes) + + content_reference = self.__parsed_content + for index, key in enumerate(indexes): + if index == indexes_length - 1: + del content_reference[key] + break + + content_reference = content_reference[key] + except (KeyError, TypeError): + raise KeyError(f"The specified key '{key}' to delete was not found.") + + def stringify(self) -> str: + return self.dumps(self.__parsed_content) + + def has(self, search_key: str, wild: bool = False) -> bool: + if wild: + return get_occurrence_of_key(self.__parsed_content, key=search_key) > 0 + + try: + self.get(search_key) + return True + except (KeyError, ParsingError): + return False diff --git a/config_file/parsers/ini_parser.py b/config_file/parsers/ini_parser.py new file mode 100644 index 0000000..fe78f05 --- /dev/null +++ b/config_file/parsers/ini_parser.py @@ -0,0 +1,44 @@ +import configparser +from io import StringIO +from typing import Any, Type + +from .base_parser import BaseParser + + +class IniParser(BaseParser): + def __init__(self, file_contents: str): + super().__init__(file_contents) + + @property + def decode_error(self) -> Type[Exception]: + return configparser.Error + + def loads(self, contents: str) -> dict: + parser = configparser.ConfigParser() + parser.read_string(contents) + + return self.__create_configparser_dict(parser) + + def dumps(self, loaded_contents: dict) -> str: + parser = configparser.ConfigParser() + buffer = StringIO() + + parser.read_dict(loaded_contents) + parser.write(buffer) + + return buffer.getvalue() + + def __create_configparser_dict(self, parser: configparser.ConfigParser) -> dict: + result = {} + items = dict(parser.items()) + + for section in parser.sections(): + result.update({str(section): dict(items[section])}) + + return result + + def get(self, search_key: str) -> Any: + retrieved_value = super().get(search_key) + return ( + retrieved_value if type(retrieved_value) is dict else str(retrieved_value) + ) diff --git a/config_file/parsers/json_parser.py b/config_file/parsers/json_parser.py new file mode 100644 index 0000000..58924b4 --- /dev/null +++ b/config_file/parsers/json_parser.py @@ -0,0 +1,19 @@ +import json +from typing import Type + +from .base_parser import BaseParser + + +class JsonParser(BaseParser): + def __init__(self, file_contents: str): + super().__init__(file_contents) + + @property + def decode_error(self) -> Type[Exception]: + return json.decoder.JSONDecodeError + + def loads(self, contents: str) -> dict: + return json.loads(contents) + + def dumps(self, loaded_contents: dict) -> str: + return json.dumps(loaded_contents, indent=4) diff --git a/config_file/parsers/parse_value.py b/config_file/parsers/parse_value.py new file mode 100644 index 0000000..12032d6 --- /dev/null +++ b/config_file/parsers/parse_value.py @@ -0,0 +1,218 @@ +"""This module allows you to parse a string into its native type.""" +import ast +import re +from distutils.util import strtobool +from typing import Any + + +def parse_value(value: Any) -> Any: + """Parse a value into native type. + + parse_value('5') -> 5 (int) + parse_value('-5') -> -5 (int) + + parse_value('5.52') -> 5.52 (float) + parse_value('-53.2') -> -53.2 (float) + + parse_value('blahfafda') -> 'blahfafda' (string) + + parse_value('true') -> True (bool) + parse_value('FALSE') -> False (bool) + + parse_value(" [ [ [ [] ]] ] ") -> [[[[]]]] (list) + + Args: + value: The value to parse. + + Returns: + The parsed value, if it could be parsed + as a dictionary, list, int, float, or bool. + Otherwise, it simply returns the original + passed in value. + """ + if isinstance(value, dict): + parsed = {} + + for item in value: + parsed[item] = parse_value(value[item]) + + return parsed + + if isinstance(value, list): + parsed = [] + + for item in value: + parsed.append(parse_value(item)) + + return parsed + + if can_be_parsed_as_int(value): + return int(value.strip()) if isinstance(value, str) else int(value) + + if can_be_parsed_as_float(value): + return float(value.strip()) if isinstance(value, str) else float(value) + + if can_be_parsed_as_bool(value): + return bool(value) if isinstance(value, bool) else bool(strtobool(value)) + + if can_be_parsed_as_dict(value): + return parse_value(ast.literal_eval(value.strip())) + + if can_be_parsed_as_list(value): + return parse_value(ast.literal_eval(value.strip())) + + return value + + +def can_be_parsed_as_int(value: Any) -> bool: + """Check whether a value can be parsed as a integer. + + can_be_parsed_as_int(5) -> True + can_be_parsed_as_int("5") -> True + can_be_parsed_as_int("-5") -> True + can_be_parsed_as_int(True) -> False + + Args: + value: The value to check if it can be parsed as an integer. + + Returns: + True if we can parse the value as a integer. False otherwise. + """ + if isinstance(value, int) and not isinstance(value, bool): + return True + + if not isinstance(value, str): + return False + + value = value.strip() + + if value.startswith("-"): + return value[1:].isdigit() + + return value.isdigit() + + +def can_be_parsed_as_float(value: Any) -> bool: + """Checks whether a value can be parsed as a float. + + can_be_parsed_as_float(45) -> False + can_be_parsed_as_float(1.1) -> True + can_be_parsed_as_float("1.1") -> True + can_be_parsed_as_float("-1.1") -> True + can_be_parsed_as_float(".1") -> True + + Args: + value: The value to be parsed. + + Returns: + True if the value can be parsed as a float. False otherwise. + """ + FLOAT_REGEX = r"^\d*\.\d+$" + + if isinstance(value, float): + return True + + if not isinstance(value, str): + return False + + value = value.strip() + + if value.startswith("-"): + value = value[1:] + + return bool(re.match(FLOAT_REGEX, value)) + + +def can_be_parsed_as_bool(value: Any) -> bool: + """Checks whether a value can be parsed as a boolean. + + can_be_parsed_as_bool(True) -> True + can_be_parsed_as_bool("true") -> True + can_be_parsed_as_bool("false") -> True + can_be_parsed_as_bool("TRUE") -> True + can_be_parsed_as_bool(0) -> False + + Args: + value: The value to be parsed. + + Returns: + True if the value can be parsed as a boolean. False otherwise. + """ + if isinstance(value, bool): + return True + + if not isinstance(value, str): + return False + + value = value.lower().strip() + + return value == "true" or value == "false" + + +def can_be_parsed_as_dict(value: Any) -> bool: + """Checks whether a value can be parsed as a dictionary. + + can_be_parsed_as_dict({}) -> True + can_be_parsed_as_dict("{}") -> True + can_be_parsed_as_dict(" { } ") -> True + can_be_parsed_as_dict("{ 'hello': 5 }") -> True + can_be_parsed_as_dict([]]) -> False + can_be_parsed_as_dict(" { invalid } ") -> False + + Args: + value: The value to be parsed. + + Returns: + True if the value can be parsed as a dictionary. False otherwise. + """ + if isinstance(value, dict): + return True + + if not isinstance(value, str): + return False + + value = value.strip() + + if value[0] == "{" and value[-1] == "}": + try: + ast.literal_eval(value) + return True + except Exception: + return False + + return False + + +def can_be_parsed_as_list(value: Any) -> bool: + """Checks whether a value can be parsed as a list. + + can_be_parsed_as_list([]) -> True + can_be_parsed_as_list([1, 2]) -> True + can_be_parsed_as_list("[]") -> True + can_be_parsed_as_list(" [] ") -> True + can_be_parsed_as_list("[1, 2]") -> True + can_be_parsed_as_list({}) -> False + can_be_parsed_as_list(" [ invalid ] ") -> False + + Args: + value: The value to be parsed. + + Returns: + True if the value can be parsed as a list. False otherwise. + """ + if isinstance(value, list): + return True + + if not isinstance(value, str): + return False + + value = value.strip() + + if value[0] == "[" and value[-1] == "]": + try: + ast.literal_eval(value) + return True + except Exception: + return False + + return False diff --git a/config_file/parsers/toml_parser.py b/config_file/parsers/toml_parser.py new file mode 100644 index 0000000..de5226c --- /dev/null +++ b/config_file/parsers/toml_parser.py @@ -0,0 +1,31 @@ +from typing import Type + +from .base_parser import BaseParser + + +class TomlParser(BaseParser): + def __init__(self, file_contents: str): + try: + super().__init__(file_contents) + except ImportError: + raise ImportError( + "It doesn't appear `tomlkit` is installed, but a toml " + "file was attempted to be used. Install the `toml` " + "extra first with `pip install config-file[toml]`." + ) + + @property + def decode_error(self) -> Type[Exception]: + from tomlkit.exceptions import ParseError + + return ParseError + + def loads(self, contents: str) -> dict: + import tomlkit + + return tomlkit.loads(contents) + + def dumps(self, loaded_contents: dict) -> str: + import tomlkit + + return tomlkit.dumps(loaded_contents) diff --git a/config_file/parsers/yaml_parser.py b/config_file/parsers/yaml_parser.py new file mode 100644 index 0000000..fc4239a --- /dev/null +++ b/config_file/parsers/yaml_parser.py @@ -0,0 +1,31 @@ +from typing import Type + +from .base_parser import BaseParser + + +class YamlParser(BaseParser): + def __init__(self, file_contents: str): + try: + super().__init__(file_contents) + except ImportError: + raise ImportError( + "It doesn't appear `ruamel.yaml` is installed, but a yaml " + "file was attempted to be used. Install the `yaml` " + "extra first with `pip install config-file[yaml]`." + ) + + @property + def decode_error(self) -> Type[Exception]: + from ruamel.yaml import YAMLError + + return YAMLError + + def loads(self, contents: str) -> dict: + from ruamel.yaml import round_trip_load + + return round_trip_load(contents) + + def dumps(self, loaded_contents: dict) -> str: + from ruamel.yaml import round_trip_dump + + return round_trip_dump(loaded_contents) |