diff options
| author | Eugene Triguba <eugenetriguba@gmail.com> | 2020-08-05 20:39:28 -0500 |
|---|---|---|
| committer | Eugene Triguba <eugenetriguba@gmail.com> | 2020-08-05 20:39:28 -0500 |
| commit | 59eeb1321fbad41dce7c971778e37ac1943fda3b (patch) | |
| tree | 0ccb143e1094784e9b149977d6f0cabf6f6220b2 /config_file/parsers | |
| parent | Add ConfigFilePath to refactor out file specific code (diff) | |
| download | config-file-59eeb1321fbad41dce7c971778e37ac1943fda3b.zip | |
Redo package to have a flat package structure
By having a flat package structure like this, it'll
avoid exposing packages and things we don't want to
be exposed.
Diffstat (limited to 'config_file/parsers')
| -rw-r--r-- | config_file/parsers/__init__.py | 0 | ||||
| -rw-r--r-- | config_file/parsers/abstract_parser.py | 117 | ||||
| -rw-r--r-- | config_file/parsers/base_parser.py | 98 | ||||
| -rw-r--r-- | config_file/parsers/ini_parser.py | 13 | ||||
| -rw-r--r-- | config_file/parsers/ini_parser_compat.py | 42 | ||||
| -rw-r--r-- | config_file/parsers/json_parser.py | 15 | ||||
| -rw-r--r-- | config_file/parsers/parse_value.py | 218 | ||||
| -rw-r--r-- | config_file/parsers/toml_parser.py | 28 | ||||
| -rw-r--r-- | config_file/parsers/yaml_parser.py | 28 |
9 files changed, 0 insertions, 559 deletions
diff --git a/config_file/parsers/__init__.py b/config_file/parsers/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/config_file/parsers/__init__.py +++ /dev/null diff --git a/config_file/parsers/abstract_parser.py b/config_file/parsers/abstract_parser.py deleted file mode 100644 index ed9430b..0000000 --- a/config_file/parsers/abstract_parser.py +++ /dev/null @@ -1,117 +0,0 @@ -from abc import ABC, abstractmethod -from typing import Any - - -class AbstractParser(ABC): - """Abstract Parser is the API contract for all parsers. - - 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. - - Attributes: - file_contents: The stringified version of a file. - """ - - @abstractmethod - def __init__(self, file_contents: str) -> None: - self.file_contents = file_contents - - @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: - MissingKeyError: 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: - MissingKeyError: 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) -> 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. - - 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 deleted file mode 100644 index c2a7d71..0000000 --- a/config_file/parsers/base_parser.py +++ /dev/null @@ -1,98 +0,0 @@ -from types import ModuleType -from typing import Any - -from config_file.exceptions import MissingKeyError, ParsingError -from config_file.nested_lookup import get_occurrence_of_key -from config_file.utils import split_on_dot - -from .abstract_parser import AbstractParser - - -class BaseParser(AbstractParser): - def __init__(self, file_contents: str, module: ModuleType, decode_error: Exception): - super().__init__(file_contents) - self.__module = module - self.__decode_error = decode_error - self.parsed_content = self.parse_file_contents(module, decode_error) - - def parse_file_contents(self, module, decode_error) -> Any: - try: - return module.loads(self.file_contents) - except decode_error as error: - raise ParsingError(error) - - def reset_internal_contents(self, file_contents: str) -> None: - self.file_contents = file_contents - self.parsed_content = self.parse_file_contents( - self.__module, self.__decode_error - ) - - def get(self, search_key: str) -> Any: - if "." not in search_key: - result = self.parsed_content[search_key] - return result - else: - split_keys = split_on_dot(search_key) - - result = self.parsed_content - key_causing_error = None - try: - for key in split_keys: - key_causing_error = key - result = result[key] - except (KeyError, TypeError): - raise ParsingError( - f"Cannot `get` {search_key} because " - f"{key_causing_error} is not subscriptable." - ) - - return result - - 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 MissingKeyError(f"The specified key '{key}' to delete was not found.") - - def stringify(self) -> str: - return self.__module.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 deleted file mode 100644 index 72974f1..0000000 --- a/config_file/parsers/ini_parser.py +++ /dev/null @@ -1,13 +0,0 @@ -import configparser - -from .base_parser import BaseParser -from .ini_parser_compat import IniParserCompatibility - - -class IniParser(BaseParser): - def __init__(self, file_contents: str): - super().__init__( - file_contents=file_contents, - module=IniParserCompatibility, - decode_error=configparser.Error, - ) diff --git a/config_file/parsers/ini_parser_compat.py b/config_file/parsers/ini_parser_compat.py deleted file mode 100644 index 9dfea2e..0000000 --- a/config_file/parsers/ini_parser_compat.py +++ /dev/null @@ -1,42 +0,0 @@ -import configparser -from io import StringIO - - -class IniParserCompatibility: - """ - Provides compatibility with the json, yaml, - and toml API so we can use the BaseParser - easily, while still being able to leverage - the built-in configparser to parse the file. - - It is used as the `module` parameter - for BaseParser, which requires us to have a - `dumps` and `loads` method. - """ - - @staticmethod - def loads(file_contents: str) -> dict: - parser = configparser.ConfigParser() - parser.read_string(file_contents) - - return IniParserCompatibility.__create_configparser_dict(parser) - - @staticmethod - def dumps(file_contents: dict) -> str: - parser = configparser.ConfigParser() - buffer = StringIO() - - parser.read_dict(file_contents) - parser.write(buffer) - - return buffer.getvalue() - - @staticmethod - def __create_configparser_dict(parser: configparser.ConfigParser) -> dict: - result = {} - items = dict(parser.items()) - - for section in parser.sections(): - result.update({str(section): dict(items[section])}) - - return result diff --git a/config_file/parsers/json_parser.py b/config_file/parsers/json_parser.py deleted file mode 100644 index 5314cd7..0000000 --- a/config_file/parsers/json_parser.py +++ /dev/null @@ -1,15 +0,0 @@ -import json - -from .base_parser import BaseParser - - -class JsonParser(BaseParser): - def __init__(self, file_contents: str): - super().__init__( - file_contents=file_contents, - module=json, - decode_error=json.decoder.JSONDecodeError, - ) - - def stringify(self) -> str: - return json.dumps(self.parsed_content, indent=4) diff --git a/config_file/parsers/parse_value.py b/config_file/parsers/parse_value.py deleted file mode 100644 index 12032d6..0000000 --- a/config_file/parsers/parse_value.py +++ /dev/null @@ -1,218 +0,0 @@ -"""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 deleted file mode 100644 index 1c7f8a7..0000000 --- a/config_file/parsers/toml_parser.py +++ /dev/null @@ -1,28 +0,0 @@ -try: - import tomlkit - - TOML_AVAILABLE = True -except ImportError: - TOML_AVAILABLE = False - -from config_file.exceptions import MissingDependencyError - -from .base_parser import BaseParser - - -class TomlParser(BaseParser): - def __init__(self, file_contents: str): - if not TOML_AVAILABLE: - raise MissingDependencyError( - "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]`." - ) - - super().__init__( - file_contents=file_contents, - module=tomlkit, - # tomlkit doesn't expose it's exceptions, but - # it's parsing error is a subclass of ValueError - decode_error=ValueError, - ) diff --git a/config_file/parsers/yaml_parser.py b/config_file/parsers/yaml_parser.py deleted file mode 100644 index babe873..0000000 --- a/config_file/parsers/yaml_parser.py +++ /dev/null @@ -1,28 +0,0 @@ -try: - from ruamel.yaml import YAML, YAMLError, round_trip_dump, round_trip_load - - YAML_AVAILABLE = True -except ImportError: - YAML_AVAILABLE = False - -from config_file.exceptions import MissingDependencyError - -from .base_parser import BaseParser - - -class YamlParser(BaseParser): - def __init__(self, file_contents: str): - if not YAML_AVAILABLE: - raise MissingDependencyError( - "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]`." - ) - - yaml = YAML(typ="safe") - yaml.loads = round_trip_load - yaml.dumps = round_trip_dump - - super().__init__( - file_contents=file_contents, module=yaml, decode_error=YAMLError - ) |