aboutsummaryrefslogtreecommitdiffstats
path: root/config_file
diff options
context:
space:
mode:
authorEugene Triguba <eugenetriguba@gmail.com>2020-01-19 14:57:37 -0600
committerEugene Triguba <eugenetriguba@gmail.com>2020-01-19 14:57:37 -0600
commit7f32dc49460875aedec9e555d0e5d27f23a3f2df (patch)
treef70688edfcf512e3e29fdd7f706391a0f99fb018 /config_file
parentAdd start of json_parser implementaiton (diff)
parentAdd spacing (diff)
downloadconfig-file-7f32dc49460875aedec9e555d0e5d27f23a3f2df.zip
Merge branch 'master' of github.com:eugenetriguba/config_file into json
Diffstat (limited to 'config_file')
-rw-r--r--config_file/__init__.py2
-rw-r--r--config_file/config_file.py90
-rw-r--r--config_file/parsers/ini_parser.py15
-rw-r--r--config_file/utils.py5
4 files changed, 99 insertions, 13 deletions
diff --git a/config_file/__init__.py b/config_file/__init__.py
index c71562f..22164c1 100644
--- a/config_file/__init__.py
+++ b/config_file/__init__.py
@@ -1,7 +1,7 @@
from config_file.config_file import ConfigFile
from config_file.parsers.base_parser import BaseParser, ParsingError
-__version__ = "0.3.3"
+__version__ = "0.5.0"
__all__ = [
"ConfigFile",
diff --git a/config_file/config_file.py b/config_file/config_file.py
index 5a2dbb5..b090ace 100644
--- a/config_file/config_file.py
+++ b/config_file/config_file.py
@@ -1,5 +1,6 @@
import inspect
-from pathlib import Path
+from pathlib import Path, PurePath
+from shutil import copyfile
from config_file.parsers.base_parser import BaseParser
from config_file.parsers.ini_parser import IniParser
@@ -7,26 +8,49 @@ from config_file.utils import split_on_dot
class ConfigFile:
- def __init__(self, file_path: str, parser=None):
- self.path = self.__create_config_path(file_path)
+ def __init__(self, file_path, parser=None):
+ """
+ Saves 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.
- with open(self.path, "r") as file:
- self.contents = file.read()
+ :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.
+ """
+ self.path = self.__create_config_path(file_path)
+ self.contents = self.__read_config_file()
self.parser = self.__determine_parser(file_path, parser)
@staticmethod
- def __create_config_path(file_path: str):
+ def __create_config_path(file_path, original=False) -> str:
+ if isinstance(file_path, PurePath):
+ file_path = str(file_path)
+
if len(file_path) > 1 and file_path[0] == "~":
- return Path(file_path).expanduser().resolve()
+ return str(Path(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)
- return Path(file_path)
+ 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, parser):
+ if isinstance(file_path, PurePath):
+ file_path = str(file_path)
- def __determine_parser(self, file_path: str, parser):
if isinstance(parser, BaseParser) and not inspect.isabstract(parser):
return parser(self.contents)
- file_type = split_on_dot(file_path)[-1]
+ file_type = split_on_dot(file_path, only_last_dot=True)[-1]
if file_type == "ini":
return IniParser(self.contents)
else:
@@ -35,6 +59,10 @@ class ConfigFile:
f"unrecognized file type: {file_path}"
)
+ def __read_config_file(self):
+ with open(self.path, "r") as file:
+ return file.read()
+
def get(self, key, parse_type=True):
"""
Retrieve the value of a key in its native type.
@@ -64,6 +92,46 @@ class ConfigFile:
using a section.key format.
Some formats, like JSON, do not have sections and therefore,
- it would only be checking if the section
+ it would only be checking if the key exists.
"""
return self.parser.has(section_key)
+
+ def reset(self, original_file_path=None):
+ """
+ Resets the config file by deleting it and copying the original back
+ in its place. The contents of this config file 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 OSError: If the original configuration file is not present or if an
+ error occurred when trying to copy the file.
+ """
+ if original_file_path is None:
+ original_file_path = self.__create_config_path(
+ str(self.path), original=True
+ )
+
+ if not Path(original_file_path).exists():
+ raise OSError(f"The {original_file_path} file to reset to does not exist.")
+
+ Path(self.path).expanduser().unlink(missing_ok=True)
+ copyfile(original_file_path, self.path)
+
+ self.contents = self.__read_config_file()
+ self.parser.parsed_content = self.parser.parse(self.contents)
+
+ return True
+
+ def save(self):
+ """
+ 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())
+
+ return True
diff --git a/config_file/parsers/ini_parser.py b/config_file/parsers/ini_parser.py
index 3c8f12f..549ed37 100644
--- a/config_file/parsers/ini_parser.py
+++ b/config_file/parsers/ini_parser.py
@@ -33,14 +33,27 @@ class IniParser(BaseParser):
: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.
"""
- section, key = split_on_dot(section_key, only_last_dot=True)
+ if "." not in section_key:
+ return self.__retrieve_section(section_key, parse_type)
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_type else value
except configparser.Error as error:
raise ParsingError(error.message)
+ def __retrieve_section(self, section, parse_type):
+ items = dict(self.parsed_content.items(section))
+
+ if not parse_type:
+ return items
+
+ for item in items:
+ items[item] = parse_value(items[item])
+
+ return items
+
def set(self, section_key, value):
"""
Sets the value of 'section.key' of the config file. If the specified section
diff --git a/config_file/utils.py b/config_file/utils.py
index 41ce2a5..61f0ae0 100644
--- a/config_file/utils.py
+++ b/config_file/utils.py
@@ -8,6 +8,11 @@ def split_on_dot(line: str, only_last_dot=False):
:raises ValueError: if the line does not have a dot.
"""
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'"