|
1
|
|
|
# -*- coding: utf-8 -*- |
|
2
|
|
|
|
|
3
|
|
|
from __future__ import absolute_import |
|
4
|
|
|
|
|
5
|
|
|
import io |
|
6
|
|
|
from typing import Dict |
|
7
|
|
|
|
|
8
|
|
|
from benedict.serializers.abstract import AbstractSerializer |
|
9
|
|
|
|
|
10
|
|
|
import configparser |
|
11
|
|
|
|
|
12
|
|
|
|
|
13
|
|
|
class INISerializer(AbstractSerializer): |
|
14
|
|
|
|
|
15
|
|
|
def __init__(self): |
|
16
|
|
|
super(INISerializer, self).__init__() |
|
17
|
|
|
|
|
18
|
|
|
def decode(self, s, **kwargs): |
|
19
|
|
|
parser = configparser.ConfigParser() |
|
20
|
|
|
kwargs.setdefault("source", "<string>") |
|
21
|
|
|
parser.read_string(s, **kwargs) |
|
22
|
|
|
data = {s: dict(parser.items(s)) for s in parser.sections()} |
|
23
|
|
|
return data |
|
24
|
|
|
|
|
25
|
|
|
def encode(self, d, **kwargs): |
|
26
|
|
|
parser = configparser.ConfigParser() |
|
27
|
|
|
parser.read_dict(self._preprocessed_dict(d, **kwargs)) |
|
28
|
|
|
with io.StringIO() as data: |
|
29
|
|
|
parser.write(data, **kwargs) |
|
30
|
|
|
data.seek(0) |
|
31
|
|
|
return data.getvalue() |
|
32
|
|
|
|
|
33
|
|
|
def _preprocessed_dict(self, d: Dict, default_namespace="default"): |
|
34
|
|
|
sections = { |
|
35
|
|
|
default_namespace: {} |
|
36
|
|
|
} |
|
37
|
|
|
for key, value in d.items(): |
|
38
|
|
|
if isinstance(value, dict): |
|
39
|
|
|
sections[key] = value |
|
40
|
|
|
else: |
|
41
|
|
|
sections[default_namespace][key] = value |
|
42
|
|
|
|
|
43
|
|
|
for section in sections.values(): |
|
44
|
|
|
for key, val in section.items(): |
|
45
|
|
|
if isinstance(val, object): |
|
46
|
|
|
section[key] = str(val) |
|
47
|
|
|
|
|
48
|
|
|
return sections |
|
49
|
|
|
|