diff options
| author | Eugene Triguba <eugenetriguba@gmail.com> | 2020-08-01 17:58:32 -0500 |
|---|---|---|
| committer | Eugene Triguba <eugenetriguba@gmail.com> | 2020-08-01 17:58:32 -0500 |
| commit | 032196104a59761bd75b5d594440d1e8ef16965a (patch) | |
| tree | efd67c11ac11ba7a64dc09e53b1f329916384d06 | |
| parent | Raise FileNotFoundError if the config file does not exist (diff) | |
| download | config-file-032196104a59761bd75b5d594440d1e8ef16965a.zip | |
Add ConfigFilePath to refactor out file specific code
| -rw-r--r-- | config_file/config_file.py | 74 | ||||
| -rw-r--r-- | config_file/config_file_path.py | 117 | ||||
| -rw-r--r-- | config_file/default.py | 14 | ||||
| -rw-r--r-- | config_file/utils.py | 33 | ||||
| -rw-r--r-- | tests/conftest.py | 11 | ||||
| -rw-r--r-- | tests/test_config_file.py | 9 | ||||
| -rw-r--r-- | tests/test_config_file_path.py | 0 |
7 files changed, 159 insertions, 99 deletions
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: """ diff --git a/config_file/config_file_path.py b/config_file/config_file_path.py new file mode 100644 index 0000000..a40cc40 --- /dev/null +++ b/config_file/config_file_path.py @@ -0,0 +1,117 @@ +import os +from pathlib import Path as _Path_ +from pathlib import _posix_flavour, _windows_flavour +from typing import Type + +from .exceptions import UnrecognizedFileError +from .parsers.abstract_parser import AbstractParser +from .parsers.ini_parser import IniParser +from .parsers.json_parser import JsonParser +from .parsers.toml_parser import TomlParser +from .parsers.yaml_parser import YamlParser +from .utils import split_on_dot + + +class ConfigFilePath(_Path_): + """A ConfigFilePath object, which subclasses Path. + + It provides us easy ways to grab the original config file + path, file extension, validate the path, or determine the parser + that should be use for the given file type. + + See https://codereview.stackexchange.com/questions/162426/subclassing-pathlib-path + for most details on subclassing the pathlib.Path object. + """ + + _flavour = _windows_flavour if os.name == "nt" else _posix_flavour + + @property + def original_path(self) -> "ConfigFilePath": + """Computes the original configuration file path. + + e.g. ConfigFilePath("./config.ini").original_path -> "./config.original.ini" + + Returns: + The path to the original configuration file, which + may or may not exist. + """ + file_parts = split_on_dot(self, only_last_dot=True) + file_parts.insert(-1, "original") + return ConfigFilePath(".".join(file_parts)) + + @property + def extension(self) -> str: + """Retrieves the extension of the file + path we passed in, without the '.'. + + e.g. ConfigFilePath("./pyproject.toml").extension -> "toml" + + Returns: + The extension of the current file path. + """ + _, extension = os.path.splitext(str(self)) + return extension[1:] + + @property + def parser(self) -> Type[AbstractParser]: + """Determine what parser should be used for this file. + + Raises: + UnrecognizedFileError: If the extension of the file + is not recognized. + + Returns: + The instantiated parser that should be used for this file. + """ + if self.extension == "": + raise UnrecognizedFileError( + "Tried to determine a parser to use, but the file at " + f"{self} does not have an extension." + ) + + if self.extension == "ini": + return IniParser(self.contents) + elif self.extension == "json": + return JsonParser(self.contents) + elif self.extension == "yaml" or self.extension == "yml": + return YamlParser(self.contents) + elif self.extension == "toml": + return TomlParser(self.contents) + else: + raise UnrecognizedFileError( + f"File path at `{self}` contains an unrecognized file type." + ) + + @property + def contents(self) -> str: + """Retrieve the contents of the file. + + Returns: + The contents of the file at this path. + """ + with open(self, "r") as file: + return file.read() + + def validate(self) -> "ConfigFilePath": + """Validates that the current path exists, is a directory, + and expands any home tidles. + + Raises: + FileNotFoundError: If the path does not exist. + ValueError: If the path leads to a directory. + + Returns: + This ConfigFilePath object + """ + if len(self.parts) >= 1 and self.parts[0] == "~": + self = ConfigFilePath(self.expanduser()) + + if not self.exists(): + raise FileNotFoundError( + f"The specified config file ({self}) does not exist." + ) + + if self.is_dir(): + raise ValueError(f"The specified config file ({self}) is a directory") + + return self diff --git a/config_file/default.py b/config_file/default.py new file mode 100644 index 0000000..529021c --- /dev/null +++ b/config_file/default.py @@ -0,0 +1,14 @@ +class Default: + """ + Default is used for the `default` value in ConfigFile's `get`. + + Previously, the default value for `get` was None. However, then + the user cannot have `get` return a default value of None. So this + class is used instead to get around that limitation. + """ + + def __init__(self, value): + self.value = value + + def __repr__(self): + return "Default Value: {} ({})".format(self.value, type(self.value)) diff --git a/config_file/utils.py b/config_file/utils.py index 4d8bb36..c6c3d24 100644 --- a/config_file/utils.py +++ b/config_file/utils.py @@ -20,36 +20,3 @@ def split_on_dot(line: Union[str, Path], only_last_dot=False) -> List[str]: raise ValueError(f"The given string does not have a dot to split on: {line}") return line.rsplit(".", 1) if only_last_dot else line.split(".") - - -def read_file(path: Union[str, Path]) -> str: - with open(path, "r") as file: - return file.read() - - -def create_config_path(file_path: Path, original: bool = False) -> Path: - 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 = Path(".".join(file_parts)) - - if file_path.is_dir(): - raise ValueError(f"The specified config file ({file_path}) is a directory.") - - if not file_path.exists(): - raise FileNotFoundError( - f"The specified config file ({file_path}) does not exist." - ) - - return file_path - - -class Default: - def __init__(self, value): - self.value = value - - def __repr__(self): - return "Default Value: {} ({})".format(self.value, type(self.value)) diff --git a/tests/conftest.py b/tests/conftest.py index 70e88c7..faf1630 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -4,7 +4,7 @@ from typing import Callable, Tuple, Type, Union import pytest from config_file import AbstractParser, ConfigFile -from config_file.utils import create_config_path +from config_file.config_file_path import ConfigFilePath @pytest.fixture @@ -37,7 +37,7 @@ def template_original_file() -> Callable[[Path], Path]: if isinstance(template_path, str): template_path = Path(template_path) - original_path = create_config_path(template_path, original=True) + original_path = ConfigFilePath(template_path).original_path original_path.touch() original_path.write_text(template_path.read_text(encoding="utf-8")) @@ -54,12 +54,7 @@ def template_and_parser( file_type: str, template_name: str = "default" ) -> Tuple[Path, Type[AbstractParser]]: test_file = template_file(file_type, template_name) - text = test_file.read_text(encoding="utf-8") - - parser = ConfigFile._ConfigFile__find_parser_by_file_type( - file_contents=text, file_type=file_type, file_path=test_file - ) - return test_file, parser + return test_file, ConfigFile(test_file)._ConfigFile__parser return func diff --git a/tests/test_config_file.py b/tests/test_config_file.py index d655397..548951b 100644 --- a/tests/test_config_file.py +++ b/tests/test_config_file.py @@ -30,7 +30,7 @@ def templated_config_file(template_and_config_file): def test_that_config_file_is_initialized_correctly(template_and_config_file): template_file, config = template_and_config_file() - assert config.path == template_file + assert config.file_path == template_file assert config.stringify() == template_file.read_text() assert isinstance(config._ConfigFile__parser, AbstractParser) @@ -41,7 +41,7 @@ def test_that_a_tidle_in_the_config_path_expands_to_the_absolute_path(): try: Path(config_path).expanduser().touch() - assert ConfigFile(config_path).path == Path.home() / config_name + assert ConfigFile(config_path).file_path == Path.home() / config_name finally: Path(config_path).expanduser().unlink() @@ -66,7 +66,7 @@ def test_that_config_file_can_restore_the_original( templated_config_file, template_original_file ): config = templated_config_file() - original_file = template_original_file(config.path) + original_file = template_original_file(config.file_path) config.set("header_one.number_key", 5) config.restore_original() @@ -80,7 +80,8 @@ def test_missing_config_file_during_restore(templated_config_file): with pytest.raises(FileNotFoundError) as error: config.restore_original() - assert "file to restore to does not exist" in str(error) + assert "The specified config file" in str(error) + assert "does not exist" in str(error) @pytest.mark.parametrize( diff --git a/tests/test_config_file_path.py b/tests/test_config_file_path.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/tests/test_config_file_path.py |