aboutsummaryrefslogtreecommitdiffstats
path: root/debian/lib/python/debian_linux/config.py
blob: 970039acae750978d7f30f438dff029606deeb85 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import os, os.path, re, sys, textwrap, ConfigParser

__all__ = [
    'config_parser',
    'config_reader',
    'config_reader_arch',
]

_marker = object()

class schema_item_boolean(object):
    def __call__(self, i):
        i = i.strip().lower()
        if i in ("true", "1"):
            return True
        if i in ("false", "0"):
            return False
        raise Error

class schema_item_list(object):
    def __init__(self, type = "\s+"):
        self.type = type

    def __call__(self, i):
        i = i.strip()
        if not i:
            return []
        return [j.strip() for j in re.split(self.type, i)]

class config_reader(dict):
    config_name = "defines"

    def __init__(self, dirs = []):
        self._dirs = dirs

    def __getitem__(self, key):
        return self.get(key)

    def _get_files(self, name):
        return [os.path.join(i, name) for i in self._dirs if i]

    def _update(self, ret, inputkey):
        for key, value in super(config_reader, self).get(tuple(inputkey), {}).iteritems():
            ret[key] = value

    def get(self, key, default = _marker):
        if isinstance(key, basestring):
            key = key,

        ret = super(config_reader, self).get(tuple(key), default)
        if ret == _marker:
            raise KeyError, key
        return ret

    def merge(self, section, *args):
        ret = {}
        for i in xrange(0, len(args) + 1):
            ret.update(self.get(tuple([section] + list(args[:i])), {}))
        return ret

    def sections(self):
        return super(config_reader, self).keys()

class config_reader_arch(config_reader):
    schema = {
        'arches': schema_item_list(),
        'available': schema_item_boolean(),
        'configs': schema_item_list(),
        'flavours': schema_item_list(),
        'initramfs': schema_item_boolean(),
        'initramfs-generators': schema_item_list(),
        'modules': schema_item_boolean(),
        'subarches': schema_item_list(),
        'versions': schema_item_list(),
    }

    def __init__(self, dirs = []):
        super(config_reader_arch, self).__init__(dirs)
        self._read_base()

    def _read_arch(self, arch):
        files = self._get_files("%s/%s" % (arch, self.config_name))
        config = config_parser(self.schema, files)

        subarches = config['base',].get('subarches', [])
        flavours = config['base',].get('flavours', [])

        for section in iter(config):
            real = list(section)
            # TODO
            if real[-1] in subarches:
                real[0:0] = ['base', arch]
            elif real[-1] in flavours:
                real[0:0] = ['base', arch, 'none']
            else:
                real[0:0] = [real.pop()]
                if real[-1] in flavours:
                    real[1:1] = [arch, 'none']
                else:
                    real[1:1] = [arch]
            real = tuple(real)
            s = self.get(real, {})
            s.update(config[section])
            self[tuple(real)] = s

        for subarch in subarches:
            if self.has_key(('base', arch, subarch)):
                avail = self['base', arch, subarch].get('available', True)
            else:
                avail = True
            if avail:
                self._read_subarch(arch, subarch)

        base = self['base', arch]
        base['subarches'] = subarches

        if flavours:
            subarches.insert(0, 'none')
            del base['flavours']
            self['base', arch] = base
            self['base', arch, 'none'] = {'flavours': flavours}
            for flavour in flavours:
                self._read_flavour(arch, 'none', flavour)

    def _read_base(self):
        files = self._get_files(self.config_name)
        config = config_parser(self.schema, files)

        arches = config['base',]['arches']

        for section in iter(config):
            real = list(section)
            if real[-1] in arches:
                real.insert(0, 'base')
            else:
                real.insert(0, real.pop())
            self[tuple(real)] = config[section]

        for arch in arches:
            try:
                avail = self['base', arch].get('available', True)
            except KeyError:
                avail = True
            if avail:
                self._read_arch(arch)

    def _read_flavour(self, arch, subarch, flavour):
        if not self.has_key(('base', arch, subarch, flavour)):
            if subarch == 'none':
                import warnings
                warnings.warn('No config entry for flavour %s, subarch none, arch %s' % (flavour, arch), DeprecationWarning)
            self['base', arch, subarch, flavour] = {}

    def _read_subarch(self, arch, subarch):
        files = self._get_files("%s/%s/%s" % (arch, subarch, self.config_name))
        config = config_parser(self.schema, files)

        flavours = config['base',].get('flavours', [])

        for section in iter(config):
            real = list(section)
            if real[-1] in flavours:
                real[0:0] = ['base', arch, subarch]
            else:
                real[0:0] = [real.pop(), arch, subarch]
            real = tuple(real)
            s = self.get(real, {})
            s.update(config[section])
            self[tuple(real)] = s

        for flavour in flavours:
            self._read_flavour(arch, subarch, flavour)

    def merge(self, section, arch = None, subarch = None, flavour = None):
        ret = {}
        ret.update(self.get((section,), {}))
        if arch:
            ret.update(self.get((section, arch), {}))
        if flavour and subarch and subarch != 'none':
            ret.update(self.get((section, arch, 'none', flavour), {}))
        if subarch:
            ret.update(self.get((section, arch, subarch), {}))
        if flavour:
            ret.update(self.get((section, arch, subarch, flavour), {}))
        return ret

class config_parser(object):
    __slots__ = 'configs', 'schema'

    def __init__(self, schema, files):
        self.configs = []
        self.schema = schema
        for file in files:
            config = ConfigParser.ConfigParser()
            config.read(file)
            self.configs.append(config)

    def __getitem__(self, key):
        return self.items(key)

    def __iter__(self):
        return iter(self.sections())

    def items(self, section, var = {}):
        ret = {}
        section = '_'.join(section)
        exceptions = []
        for config in self.configs:
            try:
                items = config.items(section)
            except ConfigParser.NoSectionError, e:
                exceptions.append(e)
            else:
                for key, value in items:
                    try:
                        value = self.schema[key](value)
                    except KeyError: pass
                    ret[key] = value
        if len(exceptions) == len(self.configs):
            raise exceptions[0]
        return ret

    def sections(self):
        sections = []
        for config in self.configs:
            for section in config.sections():
                section = tuple(section.split('_'))
                if section not in sections:
                    sections.append(section)
        return sections

if __name__ == '__main__':
    import sys
    config = config_reader()
    sections = config.sections()
    sections.sort()
    for section in sections:
        print "[%s]" % (section,)
        items = config[section]
        items_keys = items.keys()
        items_keys.sort()
        for item in items:
            print "%s: %s" % (item, items[item])
        print