aboutsummaryrefslogtreecommitdiffstats
path: root/config_file
diff options
context:
space:
mode:
authorEugene Triguba <eugenetriguba@gmail.com>2020-01-17 20:31:42 -0600
committerEugene Triguba <eugenetriguba@gmail.com>2020-01-17 20:31:42 -0600
commit0174602093dcb097e23f6493bfd4f5d1a9fe2e3c (patch)
treeced5d54e2cb5e80008adc39cf0f9fdb2c53eadc8 /config_file
parentFix bug with isinstance use in config file (diff)
downloadconfig-file-0174602093dcb097e23f6493bfd4f5d1a9fe2e3c.zip
Remove _split_on_dot from base parser and add it to utils
Also, change the default behavior to split on every dot and split on only the last dot if specified
Diffstat (limited to 'config_file')
-rw-r--r--config_file/config_file.py6
-rw-r--r--config_file/parsers/base_parser.py21
-rw-r--r--config_file/parsers/ini_parser.py48
-rw-r--r--config_file/utils.py16
4 files changed, 46 insertions, 45 deletions
diff --git a/config_file/config_file.py b/config_file/config_file.py
index c47def2..5a2dbb5 100644
--- a/config_file/config_file.py
+++ b/config_file/config_file.py
@@ -1,7 +1,9 @@
+import inspect
from pathlib import Path
from config_file.parsers.base_parser import BaseParser
from config_file.parsers.ini_parser import IniParser
+from config_file.utils import split_on_dot
class ConfigFile:
@@ -21,10 +23,10 @@ class ConfigFile:
return Path(file_path)
def __determine_parser(self, file_path: str, parser):
- if isinstance(parser, BaseParser):
+ if isinstance(parser, BaseParser) and not inspect.isabstract(parser):
return parser(self.contents)
- file_type = self._split_on_dot(file_path, all_dots=True)[-1]
+ file_type = split_on_dot(file_path)[-1]
if file_type == "ini":
return IniParser(self.contents)
else:
diff --git a/config_file/parsers/base_parser.py b/config_file/parsers/base_parser.py
index 38e8859..22e286a 100644
--- a/config_file/parsers/base_parser.py
+++ b/config_file/parsers/base_parser.py
@@ -22,7 +22,7 @@ class BaseParser(ABC):
the parser and save the file when they are done using stringify().
"""
self.contents = file_contents
- self.parse(self.contents)
+ self.parsed_content = self.parse(self.contents)
@abstractmethod
def get(self, key, parse_type=True):
@@ -74,25 +74,6 @@ class BaseParser(ABC):
"""
raise NotImplementedError
- @staticmethod
- def _split_on_dot(line: str, all_dots=False):
- """
- Split a string on the first dot (.).
-
- :param line: The line ot split on.
- :param all_dots: If the line should be split on all the dots. Defaults to
- False and only splits on the first occurrence of one.
-
- :raises ValueError: if the line does not have a dot.
- """
- if "." not in line:
- raise ValueError(
- "section_key must contain the section and key separated by a dot. "
- + "e.g. 'section.key'"
- )
-
- return line.split(".") if all_dots else line.rsplit(".", 1)
-
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 9a69164..4e0922c 100644
--- a/config_file/parsers/ini_parser.py
+++ b/config_file/parsers/ini_parser.py
@@ -3,21 +3,22 @@ from io import StringIO
from config_file.parsers.base_parser import BaseParser, ParsingError
from config_file.parsers.parse_value import parse_value
+from config_file.utils import split_on_dot
class IniParser(BaseParser):
-
def __init__(self, file_contents: str):
- """Reads in the file contents into the parser."""
+ """Reads in the file contents into the configparser."""
+ super().__init__(file_contents)
+
+ def parse(self, file_contents: str):
try:
- self.parser = configparser.ConfigParser()
- super().__init__(file_contents)
+ parser = configparser.ConfigParser()
+ parser.read_string(file_contents)
+ return parser
except configparser.Error as error:
raise ParsingError(error)
- def parse(self, file_contents: str):
- self.parser.read_string(file_contents)
-
def get(self, section_key, parse_type=True):
"""
Read the value of `section.key` of the config file.
@@ -27,14 +28,15 @@ class IniParser(BaseParser):
:param parse_type: Coerces the return value to its native type.
:return: The value of the key, parsed to its native type if parse_type is True.
- :raises ValueError: if the section_key given is not in a dot format. e.g. 'section1.key'
+ :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.
"""
- section, key = self._split_on_dot(section_key)
+ section, key = split_on_dot(section_key, only_last_dot=True)
try:
- value = self.parser.get(section, key)
+ 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)
@@ -53,12 +55,12 @@ class IniParser(BaseParser):
:raises ValueError: If there is no dot (.) in section_key
"""
- section, key = self._split_on_dot(section_key)
+ section, key = split_on_dot(section_key, only_last_dot=True)
- if value is not None and not self.parser.has_section(section):
- self.parser.add_section(section)
+ if value is not None and not self.parsed_content.has_section(section):
+ self.parsed_content.add_section(section)
- self.parser.set(section, key, value)
+ self.parsed_content.set(section, key, value)
return True
def delete(self, section_key):
@@ -75,31 +77,31 @@ class IniParser(BaseParser):
:raise ValueError: If the section or key does not exist in the config file.
"""
if "." not in section_key:
- if not self.parser.has_section(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."
)
- self.parser.remove_section(section_key)
+ self.parsed_content.remove_section(section_key)
return True
- section, key = self._split_on_dot(section_key)
- if key not in self.parser[section]:
+ 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}."
)
- self.parser.remove_option(section, key)
+ self.parsed_content.remove_option(section, key)
return True
def stringify(self) -> str:
buffer = StringIO()
- self.parser.write(buffer)
+ self.parsed_content.write(buffer)
return buffer.getvalue()
def has(self, section_key: str) -> bool:
if "." not in section_key:
- return self.parser.has_section(section_key)
+ return self.parsed_content.has_section(section_key)
- section, key = self._split_on_dot(section_key)
- return self.parser.has_option(section, key)
+ section, key = split_on_dot(section_key, only_last_dot=True)
+ return self.parsed_content.has_option(section, key)
diff --git a/config_file/utils.py b/config_file/utils.py
new file mode 100644
index 0000000..41ce2a5
--- /dev/null
+++ b/config_file/utils.py
@@ -0,0 +1,16 @@
+def split_on_dot(line: str, only_last_dot=False):
+ """
+ Split a string on the dot character (.).
+
+ :param line: The line ot split on.
+ :param only_last_dot: Only split on the last occurrence of the dot.
+
+ :raises ValueError: if the line does not have a dot.
+ """
+ if "." not in line:
+ raise ValueError(
+ "section_key must contain the section and key separated by a dot. "
+ + "e.g. 'section.key'"
+ )
+
+ return line.rsplit(".", 1) if only_last_dot else line.split(".")