ConfWriter.write_section()   F
last analyzed

Complexity

Conditions 11

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
dl 0
loc 27
rs 3.1764
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like ConfWriter.write_section() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
from itertools import chain
2
from types import MappingProxyType
3
4
from pyprint.ClosableObject import ClosableObject
5
6
from coala_utils.string_processing import escape
7
from coalib.settings.Section import Section
8
9
10
class ConfWriter(ClosableObject):
11
12
    def __init__(self,
13
                 file_name,
14
                 key_value_delimiters=('=',),
15
                 comment_separators=('#',),
16
                 key_delimiters=(',', ' '),
17
                 section_name_surroundings=MappingProxyType({"[": "]"}),
18
                 section_override_delimiters=(".",),
19
                 unsavable_keys=("save",)):
20
        ClosableObject.__init__(self)
21
        self.__file_name = file_name
22
        self.__file = open(self.__file_name, "w")
23
        self.__key_value_delimiters = key_value_delimiters
24
        self.__comment_separators = comment_separators
25
        self.__key_delimiters = key_delimiters
26
        self.__section_name_surroundings = section_name_surroundings
27
        self.__section_override_delimiters = section_override_delimiters
28
        self.__unsavable_keys = unsavable_keys
29
        self.__wrote_newline = True
30
        self.__closed = False
31
32
        self.__key_delimiter = self.__key_delimiters[0]
33
        self.__key_value_delimiter = self.__key_value_delimiters[0]
34
        (self.__section_name_surrounding_beg,
35
         self.__section_name_surrounding_end) = (
36
            tuple(self.__section_name_surroundings.items())[0])
37
38
    def _close(self):
39
        self.__file.close()
40
41
    def write_sections(self, sections):
42
        assert not self.__closed
43
44
        self.__wrote_newline = True
45
        for section in sections:
46
            self.write_section(sections[section])
47
48
    def write_section(self, section):
49
        assert not self.__closed
50
51
        if not isinstance(section, Section):
52
            raise TypeError
53
54
        self.__write_section_name(section.name)
55
56
        keys = []
57
        val = None
58
        section_iter = section.__iter__(ignore_defaults=True)
59
        try:
60
            while True:
61
                setting = section[next(section_iter)]
62
                if (str(setting) == val and
63
                    not self.is_comment(setting.key) and
64
                    (
65
                        (setting.key not in self.__unsavable_keys) or
66
                        (not setting.from_cli))):
67
                    keys.append(setting.key)
68
                elif ((setting.key not in self.__unsavable_keys) or
69
                      (not setting.from_cli)):
70
                    self.__write_key_val(keys, val)
71
                    keys = [setting.key]
72
                    val = str(setting)
73
        except StopIteration:
74
            self.__write_key_val(keys, val)
75
76
    def __write_section_name(self, name):
77
        assert not self.__closed
78
79
        if not self.__wrote_newline:
80
            self.__file.write("\n")
81
82
        self.__file.write(self.__section_name_surrounding_beg + name +
83
                          self.__section_name_surrounding_end + '\n')
84
        self.__wrote_newline = False
85
86
    def __write_key_val(self, keys, val):
87
        assert not self.__closed
88
89
        if keys == []:
90
            return
91
92
        if all(self.is_comment(key) for key in keys):
93
            self.__file.write(val + "\n")
94
            self.__wrote_newline = val == ""
95
            return
96
97
        # Add escape characters as appropriate
98
        keys = [escape(key, chain(['\\'],
99
                                  self.__key_value_delimiters,
100
                                  self.__comment_separators,
101
                                  self.__key_delimiters,
102
                                  self.__section_override_delimiters))
103
                for key in keys]
104
        val = escape(val, chain(['\\'], self.__comment_separators))
105
106
        self.__file.write((self.__key_delimiter + " ").join(keys) + " " +
107
                          self.__key_value_delimiter + " " + val + "\n")
108
        self.__wrote_newline = False
109
110
    @staticmethod
111
    def is_comment(key):
112
        return key.lower().startswith("comment")
113