aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorEugene Triguba <eugenetriguba@gmail.com>2020-06-20 15:13:53 -0500
committerEugene Triguba <eugenetriguba@gmail.com>2020-06-20 15:56:19 -0500
commit95c47a183409fabed81f078a70967f053679737e (patch)
tree1d3376c3cb1e3dfebf8feb465ae52f24ab0ca6e4
parentRemove taskipy from tox & add default to parser in __determine_parser (diff)
downloadconfig-file-95c47a183409fabed81f078a70967f053679737e.zip
Change path, parser, and contents to be properties
Also, restore_original now raises a FileNotFoundError.
-rw-r--r--.pre-commit-config.yaml42
-rw-r--r--CHANGELOG.md3
-rw-r--r--config_file/config_file.py94
-rw-r--r--config_file/utils.py22
-rw-r--r--tests/test_config_file.py45
5 files changed, 108 insertions, 98 deletions
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 9975877..879742c 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -1,30 +1,42 @@
repos:
+ - repo: git@github.com:humitos/mirrors-autoflake.git
+ rev: v1.3
+ hooks:
+ - id: autoflake
+ args:
+ [
+ "--in-place",
+ "--remove-all-unused-imports",
+ "--remove-unused-variable",
+ ]
-- repo: git@github.com:humitos/mirrors-autoflake.git
- rev: v1.3
- hooks:
- - id: autoflake
- args: ['--in-place', '--remove-all-unused-imports', '--remove-unused-variable']
-
-- repo: https://github.com/asottile/seed-isort-config
+ - repo: https://github.com/asottile/seed-isort-config
rev: v1.9.4
hooks:
- - id: seed-isort-config
+ - id: seed-isort-config
-- repo: https://github.com/pre-commit/mirrors-isort
+ - repo: https://github.com/pre-commit/mirrors-isort
rev: v4.3.21
hooks:
- - id: isort
+ - id: isort
additional_dependencies:
- toml
-- repo: https://github.com/ambv/black
+ - repo: https://github.com/ambv/black
rev: stable
hooks:
- - id: black
- language_version: python3.8
+ - id: black
+
+ - repo: https://github.com/pre-commit/pre-commit-hooks
+ rev: v2.5.0
+ hooks:
+ - id: trailing-whitespace
+ - id: check-docstring-first
+ - id: check-case-conflict
+ - id: check-yaml
+ - id: check-toml
-- repo: https://github.com/pre-commit/pre-commit-hooks
+ - repo: https://github.com/pre-commit/pre-commit-hooks
rev: v1.2.3
hooks:
- - id: flake8
+ - id: flake8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e6ac91f..2c9e591 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,9 @@ Changed
- The `get_all`, `set_all`, and `delete_all` optional parameter options in `JsonParser` have
been renamed to just `all`. This shouldn't have any effect since `JsonParser` is not intended
to be used directly, and that option is not in `ConfigFile`.
+- `path`, `parser`, and `contents` on the `ConfigFile` are now all properties and can only be retrieved.
+- `restore_original` in `ConfigFile` now raises a `FileNotFoundError` instead of an `OSError` if the original
+ file path does not exist.
## 0.10.0 - 2020-05-10
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
diff --git a/config_file/utils.py b/config_file/utils.py
index 61f0ae0..05c3a7a 100644
--- a/config_file/utils.py
+++ b/config_file/utils.py
@@ -1,4 +1,8 @@
-def split_on_dot(line: str, only_last_dot=False):
+from pathlib import Path
+from typing import Union
+
+
+def split_on_dot(line: Union[str, Path], only_last_dot=False):
"""
Split a string on the dot character (.).
@@ -7,15 +11,17 @@ def split_on_dot(line: str, only_last_dot=False):
:raises ValueError: if the line does not have a dot.
"""
+ if isinstance(line, Path):
+ line = str(line)
+
if "." not in line:
- # TODO: This is used in the parser for section.keys where a more specific
- # error message would be nice, but it is only used more generically to, say,
- # split a file path. We may just have to insert some try-catches to catch the
- # ValueError and insert a more specific error message or create a custom error
- # for this method?
raise ValueError(
- "section_key must contain the section and key separated by a dot. "
- + "e.g. 'section.key'"
+ "The given string does not have a dot to split on: {}".format(line)
)
return line.rsplit(".", 1) if only_last_dot else line.split(".")
+
+
+def read_file(path: Union[str, Path]):
+ with open(path, "r") as file:
+ return file.read()
diff --git a/tests/test_config_file.py b/tests/test_config_file.py
index fe8539f..38cdf38 100644
--- a/tests/test_config_file.py
+++ b/tests/test_config_file.py
@@ -3,7 +3,7 @@ from pathlib import Path
import pytest
-from config_file import ConfigFile, BaseParser
+from config_file import BaseParser, ConfigFile
@pytest.mark.parametrize(
@@ -14,7 +14,7 @@ def test_that_config_file_initializes_correctly(tmp_path, file_contents, file_na
temp.write_text(file_contents)
config = ConfigFile(temp)
- assert config.path == str(temp)
+ assert config.path == temp
assert config.contents == temp.read_text()
assert isinstance(config.parser, BaseParser)
@@ -26,39 +26,27 @@ def test_that_config_file_initializes_correctly(tmp_path, file_contents, file_na
def test_that_config_file_can_restore_the_original(
tmpdir, file_contents, file_name, original_file_name
):
- config_path = tmpdir / file_name
+ config_path = Path(tmpdir / file_name)
config_path.write_text(file_contents, encoding="utf-8")
-
- original_config_path = tmpdir / original_file_name
+ original_config_path = Path(tmpdir / original_file_name)
original_config_path.write_text(file_contents, encoding="utf-8")
- config = ConfigFile(str(config_path))
- config.set("calendar.sunday_index", 0)
+ config = ConfigFile(config_path)
+ config.set("calendar.sunday_index", 5)
config.restore_original()
- assert config.stringify() == ConfigFile(str(original_config_path)).stringify()
- assert config_path.read_text(encoding="utf-8") == original_config_path.read_text(
- encoding="utf-8"
- )
+ assert config.stringify() == ConfigFile(original_config_path).stringify()
-@pytest.mark.parametrize(
- "file_extension, specify_original_config_path", [("ini", False), ("ini", True)]
-)
-def test_missing_config_files_during_restore(
- tmpdir, file_extension, specify_original_config_path
-):
- with pytest.raises(OSError):
- temp_path = tmpdir / "config.{}".format(file_extension)
- temp_path.write("")
- config = ConfigFile(str(temp_path))
- if specify_original_config_path:
- specify_original_config_path = "does_not_exist.{}".format(file_extension)
- else:
- config.path = "does_not_exist.{}".format(file_extension)
- specify_original_config_path = None
+def test_missing_config_files_during_restore(tmpdir):
+ config_path = Path(tmpdir / "config.ini")
+ config_path.write_text("")
+ config = ConfigFile(config_path)
- config.restore_original(original_file_path=specify_original_config_path)
+ with pytest.raises(FileNotFoundError) as error:
+ config.restore_original(original_file_path="jhklasdfhjlkasjej")
+
+ assert "file to restore to does not exist" in str(error)
@pytest.mark.parametrize(
@@ -228,6 +216,7 @@ def test_that_custom_parser_can_be_used(tmpdir):
config_path = tmpdir / "config.conf"
config_path.write_text("", encoding="utf-8")
config = ConfigFile(str(config_path), parser=CustomParser)
+
assert isinstance(config.parser, CustomParser)
assert config.get("key") == "key"
assert config.set("key", "value") == ("key", "value")
@@ -242,6 +231,6 @@ 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 == str(Path.home() / config_name)
+ assert ConfigFile(config_path).path == Path.home() / config_name
finally:
Path(config_path).expanduser().unlink()