diff options
| author | Eugene Triguba <eugenetriguba@gmail.com> | 2020-11-26 13:18:44 -0600 |
|---|---|---|
| committer | Eugene Triguba <eugenetriguba@gmail.com> | 2020-11-26 13:18:44 -0600 |
| commit | d6832cd600a28c1396c67229245347c1cf9440ca (patch) | |
| tree | e216eed48e9130be1bd63d4ad0ee3c8cad68d915 /config_file/parsers/ini_parser.py | |
| parent | Add python 3.9 to pyproject and update lockfile (diff) | |
| download | config-file-d6832cd600a28c1396c67229245347c1cf9440ca.zip | |
Move parsers to parsers directory
Diffstat (limited to 'config_file/parsers/ini_parser.py')
| -rw-r--r-- | config_file/parsers/ini_parser.py | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/config_file/parsers/ini_parser.py b/config_file/parsers/ini_parser.py new file mode 100644 index 0000000..fe78f05 --- /dev/null +++ b/config_file/parsers/ini_parser.py @@ -0,0 +1,44 @@ +import configparser +from io import StringIO +from typing import Any, Type + +from .base_parser import BaseParser + + +class IniParser(BaseParser): + def __init__(self, file_contents: str): + super().__init__(file_contents) + + @property + def decode_error(self) -> Type[Exception]: + return configparser.Error + + def loads(self, contents: str) -> dict: + parser = configparser.ConfigParser() + parser.read_string(contents) + + return self.__create_configparser_dict(parser) + + def dumps(self, loaded_contents: dict) -> str: + parser = configparser.ConfigParser() + buffer = StringIO() + + parser.read_dict(loaded_contents) + parser.write(buffer) + + return buffer.getvalue() + + def __create_configparser_dict(self, parser: configparser.ConfigParser) -> dict: + result = {} + items = dict(parser.items()) + + for section in parser.sections(): + result.update({str(section): dict(items[section])}) + + return result + + def get(self, search_key: str) -> Any: + retrieved_value = super().get(search_key) + return ( + retrieved_value if type(retrieved_value) is dict else str(retrieved_value) + ) |