diff options
| author | Eugene Triguba <eugenetriguba@gmail.com> | 2020-08-07 20:25:00 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-08-07 20:25:00 -0500 |
| commit | 05dba35cab34c2524b945da0164327b7b8a1159d (patch) | |
| tree | e1f263a316839c0d32a413c120a3c92426f36817 /config_file/parsers | |
| parent | Create python-package-ci.yml (diff) | |
| parent | Fix ConfigFile default (diff) | |
| download | config-file-05dba35cab34c2524b945da0164327b7b8a1159d.zip | |
Merge pull request #24 from eugenetriguba/dev
v0.11.0
Diffstat (limited to 'config_file/parsers')
| -rw-r--r-- | config_file/parsers/__init__.py | 0 | ||||
| -rw-r--r-- | config_file/parsers/base_parser.py | 79 | ||||
| -rw-r--r-- | config_file/parsers/ini_parser.py | 123 | ||||
| -rw-r--r-- | config_file/parsers/json_parser.py | 129 | ||||
| -rw-r--r-- | config_file/parsers/parse_value.py | 87 |
5 files changed, 0 insertions, 418 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/base_parser.py b/config_file/parsers/base_parser.py deleted file mode 100644 index 42f93b1..0000000 --- a/config_file/parsers/base_parser.py +++ /dev/null @@ -1,79 +0,0 @@ -from abc import ABC, abstractmethod - - -class BaseParser(ABC): - """ - The abstract base parser for all other parsers to implement. - - All the keys are specified in a 'dot' syntax. So if you have - sections with subsections with a key that you're trying to get - the value of, you'd use 'section.subsection.key' as the key parameter. - """ - - @abstractmethod - def __init__(self, file_contents: str): - """ - All parsers will take in the file as a string, parse - them internally to their own representation that they - can work with, and are able to stringify them back out - when we need to save (write) them. - - It is up to the caller of the parser to read in the file to - the parser and save the file when they are done using stringify(). - """ - self.content = file_contents - self.parsed_content = self.parse(self.content) - - @abstractmethod - def get(self, key, parse_types=False): - """ - Retrieve the value of a key in its native type. - This means the string 'true' will be parsed back as the - boolean True. - - If parse_types is set to False, all values will be returned - back as strings. - """ - raise NotImplementedError - - @abstractmethod - def set(self, key, value) -> bool: - """Sets the value of a key.""" - raise NotImplementedError - - @abstractmethod - def delete(self, section_key) -> bool: - """Deletes a key/value pair or entire sections.""" - raise NotImplementedError - - @abstractmethod - def stringify(self) -> str: - """ - Using self.__contents, converts the parsed internal representation - of the file back into a string. - """ - raise NotImplementedError - - @abstractmethod - def has(self, section_key: str) -> bool: - """ - Check if a section, sub-section, or key exists in the file - using a section.key format. - - Some formats, like JSON, do not have sections and therefore, - it would only be checking if - """ - raise NotImplementedError - - @abstractmethod - def parse(self, file_contents: str): - """ - Parse the file_contents into an internal representation - the given parser can work with. It should not return anything - if you're going to be using the super() constructor. - """ - raise NotImplementedError - - -class ParsingError(Exception): - """Unable to parse the configuration file""" diff --git a/config_file/parsers/ini_parser.py b/config_file/parsers/ini_parser.py deleted file mode 100644 index 81f2d1b..0000000 --- a/config_file/parsers/ini_parser.py +++ /dev/null @@ -1,123 +0,0 @@ -import configparser -from io import StringIO - -from config_file.parsers.base_parser import BaseParser, ParsingError -from config_file.parsers.parse_value import parse_value -from config_file.utils import split_on_dot - - -class IniParser(BaseParser): - def __init__(self, file_contents: str): - """Reads in the file contents into the configparser.""" - super().__init__(file_contents) - - def parse(self, file_contents: str): - try: - parser = configparser.ConfigParser() - parser.read_string(file_contents) - return parser - except configparser.Error as error: - raise ParsingError(error) - - def get(self, section_key: str, parse_types: bool = False): - """ - Read the value of `section.key` of the config file. - - :param section_key: The section and key to read from in the config file. - e.g. 'section1.key2' - :param parse_types: Coerces the return value to its native type. - :return: The value of the key, parsed to its native type if parse_types is True. - - :raises ValueError: if the section_key given is not in a dot format. e.g. - 'section1.key' - :raises ParsingError: if the specified `section.key` is not found, in an - invalid format, or if we are unable to coerce the return value to value_type. - """ - if "." not in section_key: - return self.__retrieve_section(section_key, parse_types) - - try: - section, key = split_on_dot(section_key, only_last_dot=True) - value = self.parsed_content.get(section, key) - return parse_value(value) if parse_types else value - except configparser.Error as error: - raise ParsingError(error.message) - - def __retrieve_section(self, section, parse_types): - items = dict(self.parsed_content.items(section)) - - if not parse_types: - return items - - for item in items: - items[item] = parse_value(items[item]) - - return items - - def set(self, section_key: str, value) -> bool: - """ - Sets the value of 'section.key' of the config file. If the specified section - is not in the configuration file, it will be created before adding the key - to it. - - :param section_key: The key to set from the config file. e.g. 'section1.key' - - :param value: The value to set the key to. It can be any type that can - be converted to a string. - - :return: True if the setting was successful. - - :raises ValueError: If there is no dot (.) in section_key - """ - section, key = split_on_dot(section_key, only_last_dot=True) - - if value is not None and not self.parsed_content.has_section(section): - self.parsed_content.add_section(section) - - if not isinstance(value, str): - value = str(value) - - self.parsed_content.set(section, key, value) - return True - - def delete(self, section_key: str) -> bool: - """ - Deletes a key or an entire section. - - :param section_key: The key to delete from the config file. - e.g. 'ocr.engine'. If no dot (.) is present, it will assume you are trying - to delete the entire section. - - :return: True if the deletion succeeded. - - :raise ValueError: If the section or key does not exist in the config file. - """ - if "." not in section_key: - if not self.parsed_content.has_section(section_key): - raise ValueError( - f"Cannot delete {section_key} because it is not in the config file." - ) - - self.parsed_content.remove_section(section_key) - return True - - section, key = split_on_dot(section_key, only_last_dot=True) - if key not in self.parsed_content[section]: - raise ValueError( - f"Cannot delete {section}.{key} because {key} is not in {section}." - ) - - self.parsed_content.remove_option(section, key) - return True - - def stringify(self) -> str: - buffer = StringIO() - self.parsed_content.write(buffer) - return buffer.getvalue() - - def has(self, section_key: str) -> bool: - if "." not in section_key: - return self.parsed_content.has_section(section_key) - - section, key = split_on_dot(section_key, only_last_dot=True) - return self.parsed_content.has_option(section, key) diff --git a/config_file/parsers/json_parser.py b/config_file/parsers/json_parser.py deleted file mode 100644 index 20eb085..0000000 --- a/config_file/parsers/json_parser.py +++ /dev/null @@ -1,129 +0,0 @@ -import json - -from nested_lookup import ( - get_occurrence_of_key, - nested_delete, - nested_lookup, - nested_update, -) - -from config_file.parsers.base_parser import BaseParser, ParsingError -from config_file.parsers.parse_value import parse_value -from config_file.utils import split_on_dot - - -class JsonParser(BaseParser): - """ - The JsonParser allows use of json files with ConfigFile. The syntax it - supports is a bit more flexible than the IniParser. - - By default, the dot syntax is used. However, if you'd like to get/set/delete all - of a particular key, you can specify so with an optional parameter. - - Example: - - json = { - "key1": { - "key2": "foo", - "key1": "bar" - }, - "foo": "bar" - } - parser = JsonParser(json.dumps(json)) - parser.get('key1') - >>> { "key2": "foo", "key1": "bar" } - parser.get('key1.key2') - >>> "foo" - parser.get('key1', get_all=True) - >>> [{ "key2": "foo", "key1": "bar" }, "bar"] - """ - - def __init__(self, file_contents: str): - """Reads in the file contents into the parser.""" - super().__init__(file_contents) - - def parse(self, file_contents: str): - try: - return json.loads(file_contents) - except json.decoder.JSONDecodeError as error: - raise ParsingError(error) - - def get(self, key: str, parse_types: bool = False, get_all: bool = False): - """ - Retrieve values using a dot syntax. - - :param key: The key to retrieve. e.g. 'foo.bar.boo' - - :param parse_types: Whether you'd like the type parsed into its native one. - - :param get_all: Specify whether you'd like to recursively receive - all values that match the given key. Returned as a list. - e.g. 'foo' would retrieve all values that have the key 'foo', anywhere - in the json. - - :return: the value of the given key - """ - if get_all: - result = nested_lookup(key, self.parsed_content) - elif "." in key: - split_keys = split_on_dot(key) - result = self.parsed_content - - # Used so we can more precisely specify what key is causing the error. - key_for_error = None - try: - for key in split_keys: - key_for_error = key - result = result[key] - except TypeError: - raise ParsingError( - f"Cannot get {key} because {key_for_error} is not subscriptable." - ) - else: - result = self.parsed_content[key] - - return parse_value(result) if parse_types else result - - def set(self, key: str, value, set_all: bool = False): - if set_all: - nested_update(self.parsed_content, key, value, in_place=True) - elif "." in key: - indexes = split_on_dot(key) - indexes_length = len(indexes) - - ref = self.parsed_content - for index, key in enumerate(indexes): - if index == indexes_length - 1: - ref[key] = value - break - - ref = ref[key] - else: - self.parsed_content[key] = value - - return True - - def delete(self, key, delete_all: bool = False): - if delete_all: - nested_delete(self.parsed_content, key, in_place=True) - elif "." in key: - indexes = split_on_dot(key) - indexes_length = len(indexes) - - ref = self.parsed_content - for index, key in enumerate(indexes): - if index == indexes_length - 1: - del ref[key] - break - - ref = ref[key] - else: - del self.parsed_content[key] - - return True - - def stringify(self) -> str: - return json.dumps(self.parsed_content) - - def has(self, search_key: str) -> bool: - return get_occurrence_of_key(self.parsed_content, key=search_key) > 0 diff --git a/config_file/parsers/parse_value.py b/config_file/parsers/parse_value.py deleted file mode 100644 index e58781a..0000000 --- a/config_file/parsers/parse_value.py +++ /dev/null @@ -1,87 +0,0 @@ -""" -Parse types allows you to check or parse a string into its native type. - -Example: - 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) - - -"5".isdigit() -> True -"-5".isdigit() -> False -can_be_parsed_as_int("-5") -> True -""" -import re -from distutils.util import strtobool - - -def parse_value(value): - if can_be_parsed_as_int(value): - return int(value) - - if can_be_parsed_as_float(value): - return float(value) - - if can_be_parsed_as_bool(value): - return value if type(value) is bool else bool(strtobool(value)) - - if type(value) is dict: - parsed = {} - - for item in value: - parsed[item] = parse_value(value[item]) - - return parsed - - if type(value) is list: - parsed = [] - - for item in value: - parsed.append(parse_value(item)) - - return parsed - - return value - - -def can_be_parsed_as_int(value) -> bool: - if type(value) is int: - return True - - if type(value) is not str: - return False - - if value.startswith("-"): - return value[1:].isdigit() - - return value.isdigit() - - -def can_be_parsed_as_float(value) -> bool: - if type(value) is float: - return True - - if type(value) is not str: - return False - - if value.startswith("-"): - return bool(re.match(r"^\d*\.\d+$", value[1:])) - - return bool(re.match(r"^\d*\.\d+$", value)) - - -def can_be_parsed_as_bool(value) -> bool: - if type(value) is bool: - return True - - if type(value) is not str: - return False - - return value.lower() == "true" or value.lower() == "false" |