From aa44fe7a60a4f3326cc47877b3e246b56d46d6ac Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sat, 20 Jun 2020 13:41:35 -0500 Subject: Add python 3.5 support, ConfigFileError, and more type hints Also, get_all, set_all, and delete_all in JsonParser have been renamed to just all. --- config_file/parsers/base_parser.py | 3 --- config_file/parsers/ini_parser.py | 7 ++++--- config_file/parsers/json_parser.py | 21 +++++++++++---------- config_file/parsers/toml_parser.py | 0 config_file/parsers/yaml_parser.py | 0 5 files changed, 15 insertions(+), 16 deletions(-) create mode 100644 config_file/parsers/toml_parser.py create mode 100644 config_file/parsers/yaml_parser.py (limited to 'config_file/parsers') diff --git a/config_file/parsers/base_parser.py b/config_file/parsers/base_parser.py index 42f93b1..5fc47c2 100644 --- a/config_file/parsers/base_parser.py +++ b/config_file/parsers/base_parser.py @@ -74,6 +74,3 @@ class BaseParser(ABC): """ 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 index 81f2d1b..31b0dcf 100644 --- a/config_file/parsers/ini_parser.py +++ b/config_file/parsers/ini_parser.py @@ -1,9 +1,10 @@ import configparser from io import StringIO -from config_file.parsers.base_parser import BaseParser, ParsingError +from config_file.parsers.base_parser import BaseParser from config_file.parsers.parse_value import parse_value from config_file.utils import split_on_dot +from config_file.exceptions import ParsingError class IniParser(BaseParser): @@ -95,7 +96,7 @@ class IniParser(BaseParser): 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." + "Cannot delete {} because it is not in the config file.".format(section_key) ) self.parsed_content.remove_section(section_key) @@ -104,7 +105,7 @@ class IniParser(BaseParser): 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}." + "Cannot delete {section}.{key} because {key} is not in {section}.".format(section = section, key = key) ) self.parsed_content.remove_option(section, key) diff --git a/config_file/parsers/json_parser.py b/config_file/parsers/json_parser.py index 20eb085..4d93ca3 100644 --- a/config_file/parsers/json_parser.py +++ b/config_file/parsers/json_parser.py @@ -7,9 +7,10 @@ from nested_lookup import ( nested_update, ) -from config_file.parsers.base_parser import BaseParser, ParsingError +from config_file.parsers.base_parser import BaseParser from config_file.parsers.parse_value import parse_value from config_file.utils import split_on_dot +from config_file.exceptions import ParsingError class JsonParser(BaseParser): @@ -34,7 +35,7 @@ class JsonParser(BaseParser): >>> { "key2": "foo", "key1": "bar" } parser.get('key1.key2') >>> "foo" - parser.get('key1', get_all=True) + parser.get('key1', all=True) >>> [{ "key2": "foo", "key1": "bar" }, "bar"] """ @@ -48,7 +49,7 @@ class JsonParser(BaseParser): except json.decoder.JSONDecodeError as error: raise ParsingError(error) - def get(self, key: str, parse_types: bool = False, get_all: bool = False): + def get(self, key: str, parse_types: bool = False, all: bool = False): """ Retrieve values using a dot syntax. @@ -56,14 +57,14 @@ class JsonParser(BaseParser): :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 + :param 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: + if all: result = nested_lookup(key, self.parsed_content) elif "." in key: split_keys = split_on_dot(key) @@ -77,15 +78,15 @@ class JsonParser(BaseParser): result = result[key] except TypeError: raise ParsingError( - f"Cannot get {key} because {key_for_error} is not subscriptable." + "Cannot get {} because {} is not subscriptable.".format(key, key_for_error) ) 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: + def set(self, key: str, value, all: bool = False): + if all: nested_update(self.parsed_content, key, value, in_place=True) elif "." in key: indexes = split_on_dot(key) @@ -103,8 +104,8 @@ class JsonParser(BaseParser): return True - def delete(self, key, delete_all: bool = False): - if delete_all: + def delete(self, key, all: bool = False): + if all: nested_delete(self.parsed_content, key, in_place=True) elif "." in key: indexes = split_on_dot(key) diff --git a/config_file/parsers/toml_parser.py b/config_file/parsers/toml_parser.py new file mode 100644 index 0000000..e69de29 diff --git a/config_file/parsers/yaml_parser.py b/config_file/parsers/yaml_parser.py new file mode 100644 index 0000000..e69de29 -- cgit v1.2.3 From 58808235ea6880c3a0ecfa976a700c81431dc902 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sat, 20 Jun 2020 15:30:11 -0500 Subject: Revert Python 3.5 support --- config_file/parsers/ini_parser.py | 6 +++--- config_file/parsers/json_parser.py | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/ini_parser.py b/config_file/parsers/ini_parser.py index 31b0dcf..2db1ae8 100644 --- a/config_file/parsers/ini_parser.py +++ b/config_file/parsers/ini_parser.py @@ -1,10 +1,10 @@ import configparser from io import StringIO +from config_file.exceptions import ParsingError from config_file.parsers.base_parser import BaseParser from config_file.parsers.parse_value import parse_value from config_file.utils import split_on_dot -from config_file.exceptions import ParsingError class IniParser(BaseParser): @@ -96,7 +96,7 @@ class IniParser(BaseParser): if "." not in section_key: if not self.parsed_content.has_section(section_key): raise ValueError( - "Cannot delete {} because it is not in the config file.".format(section_key) + f"Cannot delete {section_key} because it is not in the config file." ) self.parsed_content.remove_section(section_key) @@ -105,7 +105,7 @@ class IniParser(BaseParser): section, key = split_on_dot(section_key, only_last_dot=True) if key not in self.parsed_content[section]: raise ValueError( - "Cannot delete {section}.{key} because {key} is not in {section}.".format(section = section, key = key) + f"Cannot delete {section}.{key} because {key} is not in {section}." ) self.parsed_content.remove_option(section, key) diff --git a/config_file/parsers/json_parser.py b/config_file/parsers/json_parser.py index 4d93ca3..10d5afc 100644 --- a/config_file/parsers/json_parser.py +++ b/config_file/parsers/json_parser.py @@ -7,10 +7,10 @@ from nested_lookup import ( nested_update, ) +from config_file.exceptions import ParsingError from config_file.parsers.base_parser import BaseParser from config_file.parsers.parse_value import parse_value from config_file.utils import split_on_dot -from config_file.exceptions import ParsingError class JsonParser(BaseParser): @@ -78,7 +78,7 @@ class JsonParser(BaseParser): result = result[key] except TypeError: raise ParsingError( - "Cannot get {} because {} is not subscriptable.".format(key, key_for_error) + f"Cannot get {key} because {key_for_error} is not subscriptable." ) else: result = self.parsed_content[key] -- cgit v1.2.3 From b3fb6aae1201faca1238b3c79e5e95ba57282bf1 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sat, 20 Jun 2020 15:35:05 -0500 Subject: Add more type hints to ConfigFile and lint all files --- config_file/parsers/base_parser.py | 1 - 1 file changed, 1 deletion(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/base_parser.py b/config_file/parsers/base_parser.py index 5fc47c2..bbdfd91 100644 --- a/config_file/parsers/base_parser.py +++ b/config_file/parsers/base_parser.py @@ -73,4 +73,3 @@ class BaseParser(ABC): if you're going to be using the super() constructor. """ raise NotImplementedError - -- cgit v1.2.3 From ee78049f1e33bcb9894f43d51e44b079edfab91f Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sat, 20 Jun 2020 16:32:23 -0500 Subject: Add types to base parser and update build badge --- config_file/parsers/base_parser.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/base_parser.py b/config_file/parsers/base_parser.py index bbdfd91..a1d38d4 100644 --- a/config_file/parsers/base_parser.py +++ b/config_file/parsers/base_parser.py @@ -1,4 +1,5 @@ from abc import ABC, abstractmethod +from typing import Any class BaseParser(ABC): @@ -25,7 +26,7 @@ class BaseParser(ABC): self.parsed_content = self.parse(self.content) @abstractmethod - def get(self, key, parse_types=False): + def get(self, key: str, parse_types: bool = False, all: bool = False): """ Retrieve the value of a key in its native type. This means the string 'true' will be parsed back as the @@ -37,12 +38,12 @@ class BaseParser(ABC): raise NotImplementedError @abstractmethod - def set(self, key, value) -> bool: + def set(self, key: str, value: Any) -> bool: """Sets the value of a key.""" raise NotImplementedError @abstractmethod - def delete(self, section_key) -> bool: + def delete(self, section_key: str) -> bool: """Deletes a key/value pair or entire sections.""" raise NotImplementedError @@ -66,10 +67,9 @@ class BaseParser(ABC): raise NotImplementedError @abstractmethod - def parse(self, file_contents: str): + def parse(self, file_contents: str) -> Any: """ 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. + the given parser can work with. """ raise NotImplementedError -- cgit v1.2.3 From 2c293cc0ac6678253c6af8101ba93866785f64c0 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sun, 21 Jun 2020 11:12:26 -0500 Subject: WIP for refactoring tests --- config_file/parsers/__init__.py | 6 ++++++ config_file/parsers/json_parser.py | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/__init__.py b/config_file/parsers/__init__.py index e69de29..415f4f9 100644 --- a/config_file/parsers/__init__.py +++ b/config_file/parsers/__init__.py @@ -0,0 +1,6 @@ +from .base_parser import BaseParser +from .ini_parser import IniParser +from .json_parser import JsonParser +from .parse_value import parse_value + +__all__ = ["BaseParser", "IniParser", "JsonParser", "parse_value"] diff --git a/config_file/parsers/json_parser.py b/config_file/parsers/json_parser.py index 10d5afc..584a2d0 100644 --- a/config_file/parsers/json_parser.py +++ b/config_file/parsers/json_parser.py @@ -124,7 +124,7 @@ class JsonParser(BaseParser): return True def stringify(self) -> str: - return json.dumps(self.parsed_content) + return json.dumps(self.parsed_content, indent=4) def has(self, search_key: str) -> bool: return get_occurrence_of_key(self.parsed_content, key=search_key) > 0 -- cgit v1.2.3 From 3a5336c20a983a01bf1495914932f490e97e8d23 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Fri, 10 Jul 2020 20:29:46 -0500 Subject: Add empty yaml and toml parsers --- config_file/parsers/toml_parser.py | 4 ++++ config_file/parsers/yaml_parser.py | 4 ++++ 2 files changed, 8 insertions(+) (limited to 'config_file/parsers') diff --git a/config_file/parsers/toml_parser.py b/config_file/parsers/toml_parser.py index e69de29..2b3a48f 100644 --- a/config_file/parsers/toml_parser.py +++ b/config_file/parsers/toml_parser.py @@ -0,0 +1,4 @@ +import toml + +class TomlParser(BaseParser): + pass \ No newline at end of file diff --git a/config_file/parsers/yaml_parser.py b/config_file/parsers/yaml_parser.py index e69de29..e7e88b5 100644 --- a/config_file/parsers/yaml_parser.py +++ b/config_file/parsers/yaml_parser.py @@ -0,0 +1,4 @@ + + +class YamlParser: + pass \ No newline at end of file -- cgit v1.2.3 From fbf798d86b1c2a5d70f39f084ee4e2a376fe6914 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sat, 11 Jul 2020 14:57:24 -0500 Subject: Add dummy toml and yaml parsers --- config_file/parsers/toml_parser.py | 2 ++ config_file/parsers/yaml_parser.py | 6 +++--- 2 files changed, 5 insertions(+), 3 deletions(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/toml_parser.py b/config_file/parsers/toml_parser.py index 2b3a48f..64ab216 100644 --- a/config_file/parsers/toml_parser.py +++ b/config_file/parsers/toml_parser.py @@ -1,3 +1,5 @@ +from config_file.parsers import BaseParser + import toml class TomlParser(BaseParser): diff --git a/config_file/parsers/yaml_parser.py b/config_file/parsers/yaml_parser.py index e7e88b5..48722b5 100644 --- a/config_file/parsers/yaml_parser.py +++ b/config_file/parsers/yaml_parser.py @@ -1,4 +1,4 @@ +from config_file.parsers import BaseParser - -class YamlParser: - pass \ No newline at end of file +class YamlParser(BaseParser): + pass -- cgit v1.2.3 From b467d83e7d67dbda82663634ff60e975f722b115 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sun, 12 Jul 2020 09:11:27 -0500 Subject: Add to __all__ --- config_file/parsers/__init__.py | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/__init__.py b/config_file/parsers/__init__.py index 415f4f9..8da520e 100644 --- a/config_file/parsers/__init__.py +++ b/config_file/parsers/__init__.py @@ -1,6 +1,23 @@ from .base_parser import BaseParser from .ini_parser import IniParser from .json_parser import JsonParser -from .parse_value import parse_value +from .toml_parser import TomlParser +from .yaml_parser import YamlParser +from .parse_value import ( + parse_value, + can_be_parsed_as_bool, + can_be_parsed_as_float, + can_be_parsed_as_int +) -__all__ = ["BaseParser", "IniParser", "JsonParser", "parse_value"] +__all__ = [ + "BaseParser", + "IniParser", + "JsonParser", + "TomlParser", + "YamlParser", + "parse_value", + "can_be_parsed_as_bool", + "can_be_parsed_as_float", + "can_be_parsed_as_int" +] -- cgit v1.2.3 From c42fd6044f15102d6688cc958a50ab134df046ba Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sun, 12 Jul 2020 09:11:53 -0500 Subject: Add return type hints to BaseParser --- config_file/parsers/base_parser.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/base_parser.py b/config_file/parsers/base_parser.py index a1d38d4..da6e90a 100644 --- a/config_file/parsers/base_parser.py +++ b/config_file/parsers/base_parser.py @@ -12,7 +12,7 @@ class BaseParser(ABC): """ @abstractmethod - def __init__(self, file_contents: str): + def __init__(self, file_contents: str) -> None: """ All parsers will take in the file as a string, parse them internally to their own representation that they @@ -26,7 +26,7 @@ class BaseParser(ABC): self.parsed_content = self.parse(self.content) @abstractmethod - def get(self, key: str, parse_types: bool = False, all: bool = False): + def get(self, key: str, parse_types: bool = False, all: bool = False) -> Any: """ Retrieve the value of a key in its native type. This means the string 'true' will be parsed back as the -- cgit v1.2.3 From bc1280444ea3d5d4e5b5afd4e39bfb9365689393 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sun, 19 Jul 2020 13:17:09 -0500 Subject: Add nested-lookup to project russellballestrini is a python project in the public domain. Rather than installing it as a dependency, this adds it as part of the config-file package now, which allows more control. --- config_file/parsers/json_parser.py | 12 ++--- config_file/parsers/toml_parser.py | 105 +++++++++++++++++++++++++++++++++++-- 2 files changed, 107 insertions(+), 10 deletions(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/json_parser.py b/config_file/parsers/json_parser.py index 584a2d0..13b84b5 100644 --- a/config_file/parsers/json_parser.py +++ b/config_file/parsers/json_parser.py @@ -1,6 +1,6 @@ import json -from nested_lookup import ( +from config_file.nested_lookup import ( get_occurrence_of_key, nested_delete, nested_lookup, @@ -8,8 +8,7 @@ from nested_lookup import ( ) from config_file.exceptions import ParsingError -from config_file.parsers.base_parser import BaseParser -from config_file.parsers.parse_value import parse_value +from config_file.parsers import BaseParser, parse_value from config_file.utils import split_on_dot @@ -70,15 +69,14 @@ class JsonParser(BaseParser): 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 + key_causing_error = None try: for key in split_keys: - key_for_error = key + key_causing_error = key result = result[key] except TypeError: raise ParsingError( - f"Cannot get {key} because {key_for_error} is not subscriptable." + f"Cannot get {key} because {key_causing_error} is not subscriptable." ) else: result = self.parsed_content[key] diff --git a/config_file/parsers/toml_parser.py b/config_file/parsers/toml_parser.py index 64ab216..ad3e7f4 100644 --- a/config_file/parsers/toml_parser.py +++ b/config_file/parsers/toml_parser.py @@ -1,6 +1,105 @@ -from config_file.parsers import BaseParser - import toml +from config_file.nested_lookup import ( + get_occurrence_of_key, + nested_delete, + nested_lookup, + nested_update, +) +from config_file.exceptions import ParsingError +from config_file.parsers import BaseParser, parse_value +from config_file.utils import split_on_dot + + class TomlParser(BaseParser): - pass \ No newline at end of file + """The TomlParser allows use of toml files with ConfigFile.""" + + 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 toml.loads(file_contents) + except toml.TomlDecodeError as error: + raise ParsingError(error) + + def get(self, key: str, parse_types: bool = False, 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 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 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, all: bool = False): + if 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, all: bool = False): + if 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, indent=4) + + def has(self, search_key: str) -> bool: + return get_occurrence_of_key(self.parsed_content, key=search_key) > 0 -- cgit v1.2.3 From c476c1ed7065910fddc15ccfe67442c81f777bbf Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sun, 19 Jul 2020 14:59:05 -0500 Subject: Remove zsh info and add extras sub header --- config_file/parsers/abstract_parser.py | 75 ++++++++++++++++++++++++++++++++++ config_file/parsers/base_parser.py | 75 ---------------------------------- 2 files changed, 75 insertions(+), 75 deletions(-) create mode 100644 config_file/parsers/abstract_parser.py delete mode 100644 config_file/parsers/base_parser.py (limited to 'config_file/parsers') diff --git a/config_file/parsers/abstract_parser.py b/config_file/parsers/abstract_parser.py new file mode 100644 index 0000000..da6e90a --- /dev/null +++ b/config_file/parsers/abstract_parser.py @@ -0,0 +1,75 @@ +from abc import ABC, abstractmethod +from typing import Any + + +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) -> None: + """ + 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: str, parse_types: bool = False, all: bool = False) -> Any: + """ + 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: str, value: Any) -> bool: + """Sets the value of a key.""" + raise NotImplementedError + + @abstractmethod + def delete(self, section_key: str) -> 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) -> Any: + """ + Parse the file_contents into an internal representation + the given parser can work with. + """ + raise NotImplementedError diff --git a/config_file/parsers/base_parser.py b/config_file/parsers/base_parser.py deleted file mode 100644 index da6e90a..0000000 --- a/config_file/parsers/base_parser.py +++ /dev/null @@ -1,75 +0,0 @@ -from abc import ABC, abstractmethod -from typing import Any - - -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) -> None: - """ - 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: str, parse_types: bool = False, all: bool = False) -> Any: - """ - 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: str, value: Any) -> bool: - """Sets the value of a key.""" - raise NotImplementedError - - @abstractmethod - def delete(self, section_key: str) -> 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) -> Any: - """ - Parse the file_contents into an internal representation - the given parser can work with. - """ - raise NotImplementedError -- cgit v1.2.3 From 461cb78f0a56b9293b5ade10fe90ec4aa77d23ad Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sun, 19 Jul 2020 15:02:13 -0500 Subject: Change name of BaseParser to AbstractParser --- config_file/parsers/__init__.py | 14 ++--- config_file/parsers/abstract_parser.py | 20 +++---- config_file/parsers/ini_parser.py | 4 +- config_file/parsers/json_parser.py | 10 ++-- config_file/parsers/toml_parser.py | 104 +-------------------------------- config_file/parsers/yaml_parser.py | 5 +- 6 files changed, 29 insertions(+), 128 deletions(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/__init__.py b/config_file/parsers/__init__.py index 8da520e..554b624 100644 --- a/config_file/parsers/__init__.py +++ b/config_file/parsers/__init__.py @@ -1,17 +1,17 @@ -from .base_parser import BaseParser +from .abstract_parser import AbstractParser from .ini_parser import IniParser from .json_parser import JsonParser -from .toml_parser import TomlParser -from .yaml_parser import YamlParser from .parse_value import ( - parse_value, can_be_parsed_as_bool, can_be_parsed_as_float, - can_be_parsed_as_int + can_be_parsed_as_int, + parse_value, ) +from .toml_parser import TomlParser +from .yaml_parser import YamlParser __all__ = [ - "BaseParser", + "AbstractParser", "IniParser", "JsonParser", "TomlParser", @@ -19,5 +19,5 @@ __all__ = [ "parse_value", "can_be_parsed_as_bool", "can_be_parsed_as_float", - "can_be_parsed_as_int" + "can_be_parsed_as_int", ] diff --git a/config_file/parsers/abstract_parser.py b/config_file/parsers/abstract_parser.py index da6e90a..8f1bee1 100644 --- a/config_file/parsers/abstract_parser.py +++ b/config_file/parsers/abstract_parser.py @@ -2,7 +2,7 @@ from abc import ABC, abstractmethod from typing import Any -class BaseParser(ABC): +class AbstractParser(ABC): """ The abstract base parser for all other parsers to implement. @@ -25,6 +25,14 @@ class BaseParser(ABC): self.content = file_contents self.parsed_content = self.parse(self.content) + @abstractmethod + def parse(self, file_contents: str) -> Any: + """ + Parse the file_contents into an internal representation + the given parser can work with. + """ + raise NotImplementedError + @abstractmethod def get(self, key: str, parse_types: bool = False, all: bool = False) -> Any: """ @@ -62,14 +70,6 @@ class BaseParser(ABC): 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) -> Any: - """ - Parse the file_contents into an internal representation - the given parser can work with. + it would only be checking if a certain key exists. """ raise NotImplementedError diff --git a/config_file/parsers/ini_parser.py b/config_file/parsers/ini_parser.py index 2db1ae8..164ff6d 100644 --- a/config_file/parsers/ini_parser.py +++ b/config_file/parsers/ini_parser.py @@ -2,12 +2,12 @@ import configparser from io import StringIO from config_file.exceptions import ParsingError -from config_file.parsers.base_parser import BaseParser +from config_file.parsers.abstract_parser import AbstractParser from config_file.parsers.parse_value import parse_value from config_file.utils import split_on_dot -class IniParser(BaseParser): +class IniParser(AbstractParser): def __init__(self, file_contents: str): """Reads in the file contents into the configparser.""" super().__init__(file_contents) diff --git a/config_file/parsers/json_parser.py b/config_file/parsers/json_parser.py index 13b84b5..237c0b5 100644 --- a/config_file/parsers/json_parser.py +++ b/config_file/parsers/json_parser.py @@ -1,18 +1,17 @@ import json +from config_file.exceptions import ParsingError from config_file.nested_lookup import ( get_occurrence_of_key, nested_delete, nested_lookup, nested_update, ) - -from config_file.exceptions import ParsingError -from config_file.parsers import BaseParser, parse_value +from config_file.parsers import AbstractParser, parse_value from config_file.utils import split_on_dot -class JsonParser(BaseParser): +class JsonParser(AbstractParser): """ The JsonParser allows use of json files with ConfigFile. The syntax it supports is a bit more flexible than the IniParser. @@ -76,7 +75,8 @@ class JsonParser(BaseParser): result = result[key] except TypeError: raise ParsingError( - f"Cannot get {key} because {key_causing_error} is not subscriptable." + f"Cannot get {key} because {key_causing_error} " + "is not subscriptable." ) else: result = self.parsed_content[key] diff --git a/config_file/parsers/toml_parser.py b/config_file/parsers/toml_parser.py index ad3e7f4..4905aec 100644 --- a/config_file/parsers/toml_parser.py +++ b/config_file/parsers/toml_parser.py @@ -1,105 +1,5 @@ -import toml +from config_file.parsers import AbstractParser -from config_file.nested_lookup import ( - get_occurrence_of_key, - nested_delete, - nested_lookup, - nested_update, -) -from config_file.exceptions import ParsingError -from config_file.parsers import BaseParser, parse_value -from config_file.utils import split_on_dot - -class TomlParser(BaseParser): +class TomlParser(AbstractParser): """The TomlParser allows use of toml files with ConfigFile.""" - - 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 toml.loads(file_contents) - except toml.TomlDecodeError as error: - raise ParsingError(error) - - def get(self, key: str, parse_types: bool = False, 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 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 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, all: bool = False): - if 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, all: bool = False): - if 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, indent=4) - - 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/yaml_parser.py b/config_file/parsers/yaml_parser.py index 48722b5..a45d7f6 100644 --- a/config_file/parsers/yaml_parser.py +++ b/config_file/parsers/yaml_parser.py @@ -1,4 +1,5 @@ -from config_file.parsers import BaseParser +from config_file.parsers import AbstractParser -class YamlParser(BaseParser): + +class YamlParser(AbstractParser): pass -- cgit v1.2.3 From bc05c79f915e2b45b7f13f143b4c01f4c49013f8 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Mon, 20 Jul 2020 21:59:22 -0500 Subject: Add FLOAT_REGEX constant --- config_file/parsers/parse_value.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/parse_value.py b/config_file/parsers/parse_value.py index e58781a..26bdf2e 100644 --- a/config_file/parsers/parse_value.py +++ b/config_file/parsers/parse_value.py @@ -1,5 +1,5 @@ """ -Parse types allows you to check or parse a string into its native type. +This module allows you to parse a string into its native type. Example: parse_value('5') -> 5 (int) @@ -17,6 +17,7 @@ Example: "5".isdigit() -> True "-5".isdigit() -> False can_be_parsed_as_int("-5") -> True +parse_value("-5") -> -5 """ import re from distutils.util import strtobool @@ -65,6 +66,8 @@ def can_be_parsed_as_int(value) -> bool: def can_be_parsed_as_float(value) -> bool: + FLOAT_REGEX = r"^\d*\.\d+$" + if type(value) is float: return True @@ -72,9 +75,9 @@ def can_be_parsed_as_float(value) -> bool: return False if value.startswith("-"): - return bool(re.match(r"^\d*\.\d+$", value[1:])) + return bool(re.match(FLOAT_REGEX, value[1:])) - return bool(re.match(r"^\d*\.\d+$", value)) + return bool(re.match(FLOAT_REGEX, value)) def can_be_parsed_as_bool(value) -> bool: -- cgit v1.2.3 From 8c28da679092d9debf7140974fa7d28dfeda8e21 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Mon, 20 Jul 2020 22:49:58 -0500 Subject: Redo docstrings and api for abstract parser --- config_file/parsers/abstract_parser.py | 122 ++++++++++++++++++++++----------- 1 file changed, 82 insertions(+), 40 deletions(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/abstract_parser.py b/config_file/parsers/abstract_parser.py index 8f1bee1..ed9430b 100644 --- a/config_file/parsers/abstract_parser.py +++ b/config_file/parsers/abstract_parser.py @@ -3,73 +3,115 @@ from typing import Any class AbstractParser(ABC): - """ - The abstract base parser for all other parsers to implement. + """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. - 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. + 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: - """ - 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) + self.file_contents = file_contents @abstractmethod - def parse(self, file_contents: str) -> Any: - """ - Parse the file_contents into an internal representation - the given parser can work with. + 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, parse_types: bool = False, all: bool = False) -> Any: - """ - Retrieve the value of a key in its native type. - This means the string 'true' will be parsed back as the - boolean True. + def get(self, key: str) -> Any: + """Retrieve the value of a key from the working file. + + Args: + key: The key to retrieve. - If parse_types is set to False, all values will be returned - back as strings. + 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) -> bool: - """Sets the value of a key.""" + 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, section_key: str) -> bool: - """Deletes a key/value pair or entire sections.""" + 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: - """ - Using self.__contents, converts the parsed internal representation - of the file back into a string. + """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, section_key: str) -> bool: - """ - Check if a section, sub-section, or key exists in the file - using a section.key format. + 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. - Some formats, like JSON, do not have sections and therefore, - it would only be checking if a certain key exists. + Returns: + True if the working file has the key. False otherwise. """ raise NotImplementedError -- cgit v1.2.3 From ce71e05c2615350dba997b671ee63f8bd607cf03 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Mon, 20 Jul 2020 22:50:39 -0500 Subject: Remove parser imports from __init__ --- config_file/parsers/__init__.py | 23 ----------------------- 1 file changed, 23 deletions(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/__init__.py b/config_file/parsers/__init__.py index 554b624..e69de29 100644 --- a/config_file/parsers/__init__.py +++ b/config_file/parsers/__init__.py @@ -1,23 +0,0 @@ -from .abstract_parser import AbstractParser -from .ini_parser import IniParser -from .json_parser import JsonParser -from .parse_value import ( - can_be_parsed_as_bool, - can_be_parsed_as_float, - can_be_parsed_as_int, - parse_value, -) -from .toml_parser import TomlParser -from .yaml_parser import YamlParser - -__all__ = [ - "AbstractParser", - "IniParser", - "JsonParser", - "TomlParser", - "YamlParser", - "parse_value", - "can_be_parsed_as_bool", - "can_be_parsed_as_float", - "can_be_parsed_as_int", -] -- cgit v1.2.3 From ba5d3e2541670829697d794943322dd5f2a453af Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Mon, 20 Jul 2020 22:51:14 -0500 Subject: Add toml and yaml parsers --- config_file/parsers/toml_parser.py | 29 ++++++++++++++++++++++++++--- config_file/parsers/yaml_parser.py | 30 +++++++++++++++++++++++++++--- 2 files changed, 53 insertions(+), 6 deletions(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/toml_parser.py b/config_file/parsers/toml_parser.py index 4905aec..d369003 100644 --- a/config_file/parsers/toml_parser.py +++ b/config_file/parsers/toml_parser.py @@ -1,5 +1,28 @@ -from config_file.parsers import AbstractParser +try: + import tomlkit + TOML_AVAILABLE = True +except ImportError: + TOML_AVAILABLE = False -class TomlParser(AbstractParser): - """The TomlParser allows use of toml files with ConfigFile.""" +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 `toml` 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 index a45d7f6..77b59fe 100644 --- a/config_file/parsers/yaml_parser.py +++ b/config_file/parsers/yaml_parser.py @@ -1,5 +1,29 @@ -from config_file.parsers import AbstractParser +try: + import yaml + YAML_AVAILABLE = True -class YamlParser(AbstractParser): - pass + # Conform yaml to json and + # toml package syntax + yaml.loads = yaml.load + yaml.dumps = yaml.dump +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 `PyYaml` is installed, but a yaml " + "file was attempted to be used. Install the `toml` " + "extra first with `pip install config-file[toml]`." + ) + + super().__init__( + file_contents=file_contents, module=yaml, decode_error=yaml.YAMLError + ) -- cgit v1.2.3 From 65d4715b0b2b9974d95ac36271caa8e177bc98fa Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Mon, 20 Jul 2020 22:51:51 -0500 Subject: Add BaseParser for all other parsers This allows one implementation for all parsers, with the parsers overriding it for a custom one if needed for that parser. --- config_file/parsers/base_parser.py | 86 ++++++++++++++++++++++ config_file/parsers/ini_parser.py | 145 ++++++++++--------------------------- config_file/parsers/json_parser.py | 127 ++------------------------------ 3 files changed, 130 insertions(+), 228 deletions(-) create mode 100644 config_file/parsers/base_parser.py (limited to 'config_file/parsers') diff --git a/config_file/parsers/base_parser.py b/config_file/parsers/base_parser.py new file mode 100644 index 0000000..09fbbbf --- /dev/null +++ b/config_file/parsers/base_parser.py @@ -0,0 +1,86 @@ +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, decode_error): + 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 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 + + content_reference = content_reference[key] + + def delete(self, key) -> None: + try: + if "." not in key: + del self.parsed_content[key] + else: + 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] + except KeyError: + raise MissingKeyError(f"The specified key '{key}' was not found.") + + def stringify(self) -> str: + return self.__module.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/ini_parser.py b/config_file/parsers/ini_parser.py index 164ff6d..2a29ba7 100644 --- a/config_file/parsers/ini_parser.py +++ b/config_file/parsers/ini_parser.py @@ -1,124 +1,53 @@ import configparser from io import StringIO -from config_file.exceptions import ParsingError -from config_file.parsers.abstract_parser import AbstractParser -from config_file.parsers.parse_value import parse_value -from config_file.utils import split_on_dot +from .base_parser import BaseParser -class IniParser(AbstractParser): - 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. +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. - :param section_key: The key to set from the config file. e.g. 'section1.key' + It is used as the `module` parameter + for BaseParser, which requires us to have a + `dumps` and `loads` method. + """ - :param value: The value to set the key to. It can be any type that can - be converted to a string. + @staticmethod + def loads(file_contents: str) -> dict: + parser = configparser.ConfigParser() + parser.read_string(file_contents) - :return: True if the setting was successful. + return IniParserCompatibility.__create_configparser_dict(parser) - :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. + @staticmethod + def dumps(file_contents: dict) -> str: + parser = configparser.ConfigParser() + buffer = StringIO() - :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." - ) + parser.read_dict(file_contents) + parser.write(buffer) - self.parsed_content.remove_section(section_key) - return True + return buffer.getvalue() - 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}." - ) + @staticmethod + def __create_configparser_dict(parser: configparser.ConfigParser) -> dict: + result = {} + items = dict(parser.items()) - self.parsed_content.remove_option(section, key) - return True + for section in parser.sections(): + result.update({str(section): dict(items[section])}) - def stringify(self) -> str: - buffer = StringIO() - self.parsed_content.write(buffer) - return buffer.getvalue() + return result - 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) +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/json_parser.py b/config_file/parsers/json_parser.py index 237c0b5..5314cd7 100644 --- a/config_file/parsers/json_parser.py +++ b/config_file/parsers/json_parser.py @@ -1,128 +1,15 @@ import json -from config_file.exceptions import ParsingError -from config_file.nested_lookup import ( - get_occurrence_of_key, - nested_delete, - nested_lookup, - nested_update, -) -from config_file.parsers import AbstractParser, parse_value -from config_file.utils import split_on_dot +from .base_parser import BaseParser -class JsonParser(AbstractParser): - """ - 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', all=True) - >>> [{ "key2": "foo", "key1": "bar" }, "bar"] - """ - +class JsonParser(BaseParser): 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, 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 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 all: - result = nested_lookup(key, self.parsed_content) - elif "." in key: - split_keys = split_on_dot(key) - result = self.parsed_content - - key_causing_error = None - try: - for key in split_keys: - key_causing_error = key - result = result[key] - except TypeError: - raise ParsingError( - f"Cannot get {key} because {key_causing_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, all: bool = False): - if 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, all: bool = False): - if 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 + 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) - - def has(self, search_key: str) -> bool: - return get_occurrence_of_key(self.parsed_content, key=search_key) > 0 -- cgit v1.2.3 From d8ee572672c6d5429257664c5339b23e0c84c55a Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Wed, 29 Jul 2020 20:54:42 -0500 Subject: Move IniParserCompatibility to new file --- config_file/parsers/ini_parser.py | 44 ++------------------------------ config_file/parsers/ini_parser_compat.py | 42 ++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 42 deletions(-) create mode 100644 config_file/parsers/ini_parser_compat.py (limited to 'config_file/parsers') diff --git a/config_file/parsers/ini_parser.py b/config_file/parsers/ini_parser.py index 2a29ba7..8dc7f47 100644 --- a/config_file/parsers/ini_parser.py +++ b/config_file/parsers/ini_parser.py @@ -1,47 +1,7 @@ import configparser -from io import StringIO from .base_parser import BaseParser - - -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 +from .ini_parser_compat import IniParserCompatibility class IniParser(BaseParser): @@ -50,4 +10,4 @@ class IniParser(BaseParser): file_contents=file_contents, module=IniParserCompatibility, decode_error=configparser.Error, - ) + ) \ No newline at end of file diff --git a/config_file/parsers/ini_parser_compat.py b/config_file/parsers/ini_parser_compat.py new file mode 100644 index 0000000..9dfea2e --- /dev/null +++ b/config_file/parsers/ini_parser_compat.py @@ -0,0 +1,42 @@ +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 -- cgit v1.2.3 From 5b9cbecb01b3ac11f553a62d3ee6135a789943a7 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Wed, 29 Jul 2020 21:32:00 -0500 Subject: Remove duplication from `can_be_parsed_as_float` --- config_file/parsers/parse_value.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/parse_value.py b/config_file/parsers/parse_value.py index 26bdf2e..5f6dfe3 100644 --- a/config_file/parsers/parse_value.py +++ b/config_file/parsers/parse_value.py @@ -75,7 +75,7 @@ def can_be_parsed_as_float(value) -> bool: return False if value.startswith("-"): - return bool(re.match(FLOAT_REGEX, value[1:])) + value = value[1:] return bool(re.match(FLOAT_REGEX, value)) -- cgit v1.2.3 From 47a58715546d780a5df8d362ab5eeedd3813ecdb Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Wed, 29 Jul 2020 21:32:57 -0500 Subject: Use ruamel.yaml for yaml parser --- config_file/parsers/yaml_parser.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/yaml_parser.py b/config_file/parsers/yaml_parser.py index 77b59fe..1937e17 100644 --- a/config_file/parsers/yaml_parser.py +++ b/config_file/parsers/yaml_parser.py @@ -1,12 +1,7 @@ try: - import yaml + from ruamel.yaml import YAML, YAMLError, round_trip_dump, round_trip_load YAML_AVAILABLE = True - - # Conform yaml to json and - # toml package syntax - yaml.loads = yaml.load - yaml.dumps = yaml.dump except ImportError: YAML_AVAILABLE = False @@ -23,7 +18,11 @@ class YamlParser(BaseParser): "file was attempted to be used. Install the `toml` " "extra first with `pip install config-file[toml]`." ) + + yaml = YAML(typ='safe') + yaml.loads = round_trip_load + yaml.dumps = round_trip_dump super().__init__( - file_contents=file_contents, module=yaml, decode_error=yaml.YAMLError + file_contents=file_contents, module=yaml, decode_error=YAMLError ) -- cgit v1.2.3 From 03811338b3bc9d07d491454ba5646ba2dd912463 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Wed, 29 Jul 2020 21:33:54 -0500 Subject: Fix `get`, `set`, `delete` and `has` in BaseParser --- config_file/parsers/base_parser.py | 39 ++++++++++++++++++++++++++------------ config_file/parsers/toml_parser.py | 1 - 2 files changed, 27 insertions(+), 13 deletions(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/base_parser.py b/config_file/parsers/base_parser.py index 09fbbbf..546450c 100644 --- a/config_file/parsers/base_parser.py +++ b/config_file/parsers/base_parser.py @@ -1,4 +1,5 @@ from typing import Any +from types import ModuleType from config_file.exceptions import MissingKeyError, ParsingError from config_file.nested_lookup import get_occurrence_of_key @@ -8,7 +9,9 @@ from .abstract_parser import AbstractParser class BaseParser(AbstractParser): - def __init__(self, file_contents: str, module, decode_error): + def __init__( + self, file_contents: str, module: ModuleType, decode_error: Exception + ): super().__init__(file_contents) self.__module = module self.__decode_error = decode_error @@ -39,9 +42,9 @@ class BaseParser(AbstractParser): for key in split_keys: key_causing_error = key result = result[key] - except TypeError: + except (KeyError, TypeError): raise ParsingError( - f"Cannot get {search_key} because " + f"Cannot `get` {search_key} because " f"{key_causing_error} is not subscriptable." ) @@ -59,9 +62,13 @@ class BaseParser(AbstractParser): content_reference[key] = value return - content_reference = content_reference[key] + try: + content_reference = content_reference[key] + except KeyError: + content_reference[key] = {} + content_reference = content_reference[key] - def delete(self, key) -> None: + def delete(self, key: str) -> None: try: if "." not in key: del self.parsed_content[key] @@ -69,18 +76,26 @@ class BaseParser(AbstractParser): indexes = split_on_dot(key) indexes_length = len(indexes) - ref = self.parsed_content + content_reference = self.parsed_content for index, key in enumerate(indexes): if index == indexes_length - 1: - del ref[key] + del content_reference[key] break - ref = ref[key] - except KeyError: - raise MissingKeyError(f"The specified key '{key}' was not found.") + 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) -> bool: - return get_occurrence_of_key(self.parsed_content, key=search_key) > 0 + 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/toml_parser.py b/config_file/parsers/toml_parser.py index d369003..58e20b9 100644 --- a/config_file/parsers/toml_parser.py +++ b/config_file/parsers/toml_parser.py @@ -9,7 +9,6 @@ from config_file.exceptions import MissingDependencyError from .base_parser import BaseParser - class TomlParser(BaseParser): def __init__(self, file_contents: str): if not TOML_AVAILABLE: -- cgit v1.2.3 From 3c1ebfaf0db4a29cc8ee9ba742c6d8925dc79cff Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Wed, 29 Jul 2020 23:53:15 -0500 Subject: Allow string lists and dicts to be auto parsed --- config_file/parsers/parse_value.py | 61 ++++++++++++++++++++++++++++++++------ 1 file changed, 52 insertions(+), 9 deletions(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/parse_value.py b/config_file/parsers/parse_value.py index 5f6dfe3..aa8d1fe 100644 --- a/config_file/parsers/parse_value.py +++ b/config_file/parsers/parse_value.py @@ -19,20 +19,12 @@ Example: can_be_parsed_as_int("-5") -> True parse_value("-5") -> -5 """ +import ast 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 = {} @@ -49,6 +41,21 @@ def parse_value(value): return parsed + 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 can_be_parsed_as_dict(value): + return parse_value(ast.literal_eval(value)) + + if can_be_parsed_as_list(value): + return parse_value(ast.literal_eval(value)) + return value @@ -88,3 +95,39 @@ def can_be_parsed_as_bool(value) -> bool: return False return value.lower() == "true" or value.lower() == "false" + + +def can_be_parsed_as_dict(value) -> bool: + if type(value) is dict: + return True + + if type(value) is not str: + return False + + value = value.strip() + if value[0] == "{" and value[-1] == "}": + try: + ast.literal_eval(value) + return True + except SyntaxError: + return False + + return False + + +def can_be_parsed_as_list(value) -> bool: + if type(value) is dict: + return True + + if type(value) is not str: + return False + + value = value.strip() + if value[0] == "[" and value[-1] == "]": + try: + ast.literal_eval(value) + return True + except SyntaxError: + return False + + return False -- cgit v1.2.3 From e40a3a23fb6649758f40e9b67e3f3100ec23f116 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Thu, 30 Jul 2020 12:57:56 -0500 Subject: Fix missing dependency error messages for yaml and toml --- config_file/parsers/toml_parser.py | 3 ++- config_file/parsers/yaml_parser.py | 10 +++++----- 2 files changed, 7 insertions(+), 6 deletions(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/toml_parser.py b/config_file/parsers/toml_parser.py index 58e20b9..1c7f8a7 100644 --- a/config_file/parsers/toml_parser.py +++ b/config_file/parsers/toml_parser.py @@ -9,11 +9,12 @@ 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 `toml` is installed, but a toml " + "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]`." ) diff --git a/config_file/parsers/yaml_parser.py b/config_file/parsers/yaml_parser.py index 1937e17..babe873 100644 --- a/config_file/parsers/yaml_parser.py +++ b/config_file/parsers/yaml_parser.py @@ -14,12 +14,12 @@ class YamlParser(BaseParser): def __init__(self, file_contents: str): if not YAML_AVAILABLE: raise MissingDependencyError( - "It doesn't appear `PyYaml` is installed, but a yaml " - "file was attempted to be used. Install the `toml` " - "extra first with `pip install config-file[toml]`." + "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 = YAML(typ="safe") yaml.loads = round_trip_load yaml.dumps = round_trip_dump -- cgit v1.2.3 From 5ac52d231e56f60a22ba3f755415c4aa43a14d83 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sat, 1 Aug 2020 11:20:39 -0500 Subject: Add tests to parse_value and fix bugs in it --- config_file/parsers/parse_value.py | 78 ++++++++++++++++++++++++++------------ 1 file changed, 53 insertions(+), 25 deletions(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/parse_value.py b/config_file/parsers/parse_value.py index aa8d1fe..28f1ccb 100644 --- a/config_file/parsers/parse_value.py +++ b/config_file/parsers/parse_value.py @@ -22,10 +22,22 @@ parse_value("-5") -> -5 import ast import re from distutils.util import strtobool +from typing import Any -def parse_value(value): - if type(value) is dict: +def parse_value(value: Any) -> Any: + """Parse a value into native type. + + 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: @@ -33,7 +45,7 @@ def parse_value(value): return parsed - if type(value) is list: + if isinstance(value, list): parsed = [] for item in value: @@ -42,92 +54,108 @@ def parse_value(value): return parsed if can_be_parsed_as_int(value): - return int(value) + return int(value.strip()) if isinstance(value, str) else int(value) if can_be_parsed_as_float(value): - return float(value) + return float(value.strip()) if isinstance(value, str) else float(value) if can_be_parsed_as_bool(value): - return value if type(value) is bool else bool(strtobool(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)) + return parse_value(ast.literal_eval(value.strip())) if can_be_parsed_as_list(value): - return parse_value(ast.literal_eval(value)) + return parse_value(ast.literal_eval(value.strip())) return value -def can_be_parsed_as_int(value) -> bool: - if type(value) is int: +def can_be_parsed_as_int(value: Any) -> bool: + """Check whether a value can be parsed as a integer. + + 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 type(value) is bool: return True - if type(value) is not str: + 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) -> bool: +def can_be_parsed_as_float(value: Any) -> bool: FLOAT_REGEX = r"^\d*\.\d+$" - if type(value) is float: + if isinstance(value, float): return True - if type(value) is not str: + 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) -> bool: - if type(value) is bool: +def can_be_parsed_as_bool(value: Any) -> bool: + if isinstance(value, bool): return True - if type(value) is not str: + if not isinstance(value, str): return False - return value.lower() == "true" or value.lower() == "false" + value = value.lower().strip() + + return value == "true" or value == "false" -def can_be_parsed_as_dict(value) -> bool: - if type(value) is dict: +def can_be_parsed_as_dict(value: Any) -> bool: + if isinstance(value, dict): return True - if type(value) is not str: + if not isinstance(value, str): return False value = value.strip() + if value[0] == "{" and value[-1] == "}": try: ast.literal_eval(value) return True - except SyntaxError: + except Exception: return False return False def can_be_parsed_as_list(value) -> bool: - if type(value) is dict: + if isinstance(value, list): return True - if type(value) is not str: + if not isinstance(value, str): return False value = value.strip() + if value[0] == "[" and value[-1] == "]": try: ast.literal_eval(value) return True - except SyntaxError: + except Exception: return False return False -- cgit v1.2.3 From b1c23487c33fc2ad5503b6340b17980a326918c8 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sat, 1 Aug 2020 11:53:56 -0500 Subject: Lint files --- config_file/parsers/base_parser.py | 9 +++------ config_file/parsers/ini_parser.py | 2 +- 2 files changed, 4 insertions(+), 7 deletions(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/base_parser.py b/config_file/parsers/base_parser.py index 546450c..c2a7d71 100644 --- a/config_file/parsers/base_parser.py +++ b/config_file/parsers/base_parser.py @@ -1,5 +1,5 @@ -from typing import Any 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 @@ -9,9 +9,7 @@ from .abstract_parser import AbstractParser class BaseParser(AbstractParser): - def __init__( - self, file_contents: str, module: ModuleType, decode_error: Exception - ): + def __init__(self, file_contents: str, module: ModuleType, decode_error: Exception): super().__init__(file_contents) self.__module = module self.__decode_error = decode_error @@ -92,10 +90,9 @@ class BaseParser(AbstractParser): 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 index 8dc7f47..72974f1 100644 --- a/config_file/parsers/ini_parser.py +++ b/config_file/parsers/ini_parser.py @@ -10,4 +10,4 @@ class IniParser(BaseParser): file_contents=file_contents, module=IniParserCompatibility, decode_error=configparser.Error, - ) \ No newline at end of file + ) -- cgit v1.2.3 From c7922b08bf010375416138b2ca85fe88fd8edcef Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sat, 1 Aug 2020 11:54:22 -0500 Subject: Expand on docstrings for parse_value file --- config_file/parsers/parse_value.py | 95 ++++++++++++++++++++++++++++++-------- 1 file changed, 76 insertions(+), 19 deletions(-) (limited to 'config_file/parsers') diff --git a/config_file/parsers/parse_value.py b/config_file/parsers/parse_value.py index 28f1ccb..12032d6 100644 --- a/config_file/parsers/parse_value.py +++ b/config_file/parsers/parse_value.py @@ -1,7 +1,13 @@ -""" -This module allows you to parse a string into its native type. +"""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. -Example: parse_value('5') -> 5 (int) parse_value('-5') -> -5 (int) @@ -13,20 +19,7 @@ Example: parse_value('true') -> True (bool) parse_value('FALSE') -> False (bool) - -"5".isdigit() -> True -"-5".isdigit() -> False -can_be_parsed_as_int("-5") -> True -parse_value("-5") -> -5 -""" -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(" [ [ [ [] ]] ] ") -> [[[[]]]] (list) Args: value: The value to parse. @@ -74,13 +67,18 @@ def parse_value(value: Any) -> Any: 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 type(value) is bool: + if isinstance(value, int) and not isinstance(value, bool): return True if not isinstance(value, str): @@ -95,6 +93,20 @@ def can_be_parsed_as_int(value: Any) -> bool: 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): @@ -112,6 +124,20 @@ def can_be_parsed_as_float(value: Any) -> bool: 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 @@ -124,6 +150,21 @@ def can_be_parsed_as_bool(value: Any) -> bool: 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 @@ -142,7 +183,23 @@ def can_be_parsed_as_dict(value: Any) -> bool: return False -def can_be_parsed_as_list(value) -> bool: +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 -- cgit v1.2.3 From 59eeb1321fbad41dce7c971778e37ac1943fda3b Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Wed, 5 Aug 2020 20:39:28 -0500 Subject: 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. --- config_file/parsers/__init__.py | 0 config_file/parsers/abstract_parser.py | 117 ----------------- config_file/parsers/base_parser.py | 98 -------------- config_file/parsers/ini_parser.py | 13 -- config_file/parsers/ini_parser_compat.py | 42 ------ config_file/parsers/json_parser.py | 15 --- config_file/parsers/parse_value.py | 218 ------------------------------- config_file/parsers/toml_parser.py | 28 ---- config_file/parsers/yaml_parser.py | 28 ---- 9 files changed, 559 deletions(-) delete mode 100644 config_file/parsers/__init__.py delete mode 100644 config_file/parsers/abstract_parser.py delete mode 100644 config_file/parsers/base_parser.py delete mode 100644 config_file/parsers/ini_parser.py delete mode 100644 config_file/parsers/ini_parser_compat.py delete mode 100644 config_file/parsers/json_parser.py delete mode 100644 config_file/parsers/parse_value.py delete mode 100644 config_file/parsers/toml_parser.py delete mode 100644 config_file/parsers/yaml_parser.py (limited to 'config_file/parsers') diff --git a/config_file/parsers/__init__.py b/config_file/parsers/__init__.py deleted file mode 100644 index e69de29..0000000 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 - ) -- cgit v1.2.3