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/config_file.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'config_file/config_file.py') diff --git a/config_file/config_file.py b/config_file/config_file.py index 91202da..805fc49 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -1,15 +1,17 @@ import inspect from pathlib import Path, PurePath from shutil import copyfile +from typing import Type, Union -from config_file.parsers.base_parser import BaseParser, ParsingError +from config_file.parsers.base_parser import BaseParser from config_file.parsers.ini_parser import IniParser from config_file.parsers.json_parser import JsonParser from config_file.utils import split_on_dot +from config_file.exceptions import ParsingError class ConfigFile: - def __init__(self, file_path, parser: BaseParser = None): + def __init__(self, file_path: Type[Union[str, PurePath]], parser: Type[BaseParser] = None) -> None: """ Saves the config file path and expands it if needed, reads in the file contents, and determines what parser should be used for @@ -17,7 +19,6 @@ class ConfigFile: :param file_path: The path to your configuration file. :param parser: A custom parser you'd like used for your config file. - It must be a concrete implementation of BaseParser. :raises ValueError: If the specified file path does not have an extension that is supported or it is a directory. @@ -27,7 +28,7 @@ class ConfigFile: self.parser = self.__determine_parser(file_path, parser) @staticmethod - def __create_config_path(file_path, original: bool = False) -> str: + def __create_config_path(file_path: Type[Union[str, PurePath]], original: bool = False) -> str: if isinstance(file_path, PurePath): file_path = str(file_path) @@ -40,11 +41,11 @@ class ConfigFile: file_path = ".".join(file_parts) if Path(file_path).is_dir(): - raise ValueError(f"The specified config file ({file_path}) is a directory.") + raise ValueError("The specified config file ({}) is a directory.".format(file_path)) return file_path - def __determine_parser(self, file_path, parser: BaseParser): + def __determine_parser(self, file_path: Type[Union[str, PurePath]], parser: Type[BaseParser]) -> BaseParser: if isinstance(file_path, PurePath): file_path = str(file_path) @@ -58,8 +59,7 @@ class ConfigFile: return JsonParser(self.contents) else: raise ValueError( - f"File path contains an unsupported or " - f"unrecognized file type: {file_path}" + "File path contains an unsupported or unrecognized file type: {}".format(file_path) ) def __read_config_file(self): @@ -134,7 +134,7 @@ class ConfigFile: if not Path(original_file_path).exists(): raise OSError( - f"The {original_file_path} file to restore to does not exist." + "The {} file to restore to does not exist.".format(original_file_path) ) Path(self.path).expanduser().unlink() -- cgit v1.2.3 From 8d377a1edf2ac2343fa374cb51a07a72a0316ed2 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sat, 20 Jun 2020 13:47:27 -0500 Subject: Remove taskipy from tox & add default to parser in __determine_parser Taskipy uses f-strings which break on 3.5. --- config_file/config_file.py | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) (limited to 'config_file/config_file.py') diff --git a/config_file/config_file.py b/config_file/config_file.py index 805fc49..1cddd20 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -11,7 +11,9 @@ from config_file.exceptions import ParsingError class ConfigFile: - def __init__(self, file_path: Type[Union[str, PurePath]], parser: Type[BaseParser] = None) -> None: + def __init__( + self, file_path: Type[Union[str, PurePath]], parser: Type[BaseParser] = None + ) -> None: """ Saves the config file path and expands it if needed, reads in the file contents, and determines what parser should be used for @@ -28,7 +30,9 @@ class ConfigFile: self.parser = self.__determine_parser(file_path, parser) @staticmethod - def __create_config_path(file_path: Type[Union[str, PurePath]], original: bool = False) -> str: + def __create_config_path( + file_path: Type[Union[str, PurePath]], original: bool = False + ) -> str: if isinstance(file_path, PurePath): file_path = str(file_path) @@ -41,11 +45,15 @@ class ConfigFile: file_path = ".".join(file_parts) if Path(file_path).is_dir(): - raise ValueError("The specified config file ({}) is a directory.".format(file_path)) + raise ValueError( + "The specified config file ({}) is a directory.".format(file_path) + ) return file_path - def __determine_parser(self, file_path: Type[Union[str, PurePath]], parser: Type[BaseParser]) -> BaseParser: + def __determine_parser( + self, file_path: Type[Union[str, PurePath]], parser: Type[BaseParser] = None + ) -> BaseParser: if isinstance(file_path, PurePath): file_path = str(file_path) @@ -59,7 +67,9 @@ class ConfigFile: return JsonParser(self.contents) else: raise ValueError( - "File path contains an unsupported or unrecognized file type: {}".format(file_path) + "File path contains an unsupported or unrecognized file type: {}".format( + file_path + ) ) def __read_config_file(self): -- cgit v1.2.3 From 95c47a183409fabed81f078a70967f053679737e Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sat, 20 Jun 2020 15:13:53 -0500 Subject: Change path, parser, and contents to be properties Also, restore_original now raises a FileNotFoundError. --- config_file/config_file.py | 94 +++++++++++++++++++++++----------------------- 1 file changed, 47 insertions(+), 47 deletions(-) (limited to 'config_file/config_file.py') diff --git a/config_file/config_file.py b/config_file/config_file.py index 1cddd20..d4131de 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -1,18 +1,18 @@ import inspect -from pathlib import Path, PurePath +from pathlib import Path from shutil import copyfile from typing import Type, Union +from config_file.exceptions import ParsingError from config_file.parsers.base_parser import BaseParser from config_file.parsers.ini_parser import IniParser from config_file.parsers.json_parser import JsonParser -from config_file.utils import split_on_dot -from config_file.exceptions import ParsingError +from config_file.utils import read_file, split_on_dot class ConfigFile: def __init__( - self, file_path: Type[Union[str, PurePath]], parser: Type[BaseParser] = None + self, file_path: Type[Union[str, Path]], parser: Type[BaseParser] = None ) -> None: """ Saves the config file path and expands it if needed, reads in @@ -25,19 +25,29 @@ class ConfigFile: :raises ValueError: If the specified file path does not have an extension that is supported or it is a directory. """ - self.path = self.__create_config_path(file_path) - self.contents = self.__read_config_file() - self.parser = self.__determine_parser(file_path, parser) + if type(file_path) is not Path: + file_path = Path(file_path) - @staticmethod - def __create_config_path( - file_path: Type[Union[str, PurePath]], original: bool = False - ) -> str: - if isinstance(file_path, PurePath): - file_path = str(file_path) + self.__path = self.__create_config_path(file_path) + self.__contents = read_file(self.__path) + self.__parser = self.__determine_parser(file_path, parser) + + @property + def path(self) -> Path: + return self.__path + + @property + def contents(self) -> str: + return self.__contents - if len(file_path) > 1 and file_path[0] == "~": - return str(Path(file_path).expanduser()) + @property + def parser(self) -> Type[BaseParser]: + return self.__parser + + @staticmethod + def __create_config_path(file_path: Path, original: bool = False) -> str: + if len(file_path.parts) >= 1 and file_path.parts[0] == "~": + return file_path.expanduser() if original: file_parts = split_on_dot(file_path, only_last_dot=True) @@ -52,30 +62,21 @@ class ConfigFile: return file_path def __determine_parser( - self, file_path: Type[Union[str, PurePath]], parser: Type[BaseParser] = None + self, file_path: Path, parser: Type[BaseParser] = None ) -> BaseParser: - if isinstance(file_path, PurePath): - file_path = str(file_path) - if parser is not None and not inspect.isabstract(parser): - return parser(self.contents) + return parser(self.__contents) file_type = split_on_dot(file_path, only_last_dot=True)[-1] if file_type == "ini": - return IniParser(self.contents) + return IniParser(self.__contents) elif file_type == "json": - return JsonParser(self.contents) + return JsonParser(self.__contents) else: raise ValueError( - "File path contains an unsupported or unrecognized file type: {}".format( - file_path - ) + "File path contains an unrecognized file type: {}".format(file_path) ) - def __read_config_file(self): - with open(self.path, "r") as file: - return file.read() - def get(self, key: str, parse_types: bool = False, return_type=None, default=None): """ Retrieve the value of a key. @@ -92,10 +93,10 @@ class ConfigFile: :return: The value of the key. """ if default is None: - key_value = self.parser.get(key, parse_types=parse_types) + key_value = self.__parser.get(key, parse_types=parse_types) else: try: - key_value = self.parser.get(key, parse_types=parse_types) + key_value = self.__parser.get(key, parse_types=parse_types) except ParsingError: return default @@ -103,15 +104,15 @@ class ConfigFile: def set(self, key: str, value): """Sets the value of a key.""" - return self.parser.set(key, value) + return self.__parser.set(key, value) def delete(self, section_key: str): """Deletes a key/value pair or entire sections.""" - return self.parser.delete(section_key) + return self.__parser.delete(section_key) def stringify(self) -> str: """Convert the parsed internal representation of the file back into a string.""" - return self.parser.stringify() + return self.__parser.stringify() def has(self, section_key: str) -> bool: """ @@ -121,7 +122,7 @@ class ConfigFile: Some formats, like JSON, do not have sections and therefore, it would only be checking if the key exists. """ - return self.parser.has(section_key) + return self.__parser.has(section_key) def restore_original(self, original_file_path=None): """ @@ -134,23 +135,22 @@ class ConfigFile: method would look for a config.original.json in the same folder by default. :return: True if the reset succeeded - :raises OSError: If the original configuration file is not present or if an - error occurred when trying to copy the file. + :raises FileNotFoundError: If the original configuration file does not exist + :raises OSError: If self.path is not writable + :raises SameFileError: If self.path and original_file_path are the same file. """ if original_file_path is None: - original_file_path = self.__create_config_path( - str(self.path), original=True - ) + original_file_path = self.__create_config_path(self.__path, original=True) if not Path(original_file_path).exists(): - raise OSError( + raise FileNotFoundError( "The {} file to restore to does not exist.".format(original_file_path) ) - Path(self.path).expanduser().unlink() - copyfile(original_file_path, self.path) - self.contents = self.__read_config_file() - self.parser.parsed_content = self.parser.parse(self.contents) + self.__path.expanduser().unlink() + copyfile(original_file_path, self.__path) + self.__contents = read_file(self.path) + self.__parser.parsed_content = self.__parser.parse(self.__contents) return True @@ -159,7 +159,7 @@ class ConfigFile: Save the configuration changes by writing the file out to the specified path :return: True if the save succeeded. """ - with open(self.path, "w") as config_file: - config_file.write(self.parser.stringify()) + with open(self.__path, "w") as config_file: + config_file.write(self.__parser.stringify()) return True -- 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/config_file.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'config_file/config_file.py') diff --git a/config_file/config_file.py b/config_file/config_file.py index d4131de..3af1083 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -55,9 +55,7 @@ class ConfigFile: file_path = ".".join(file_parts) if Path(file_path).is_dir(): - raise ValueError( - "The specified config file ({}) is a directory.".format(file_path) - ) + raise ValueError(f"The specified config file ({file_path}) is a directory.") return file_path @@ -74,7 +72,7 @@ class ConfigFile: return JsonParser(self.__contents) else: raise ValueError( - "File path contains an unrecognized file type: {}".format(file_path) + f"File path contains an unrecognized file type: {file_path}" ) def get(self, key: str, parse_types: bool = False, return_type=None, default=None): @@ -91,6 +89,8 @@ class ConfigFile: :param default: The default value to return if the value of the key is empty. :return: The value of the key. + + :raises ValueError: If the value is not able to be coerced into return_type """ if default is None: key_value = self.__parser.get(key, parse_types=parse_types) @@ -144,7 +144,7 @@ class ConfigFile: if not Path(original_file_path).exists(): raise FileNotFoundError( - "The {} file to restore to does not exist.".format(original_file_path) + f"The {original_file_path} file to restore to does not exist." ) self.__path.expanduser().unlink() -- 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/config_file.py | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) (limited to 'config_file/config_file.py') diff --git a/config_file/config_file.py b/config_file/config_file.py index 3af1083..431521a 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -1,7 +1,7 @@ import inspect -from pathlib import Path +from pathlib import Path, PurePath from shutil import copyfile -from typing import Type, Union +from typing import Any, Type, Union from config_file.exceptions import ParsingError from config_file.parsers.base_parser import BaseParser @@ -12,7 +12,9 @@ from config_file.utils import read_file, split_on_dot class ConfigFile: def __init__( - self, file_path: Type[Union[str, Path]], parser: Type[BaseParser] = None + self, + file_path: Type[Union[str, Type[PurePath]]], + parser: Type[BaseParser] = None, ) -> None: """ Saves the config file path and expands it if needed, reads in @@ -33,7 +35,7 @@ class ConfigFile: self.__parser = self.__determine_parser(file_path, parser) @property - def path(self) -> Path: + def path(self) -> Type[PurePath]: return self.__path @property @@ -45,7 +47,7 @@ class ConfigFile: return self.__parser @staticmethod - def __create_config_path(file_path: Path, original: bool = False) -> str: + def __create_config_path(file_path: Type[PurePath], original: bool = False) -> str: if len(file_path.parts) >= 1 and file_path.parts[0] == "~": return file_path.expanduser() @@ -60,7 +62,7 @@ class ConfigFile: return file_path def __determine_parser( - self, file_path: Path, parser: Type[BaseParser] = None + self, file_path: Type[PurePath], parser: Type[BaseParser] = None ) -> BaseParser: if parser is not None and not inspect.isabstract(parser): return parser(self.__contents) @@ -75,7 +77,13 @@ class ConfigFile: f"File path contains an unrecognized file type: {file_path}" ) - def get(self, key: str, parse_types: bool = False, return_type=None, default=None): + def get( + self, + key: str, + parse_types: bool = False, + return_type: Any = None, + default: Any = None, + ) -> Any: """ Retrieve the value of a key. @@ -102,7 +110,7 @@ class ConfigFile: return return_type(key_value) if return_type else key_value - def set(self, key: str, value): + def set(self, key: str, value: Any) -> bool: """Sets the value of a key.""" return self.__parser.set(key, value) @@ -124,7 +132,7 @@ class ConfigFile: """ return self.__parser.has(section_key) - def restore_original(self, original_file_path=None): + def restore_original(self, original_file_path: Union[str, Type[PurePath]] = None): """ Restores the original the config file by deleting it and copying the original back in its place. The internal contents of this config file object are then set @@ -154,7 +162,7 @@ class ConfigFile: return True - def save(self): + def save(self) -> bool: """ Save the configuration changes by writing the file out to the specified path :return: True if the save succeeded. -- 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/config_file.py | 1 + 1 file changed, 1 insertion(+) (limited to 'config_file/config_file.py') diff --git a/config_file/config_file.py b/config_file/config_file.py index 431521a..6ded72b 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -83,6 +83,7 @@ class ConfigFile: parse_types: bool = False, return_type: Any = None, default: Any = None, + all: bool = False, ) -> Any: """ Retrieve the value of a key. -- 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/config_file.py | 33 ++++----------------------------- 1 file changed, 4 insertions(+), 29 deletions(-) (limited to 'config_file/config_file.py') diff --git a/config_file/config_file.py b/config_file/config_file.py index 6ded72b..e037a82 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -4,10 +4,8 @@ from shutil import copyfile from typing import Any, Type, Union from config_file.exceptions import ParsingError -from config_file.parsers.base_parser import BaseParser -from config_file.parsers.ini_parser import IniParser -from config_file.parsers.json_parser import JsonParser -from config_file.utils import read_file, split_on_dot +from config_file.parsers import BaseParser, IniParser, JsonParser +from config_file.utils import create_config_path, read_file, split_on_dot class ConfigFile: @@ -30,7 +28,7 @@ class ConfigFile: if type(file_path) is not Path: file_path = Path(file_path) - self.__path = self.__create_config_path(file_path) + self.__path = create_config_path(file_path) self.__contents = read_file(self.__path) self.__parser = self.__determine_parser(file_path, parser) @@ -38,29 +36,6 @@ class ConfigFile: def path(self) -> Type[PurePath]: return self.__path - @property - def contents(self) -> str: - return self.__contents - - @property - def parser(self) -> Type[BaseParser]: - return self.__parser - - @staticmethod - def __create_config_path(file_path: Type[PurePath], original: bool = False) -> str: - if len(file_path.parts) >= 1 and file_path.parts[0] == "~": - return file_path.expanduser() - - if original: - file_parts = split_on_dot(file_path, only_last_dot=True) - file_parts.insert(-1, "original") - file_path = ".".join(file_parts) - - if Path(file_path).is_dir(): - raise ValueError(f"The specified config file ({file_path}) is a directory.") - - return file_path - def __determine_parser( self, file_path: Type[PurePath], parser: Type[BaseParser] = None ) -> BaseParser: @@ -149,7 +124,7 @@ class ConfigFile: :raises SameFileError: If self.path and original_file_path are the same file. """ if original_file_path is None: - original_file_path = self.__create_config_path(self.__path, original=True) + original_file_path = create_config_path(self.__path, original=True) if not Path(original_file_path).exists(): raise FileNotFoundError( -- cgit v1.2.3 From 34d81c75ee3e98c0455393a07329296f461cad53 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sun, 12 Jul 2020 09:10:37 -0500 Subject: Add more type hints to ConfigFile --- config_file/config_file.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'config_file/config_file.py') diff --git a/config_file/config_file.py b/config_file/config_file.py index e037a82..de8b851 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -25,7 +25,7 @@ class ConfigFile: :raises ValueError: If the specified file path does not have an extension that is supported or it is a directory. """ - if type(file_path) is not Path: + if not isinstance(file_path, Path): file_path = Path(file_path) self.__path = create_config_path(file_path) @@ -38,7 +38,7 @@ class ConfigFile: def __determine_parser( self, file_path: Type[PurePath], parser: Type[BaseParser] = None - ) -> BaseParser: + ) -> Type[BaseParser]: if parser is not None and not inspect.isabstract(parser): return parser(self.__contents) @@ -90,7 +90,7 @@ class ConfigFile: """Sets the value of a key.""" return self.__parser.set(key, value) - def delete(self, section_key: str): + def delete(self, section_key: str) -> bool: """Deletes a key/value pair or entire sections.""" return self.__parser.delete(section_key) @@ -108,7 +108,7 @@ class ConfigFile: """ return self.__parser.has(section_key) - def restore_original(self, original_file_path: Union[str, Type[PurePath]] = None): + def restore_original(self, original_file_path: Union[str, Type[PurePath]] = None) -> bool: """ Restores the original the config file by deleting it and copying the original back in its place. The internal contents of this config file object are then set @@ -133,7 +133,7 @@ class ConfigFile: self.__path.expanduser().unlink() copyfile(original_file_path, self.__path) - self.__contents = read_file(self.path) + self.__contents = read_file(self.__path) self.__parser.parsed_content = self.__parser.parse(self.__contents) return True -- 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/config_file.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) (limited to 'config_file/config_file.py') diff --git a/config_file/config_file.py b/config_file/config_file.py index de8b851..34df561 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -4,7 +4,7 @@ from shutil import copyfile from typing import Any, Type, Union from config_file.exceptions import ParsingError -from config_file.parsers import BaseParser, IniParser, JsonParser +from config_file.parsers import AbstractParser, IniParser, JsonParser from config_file.utils import create_config_path, read_file, split_on_dot @@ -12,7 +12,7 @@ class ConfigFile: def __init__( self, file_path: Type[Union[str, Type[PurePath]]], - parser: Type[BaseParser] = None, + parser: Type[AbstractParser] = None, ) -> None: """ Saves the config file path and expands it if needed, reads in @@ -37,8 +37,8 @@ class ConfigFile: return self.__path def __determine_parser( - self, file_path: Type[PurePath], parser: Type[BaseParser] = None - ) -> Type[BaseParser]: + self, file_path: Type[PurePath], parser: Type[AbstractParser] = None + ) -> Type[AbstractParser]: if parser is not None and not inspect.isabstract(parser): return parser(self.__contents) @@ -108,7 +108,9 @@ class ConfigFile: """ return self.__parser.has(section_key) - def restore_original(self, original_file_path: Union[str, Type[PurePath]] = None) -> bool: + def restore_original( + self, original_file_path: Union[str, Type[PurePath]] = None + ) -> bool: """ Restores the original the config file by deleting it and copying the original back in its place. The internal contents of this config file object are then set -- cgit v1.2.3 From 7929171083f9d79e4e6b62d7f09189e4de520fe4 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Mon, 20 Jul 2020 22:54:55 -0500 Subject: Remove `all`, start convert to google docstring, add other parsers --- config_file/config_file.py | 168 +++++++++++++++++++++++++++++---------------- 1 file changed, 110 insertions(+), 58 deletions(-) (limited to 'config_file/config_file.py') diff --git a/config_file/config_file.py b/config_file/config_file.py index 34df561..3ac4b91 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -1,18 +1,23 @@ import inspect -from pathlib import Path, PurePath +from pathlib import Path from shutil import copyfile -from typing import Any, Type, Union +from typing import Any, Optional, Type, Union -from config_file.exceptions import ParsingError -from config_file.parsers import AbstractParser, IniParser, JsonParser -from config_file.utils import create_config_path, read_file, split_on_dot +from config_file.exceptions import ParsingError, UnrecognizedFileError +from config_file.parsers.abstract_parser import AbstractParser +from config_file.parsers.ini_parser import IniParser +from config_file.parsers.json_parser import JsonParser +from config_file.parsers.parse_value import parse_value +from config_file.parsers.toml_parser import TomlParser +from config_file.parsers.yaml_parser import YamlParser +from config_file.utils import Default, create_config_path, read_file, split_on_dot class ConfigFile: def __init__( self, - file_path: Type[Union[str, Type[PurePath]]], - parser: Type[AbstractParser] = None, + file_path: Union[str, Path], + parser: Optional[Type[AbstractParser]] = None, ) -> None: """ Saves the config file path and expands it if needed, reads in @@ -33,23 +38,42 @@ class ConfigFile: self.__parser = self.__determine_parser(file_path, parser) @property - def path(self) -> Type[PurePath]: + def path(self) -> Path: return self.__path def __determine_parser( - self, file_path: Type[PurePath], parser: Type[AbstractParser] = None + self, file_path: Path, parser: Optional[Type[AbstractParser]] = None ) -> Type[AbstractParser]: if parser is not None and not inspect.isabstract(parser): return parser(self.__contents) - file_type = split_on_dot(file_path, only_last_dot=True)[-1] + try: + file_type = split_on_dot(file_path, only_last_dot=True)[-1] + except ValueError: + raise UnrecognizedFileError( + "Tried to determine a parser to use, but the file at " + f"{file_path} does not have an extension." + ) + + return self.__find_parser_by_file_type( + file_type=file_type, file_contents=self.__contents, file_path=self.__path + ) + + @staticmethod + def __find_parser_by_file_type( + file_type: str, file_path: Union[str, Path], file_contents: str + ) -> Type[AbstractParser]: if file_type == "ini": - return IniParser(self.__contents) + return IniParser(file_contents) elif file_type == "json": - return JsonParser(self.__contents) + return JsonParser(file_contents) + elif file_type == "yaml" or file_type == "yml": + return YamlParser(file_contents) + elif file_type == "toml": + return TomlParser(file_contents) else: - raise ValueError( - f"File path contains an unrecognized file type: {file_path}" + raise UnrecognizedFileError( + f"File path at `{file_path}` contains an unrecognized file type." ) def get( @@ -57,8 +81,7 @@ class ConfigFile: key: str, parse_types: bool = False, return_type: Any = None, - default: Any = None, - all: bool = False, + default: Any = Default(None), ) -> Any: """ Retrieve the value of a key. @@ -76,54 +99,83 @@ class ConfigFile: :raises ValueError: If the value is not able to be coerced into return_type """ - if default is None: - key_value = self.__parser.get(key, parse_types=parse_types) - else: - try: - key_value = self.__parser.get(key, parse_types=parse_types) - except ParsingError: - return default + try: + key_value = self.__parser.get(key) + except ParsingError as error: + if default is not type(Default): + key_value = default + else: + raise ParsingError(error) + + if parse_types: + key_value = parse_value(key_value) return return_type(key_value) if return_type else key_value - def set(self, key: str, value: Any) -> bool: - """Sets the value of a key.""" - return self.__parser.set(key, value) + def set(self, key: str, value: Any) -> None: + """Sets the value of a key. - def delete(self, section_key: str) -> bool: - """Deletes a key/value pair or entire sections.""" - return self.__parser.delete(section_key) + """ + self.__parser.set(key, value) + + def delete(self, section_key: str) -> None: + """Deletes a section or key. + + Args: + section_key: + """ + self.__parser.delete(section_key) def stringify(self) -> str: - """Convert the parsed internal representation of the file back into a string.""" + """Retrieves file contents as a string. + + Returns: + The internal representation of the file + that has been read in converted to a string. + """ return self.__parser.stringify() def has(self, section_key: str) -> bool: """ - Check if a section, sub-section, or key exists in the file - using a section.key format. + Check if a section, sub-section, or key exists. + + Some formats, like JSON, do not have sections and + therefore, it would only be checking if a particular + key exists. - Some formats, like JSON, do not have sections and therefore, - it would only be checking if the key exists. + Args: + section_key: + + Returns: + True if """ return self.__parser.has(section_key) def restore_original( - self, original_file_path: Union[str, Type[PurePath]] = None - ) -> bool: - """ - Restores the original the config file by deleting it and copying the original - back in its place. The internal contents of this config file object are then set - to the newly reset config file. - - :param original_file_path: The path to the original config file to reset it to. - If this is not provided and, say, your configuration file is config.json, the - method would look for a config.original.json in the same folder by default. - - :return: True if the reset succeeded - :raises FileNotFoundError: If the original configuration file does not exist - :raises OSError: If self.path is not writable - :raises SameFileError: If self.path and original_file_path are the same file. + self, original_file_path: Union[str, Path, None] = None + ) -> None: + """Restores the original the configuration file. + + The current one is deleted and the original is copied back + in its place. The internal contents are then reset to the + new file. + + Args: + original_file_path: The original file to reset to. + + If this is not provided, it is calculated for you. + e.g. if your configuration file is named config.json, + this will look for aa config.original.json in the same + directory. + + Raises: + FileNotFoundError: If the original configuration file (whether + calculated or passed in) does not exist. + + OSError: If the current configuration path is not writable. + + SameFileError: If current configuration path and the passed in + original_file_path are the same file. """ if original_file_path is None: original_file_path = create_config_path(self.__path, original=True) @@ -135,17 +187,17 @@ class ConfigFile: self.__path.expanduser().unlink() copyfile(original_file_path, self.__path) - self.__contents = read_file(self.__path) - self.__parser.parsed_content = self.__parser.parse(self.__contents) - return True + self.__contents = read_file(self.__path) + self.__parser.reset_internal_contents(self.__contents) - def save(self) -> bool: + def save(self) -> None: """ - Save the configuration changes by writing the file out to the specified path - :return: True if the save succeeded. + Save your configuration changes. + + This writes the file back out, including any changes + you've made, to the specified path when this object + was created. """ - with open(self.__path, "w") as config_file: + with open(str(self.__path), "w") as config_file: config_file.write(self.__parser.stringify()) - - return True -- cgit v1.2.3 From 5d78f7e5e8f24476ec21cf2b01c88a62e3acc9ba Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Wed, 29 Jul 2020 21:31:35 -0500 Subject: Revise docstrings, add `wild` to `has` method --- config_file/config_file.py | 96 ++++++++++++++++++++++++++++++---------------- 1 file changed, 63 insertions(+), 33 deletions(-) (limited to 'config_file/config_file.py') diff --git a/config_file/config_file.py b/config_file/config_file.py index 3ac4b91..9b14072 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -17,25 +17,26 @@ class ConfigFile: def __init__( self, file_path: Union[str, Path], - parser: Optional[Type[AbstractParser]] = None, + parser: Optional[Type[AbstractParser]] = None ) -> None: """ - Saves the config file path and expands it if needed, reads in + Stores the config file path and expands it if needed, reads in the file contents, and determines what parser should be used for the given file. - :param file_path: The path to your configuration file. - :param parser: A custom parser you'd like used for your config file. + Args: + file_path: The path to your configuration file. + parser: A custom parser you'd like used for your config file. - :raises ValueError: If the specified file path does not have an extension - that is supported or it is a directory. + Raises: + ValueError: If the specified file path does not have an extension + that is supported or it is a directory. """ if not isinstance(file_path, Path): file_path = Path(file_path) self.__path = create_config_path(file_path) - self.__contents = read_file(self.__path) - self.__parser = self.__determine_parser(file_path, parser) + self.__parser = self.__determine_parser(self.__path, parser) @property def path(self) -> Path: @@ -44,8 +45,10 @@ class ConfigFile: def __determine_parser( self, file_path: Path, parser: Optional[Type[AbstractParser]] = None ) -> Type[AbstractParser]: + file_contents = read_file(file_path) + if parser is not None and not inspect.isabstract(parser): - return parser(self.__contents) + return parser(file_contents) try: file_type = split_on_dot(file_path, only_last_dot=True)[-1] @@ -56,7 +59,7 @@ class ConfigFile: ) return self.__find_parser_by_file_type( - file_type=file_type, file_contents=self.__contents, file_path=self.__path + file_type=file_type, file_contents=file_contents, file_path=file_path ) @staticmethod @@ -86,18 +89,23 @@ class ConfigFile: """ Retrieve the value of a key. - :param key: The key to retrieve. - :param parse_types: Automatically parse ints, floats, booleans, dicts, and - lists. This recursively parses all types in whatever you're - retrieving, not just a single type. e.g. If you are - retrieving a section, all values in that section with be - parsed. - :param return_type: The type to coerce the return value to. - :param default: The default value to return if the value of the key is empty. + Args: + key: The key to retrieve. + parse_types: Automatically parse ints, floats, booleans, dicts, and + lists. This recursively parses all types in whatever you're + retrieving, not just a single type. + + e.g. If you are retrieving a section, all values in that section + will be parsed. - :return: The value of the key. + return_type: The type to coerce the return value to. + default: The default value to return if the value of the key is empty. - :raises ValueError: If the value is not able to be coerced into return_type + Returns: + The value of the key. + + Raises: + ValueError: If the value is not able to be coerced into return_type. """ try: key_value = self.__parser.get(key) @@ -115,16 +123,33 @@ class ConfigFile: def set(self, key: str, value: Any) -> None: """Sets the value of a key. + If the given key does not exist, it will be automatically + created for you. That includes if there are multiple keys + in a row that do not exist. + e.g. set('exists.does_not.does_not.also_does_not', 5) + + The behavior of how this is done, however, depends on the + file used. For example, with INI, subsections are not supported. + So it would create a key in the section `exists` called `does_not` + and set it to the value {'does_not': {'also_does_not': 5}}. + + Args: + key: The section, sub-section, or key to delete. + value: The value to set the key to. """ self.__parser.set(key, value) - def delete(self, section_key: str) -> None: + def delete(self, key: str) -> None: """Deletes a section or key. Args: - section_key: + key: The section, sub-section, or key to delete. + + Raises: + MissingKeyError: If a key is attempted to be deleted that + does not exist. """ - self.__parser.delete(section_key) + self.__parser.delete(key) def stringify(self) -> str: """Retrieves file contents as a string. @@ -135,7 +160,7 @@ class ConfigFile: """ return self.__parser.stringify() - def has(self, section_key: str) -> bool: + def has(self, key: str, wild: bool = False) -> bool: """ Check if a section, sub-section, or key exists. @@ -144,12 +169,19 @@ class ConfigFile: key exists. Args: - section_key: + key: The section, sub-section, or key to find. + wild: Whether or not to search everywhere. + + Without `wild`, a single word `key` without a `.` + will look at the outer most heirarchy of the file for it. + + With `wild`, that single word `key` will be searched + for throughout the entire file. Returns: - True if + True if the key exists. False otherwise. """ - return self.__parser.has(section_key) + return self.__parser.has(key, wild=wild) def restore_original( self, original_file_path: Union[str, Path, None] = None @@ -187,17 +219,15 @@ class ConfigFile: self.__path.expanduser().unlink() copyfile(original_file_path, self.__path) - - self.__contents = read_file(self.__path) - self.__parser.reset_internal_contents(self.__contents) + self.__parser.reset_internal_contents(read_file(self.__path)) def save(self) -> None: """ Save your configuration changes. This writes the file back out, including any changes - you've made, to the specified path when this object - was created. + you've made, to the specified path given from this + object's constructor. """ with open(str(self.__path), "w") as config_file: - config_file.write(self.__parser.stringify()) + config_file.write(self.stringify()) -- 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/config_file.py | 32 +++++++++++++++----------------- 1 file changed, 15 insertions(+), 17 deletions(-) (limited to 'config_file/config_file.py') diff --git a/config_file/config_file.py b/config_file/config_file.py index 9b14072..adcfaf1 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -15,9 +15,7 @@ from config_file.utils import Default, create_config_path, read_file, split_on_d class ConfigFile: def __init__( - self, - file_path: Union[str, Path], - parser: Optional[Type[AbstractParser]] = None + self, file_path: Union[str, Path], parser: Optional[Type[AbstractParser]] = None ) -> None: """ Stores the config file path and expands it if needed, reads in @@ -93,10 +91,10 @@ class ConfigFile: key: The key to retrieve. parse_types: Automatically parse ints, floats, booleans, dicts, and lists. This recursively parses all types in whatever you're - retrieving, not just a single type. - - e.g. If you are retrieving a section, all values in that section - will be parsed. + retrieving, not just a single type. + + e.g. If you are retrieving a section, all values in that + section will be parsed. return_type: The type to coerce the return value to. default: The default value to return if the value of the key is empty. @@ -123,14 +121,14 @@ class ConfigFile: def set(self, key: str, value: Any) -> None: """Sets the value of a key. - If the given key does not exist, it will be automatically - created for you. That includes if there are multiple keys + If the given key does not exist, it will be automatically + created for you. That includes if there are multiple keys in a row that do not exist. e.g. set('exists.does_not.does_not.also_does_not', 5) - The behavior of how this is done, however, depends on the - file used. For example, with INI, subsections are not supported. - So it would create a key in the section `exists` called `does_not` + The behavior of how this is done, however, depends on the + file used. For example, with INI, subsections are not supported. + So it would create a key in the section `exists` called `does_not` and set it to the value {'does_not': {'also_does_not': 5}}. Args: @@ -144,7 +142,7 @@ class ConfigFile: Args: key: The section, sub-section, or key to delete. - + Raises: MissingKeyError: If a key is attempted to be deleted that does not exist. @@ -170,9 +168,9 @@ class ConfigFile: Args: key: The section, sub-section, or key to find. - wild: Whether or not to search everywhere. - - Without `wild`, a single word `key` without a `.` + wild: Whether or not to search everywhere. + + Without `wild`, a single word `key` without a `.` will look at the outer most heirarchy of the file for it. With `wild`, that single word `key` will be searched @@ -226,7 +224,7 @@ class ConfigFile: Save your configuration changes. This writes the file back out, including any changes - you've made, to the specified path given from this + you've made, to the specified path given from this object's constructor. """ with open(str(self.__path), "w") as config_file: -- cgit v1.2.3 From 032196104a59761bd75b5d594440d1e8ef16965a Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sat, 1 Aug 2020 17:58:32 -0500 Subject: Add ConfigFilePath to refactor out file specific code --- config_file/config_file.py | 74 +++++++++++++--------------------------------- 1 file changed, 20 insertions(+), 54 deletions(-) (limited to 'config_file/config_file.py') diff --git a/config_file/config_file.py b/config_file/config_file.py index adcfaf1..3e8a806 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -3,14 +3,11 @@ from pathlib import Path from shutil import copyfile from typing import Any, Optional, Type, Union -from config_file.exceptions import ParsingError, UnrecognizedFileError +from config_file.config_file_path import ConfigFilePath +from config_file.default import Default +from config_file.exceptions import ParsingError from config_file.parsers.abstract_parser import AbstractParser -from config_file.parsers.ini_parser import IniParser -from config_file.parsers.json_parser import JsonParser from config_file.parsers.parse_value import parse_value -from config_file.parsers.toml_parser import TomlParser -from config_file.parsers.yaml_parser import YamlParser -from config_file.utils import Default, create_config_path, read_file, split_on_dot class ConfigFile: @@ -29,53 +26,22 @@ class ConfigFile: Raises: ValueError: If the specified file path does not have an extension that is supported or it is a directory. + FileNotFoundError: If the specified file path does not exist. """ - if not isinstance(file_path, Path): - file_path = Path(file_path) - - self.__path = create_config_path(file_path) - self.__parser = self.__determine_parser(self.__path, parser) - - @property - def path(self) -> Path: - return self.__path - - def __determine_parser( - self, file_path: Path, parser: Optional[Type[AbstractParser]] = None - ) -> Type[AbstractParser]: - file_contents = read_file(file_path) + self.__path = ConfigFilePath(file_path).validate() if parser is not None and not inspect.isabstract(parser): - return parser(file_contents) + self.__parser = parser(self.__path.contents) + else: + self.__parser = self.__path.parser - try: - file_type = split_on_dot(file_path, only_last_dot=True)[-1] - except ValueError: - raise UnrecognizedFileError( - "Tried to determine a parser to use, but the file at " - f"{file_path} does not have an extension." - ) + @property + def file_path(self) -> Path: + return Path(self.__path) - return self.__find_parser_by_file_type( - file_type=file_type, file_contents=file_contents, file_path=file_path - ) - - @staticmethod - def __find_parser_by_file_type( - file_type: str, file_path: Union[str, Path], file_contents: str - ) -> Type[AbstractParser]: - if file_type == "ini": - return IniParser(file_contents) - elif file_type == "json": - return JsonParser(file_contents) - elif file_type == "yaml" or file_type == "yml": - return YamlParser(file_contents) - elif file_type == "toml": - return TomlParser(file_contents) - else: - raise UnrecognizedFileError( - f"File path at `{file_path}` contains an unrecognized file type." - ) + @property + def original_file_path(self) -> Path: + return Path(self.__path.original_path) def get( self, @@ -207,17 +173,17 @@ class ConfigFile: SameFileError: If current configuration path and the passed in original_file_path are the same file. """ - if original_file_path is None: - original_file_path = create_config_path(self.__path, original=True) - - if not Path(original_file_path).exists(): + if original_file_path and not ConfigFilePath(original_file_path).exists(): raise FileNotFoundError( f"The {original_file_path} file to restore to does not exist." ) + else: + original_file_path = self.__path.original_path + original_file_path = original_file_path.validate() - self.__path.expanduser().unlink() + self.__path.unlink() copyfile(original_file_path, self.__path) - self.__parser.reset_internal_contents(read_file(self.__path)) + self.__parser.reset_internal_contents(self.__path.contents) def save(self) -> None: """ -- 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/config_file.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'config_file/config_file.py') diff --git a/config_file/config_file.py b/config_file/config_file.py index 3e8a806..d047560 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -3,11 +3,11 @@ from pathlib import Path from shutil import copyfile from typing import Any, Optional, Type, Union +from config_file.abstract_parser import AbstractParser from config_file.config_file_path import ConfigFilePath -from config_file.default import Default 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.parse_value import parse_value +from config_file.utils import Default class ConfigFile: -- cgit v1.2.3 From d9a2ade40e72176449433782957bf503d69cc1d8 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Wed, 5 Aug 2020 20:59:42 -0500 Subject: Remove custom parser and add ability to index ConfigFile --- config_file/config_file.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) (limited to 'config_file/config_file.py') diff --git a/config_file/config_file.py b/config_file/config_file.py index d047560..0e67794 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -1,9 +1,7 @@ -import inspect from pathlib import Path from shutil import copyfile -from typing import Any, Optional, Type, Union +from typing import Any, Union -from config_file.abstract_parser import AbstractParser from config_file.config_file_path import ConfigFilePath from config_file.exceptions import ParsingError from config_file.parse_value import parse_value @@ -11,9 +9,7 @@ from config_file.utils import Default class ConfigFile: - def __init__( - self, file_path: Union[str, Path], parser: Optional[Type[AbstractParser]] = None - ) -> None: + def __init__(self, file_path: Union[str, Path]) -> None: """ Stores the config file path and expands it if needed, reads in the file contents, and determines what parser should be used for @@ -21,7 +17,6 @@ class ConfigFile: Args: file_path: The path to your configuration file. - parser: A custom parser you'd like used for your config file. Raises: ValueError: If the specified file path does not have an extension @@ -29,11 +24,7 @@ class ConfigFile: FileNotFoundError: If the specified file path does not exist. """ self.__path = ConfigFilePath(file_path).validate() - - if parser is not None and not inspect.isabstract(parser): - self.__parser = parser(self.__path.contents) - else: - self.__parser = self.__path.parser + self.__parser = self.__path.parser @property def file_path(self) -> Path: @@ -43,6 +34,15 @@ class ConfigFile: def original_file_path(self) -> Path: return Path(self.__path.original_path) + def __getitem__(self, key: str): + return self.__parser.parsed_content[key] + + def __setitem__(self, key: str, value: Any): + self.__parser.parsed_content[key] = value + + def __delitem__(self, key: str): + del self.__parser.parsed_content[key] + def get( self, key: str, -- cgit v1.2.3 From 1fdde7b696674546220b85bb3ffd2994e93fec3a Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Wed, 5 Aug 2020 21:27:26 -0500 Subject: Add `wild` to AbstractParser --- config_file/config_file.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'config_file/config_file.py') diff --git a/config_file/config_file.py b/config_file/config_file.py index 0e67794..d66cc48 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -137,7 +137,7 @@ class ConfigFile: wild: Whether or not to search everywhere. Without `wild`, a single word `key` without a `.` - will look at the outer most heirarchy of the file for it. + will look at the outer most hierarchy of the file for it. With `wild`, that single word `key` will be searched for throughout the entire file. -- cgit v1.2.3 From 08d7c88cae495ac8904be2367eb0d223e16ac8e8 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Fri, 7 Aug 2020 09:52:11 -0500 Subject: Fix invalid reference to MissingKeyError --- config_file/config_file.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'config_file/config_file.py') diff --git a/config_file/config_file.py b/config_file/config_file.py index d66cc48..2ce61ef 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -69,6 +69,7 @@ class ConfigFile: The value of the key. Raises: + KeyError: If a key is attempted to be retrieved that does not exist. ValueError: If the value is not able to be coerced into return_type. """ try: @@ -110,7 +111,7 @@ class ConfigFile: key: The section, sub-section, or key to delete. Raises: - MissingKeyError: If a key is attempted to be deleted that + KeyError: If a key is attempted to be deleted that does not exist. """ self.__parser.delete(key) -- cgit v1.2.3 From e529b2be912925e91be6466dfd926610012ba58c Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Fri, 7 Aug 2020 19:40:38 -0500 Subject: Change file_path to path and original_file_path to original_path --- config_file/config_file.py | 35 +++++++++++++---------------------- 1 file changed, 13 insertions(+), 22 deletions(-) (limited to 'config_file/config_file.py') diff --git a/config_file/config_file.py b/config_file/config_file.py index 2ce61ef..8cde5cb 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -27,11 +27,11 @@ class ConfigFile: self.__parser = self.__path.parser @property - def file_path(self) -> Path: + def path(self) -> Path: return Path(self.__path) @property - def original_file_path(self) -> Path: + def original_path(self) -> Path: return Path(self.__path.original_path) def __getitem__(self, key: str): @@ -148,9 +148,7 @@ class ConfigFile: """ return self.__parser.has(key, wild=wild) - def restore_original( - self, original_file_path: Union[str, Path, None] = None - ) -> None: + def restore_original(self, original_path: Union[str, Path, None] = None) -> None: """Restores the original the configuration file. The current one is deleted and the original is copied back @@ -158,32 +156,25 @@ class ConfigFile: new file. Args: - original_file_path: The original file to reset to. + original_path: The original file to reset to. - If this is not provided, it is calculated for you. - e.g. if your configuration file is named config.json, - this will look for aa config.original.json in the same - directory. + Defaults to the original_path property if it is not + provided. Raises: FileNotFoundError: If the original configuration file (whether - calculated or passed in) does not exist. + calculated or passed in) does not exist or if the current + configuration path is passed in as the original_path (since + it is deleted before the original file is copied over). OSError: If the current configuration path is not writable. - - SameFileError: If current configuration path and the passed in - original_file_path are the same file. """ - if original_file_path and not ConfigFilePath(original_file_path).exists(): - raise FileNotFoundError( - f"The {original_file_path} file to restore to does not exist." - ) - else: - original_file_path = self.__path.original_path - original_file_path = original_file_path.validate() + original_path = ConfigFilePath( + original_path if original_path else self.original_path + ).validate() self.__path.unlink() - copyfile(original_file_path, self.__path) + copyfile(original_path, self.__path) self.__parser.reset_internal_contents(self.__path.contents) def save(self) -> None: -- cgit v1.2.3 From a0cdb32e3f8ae69bd1163e2d44e3d731d9e8594e Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Fri, 7 Aug 2020 20:15:05 -0500 Subject: Fix ConfigFile default --- config_file/config_file.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'config_file/config_file.py') diff --git a/config_file/config_file.py b/config_file/config_file.py index 8cde5cb..2a8d9ae 100644 --- a/config_file/config_file.py +++ b/config_file/config_file.py @@ -3,7 +3,6 @@ from shutil import copyfile from typing import Any, Union from config_file.config_file_path import ConfigFilePath -from config_file.exceptions import ParsingError from config_file.parse_value import parse_value from config_file.utils import Default @@ -74,11 +73,11 @@ class ConfigFile: """ try: key_value = self.__parser.get(key) - except ParsingError as error: - if default is not type(Default): - key_value = default + except KeyError as error: + if isinstance(default, Default) and default.value is None: + raise KeyError(error) else: - raise ParsingError(error) + key_value = default if parse_types: key_value = parse_value(key_value) -- cgit v1.2.3