2022-02-17 22:54:30 +00:00
|
|
|
from configparser import DEFAULTSECT as default_section
|
2022-10-14 14:53:06 +00:00
|
|
|
from configparser import ConfigParser
|
2022-02-17 22:54:30 +00:00
|
|
|
from io import StringIO
|
2021-05-04 21:22:11 +00:00
|
|
|
|
2022-10-14 14:53:06 +00:00
|
|
|
from benedict.serializers.abstract import AbstractSerializer
|
|
|
|
from benedict.utils import type_util
|
|
|
|
|
2021-05-04 21:22:11 +00:00
|
|
|
|
|
|
|
class INISerializer(AbstractSerializer):
|
2022-02-13 10:56:44 +00:00
|
|
|
"""
|
|
|
|
This class describes an ini serializer.
|
|
|
|
"""
|
|
|
|
|
2021-05-04 21:22:11 +00:00
|
|
|
def __init__(self):
|
2022-12-31 17:33:20 +00:00
|
|
|
super().__init__(
|
2022-10-05 14:43:46 +00:00
|
|
|
extensions=[
|
|
|
|
"ini",
|
|
|
|
],
|
|
|
|
)
|
2021-05-04 21:22:11 +00:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _get_section_option_value(parser, section, option):
|
|
|
|
value = None
|
2021-10-12 12:27:35 +00:00
|
|
|
funcs = [parser.getint, parser.getfloat, parser.getboolean, parser.get]
|
2021-05-04 21:22:11 +00:00
|
|
|
for func in funcs:
|
|
|
|
try:
|
|
|
|
value = func(section, option)
|
|
|
|
break
|
|
|
|
except ValueError:
|
|
|
|
continue
|
|
|
|
return value
|
|
|
|
|
|
|
|
def decode(self, s, **kwargs):
|
|
|
|
parser = ConfigParser(**kwargs)
|
2022-02-17 22:54:30 +00:00
|
|
|
parser.read_string(s)
|
2021-05-04 21:22:11 +00:00
|
|
|
data = {}
|
|
|
|
for option, _ in parser.defaults().items():
|
|
|
|
data[option] = self._get_section_option_value(
|
2021-10-12 12:27:35 +00:00
|
|
|
parser, default_section, option
|
|
|
|
)
|
2021-05-04 21:22:11 +00:00
|
|
|
for section in parser.sections():
|
|
|
|
data[section] = {}
|
|
|
|
for option, _ in parser.items(section):
|
|
|
|
data[section][option] = self._get_section_option_value(
|
2021-10-12 12:27:35 +00:00
|
|
|
parser, section, option
|
|
|
|
)
|
2021-05-04 21:22:11 +00:00
|
|
|
return data
|
|
|
|
|
|
|
|
def encode(self, d, **kwargs):
|
|
|
|
parser = ConfigParser(**kwargs)
|
|
|
|
for key, value in d.items():
|
|
|
|
if not type_util.is_dict(value):
|
2022-02-18 00:02:02 +00:00
|
|
|
parser.set(default_section, key, f"{value}")
|
2021-05-04 21:22:11 +00:00
|
|
|
continue
|
|
|
|
section = key
|
|
|
|
parser.add_section(section)
|
|
|
|
for option_key, option_value in value.items():
|
2022-02-18 00:02:02 +00:00
|
|
|
parser.set(section, option_key, f"{option_value}")
|
2021-05-04 21:22:11 +00:00
|
|
|
str_data = StringIO()
|
|
|
|
parser.write(str_data)
|
|
|
|
return str_data.getvalue()
|