diff options
| author | Eugene Triguba <eugenetriguba@gmail.com> | 2020-08-16 21:35:56 -0500 |
|---|---|---|
| committer | Eugene Triguba <eugenetriguba@gmail.com> | 2020-08-16 21:35:56 -0500 |
| commit | 2d091dcc5b1250b2c9457f0ff34c0c997a6a0867 (patch) | |
| tree | 7d0bbde5193b4a298f3510cfda9cd48d6bca597a /config_file/ini_parser.py | |
| parent | Remove sphinx dev dependencies (diff) | |
| download | config-file-2d091dcc5b1250b2c9457f0ff34c0c997a6a0867.zip | |
Refactor parsers to enforce loads/dumps/decode_error requirement
Diffstat (limited to 'config_file/ini_parser.py')
| -rw-r--r-- | config_file/ini_parser.py | 37 |
1 files changed, 31 insertions, 6 deletions
diff --git a/config_file/ini_parser.py b/config_file/ini_parser.py index 72974f1..d6905a9 100644 --- a/config_file/ini_parser.py +++ b/config_file/ini_parser.py @@ -1,13 +1,38 @@ import configparser +from io import StringIO +from typing import Type from .base_parser import BaseParser -from .ini_parser_compat import IniParserCompatibility class IniParser(BaseParser): def __init__(self, file_contents: str): - super().__init__( - file_contents=file_contents, - module=IniParserCompatibility, - decode_error=configparser.Error, - ) + 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 |