summaryrefslogtreecommitdiffstats
path: root/configinterface.py
blob: 7bc1d4731a7ac8d47a8171aad19e8c57a94e0f4b (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
import ConfigParser

DEF_SECT = 'global'

class GConffile(object):

    def __init__(self, path, peers):
        if peers:
            self.section = 'peers ' + ' '.join(peers)
        else:
            self.section = DEF_SECT
        self.path = path
        self.config = ConfigParser.RawConfigParser({}, dict)
        self.config.read(path)

    def update_to(self, dct):
        for sect in set([DEF_SECT, self.section]):
            if self.config.has_section(sect):
                dct.update(self.config._sections[sect])

    def get(self, opt=None):
        d = {}
        self.update_to(d)
        if opt:
            d = {opt: d.get(opt, "")}
        for k, v in d.iteritems():
            if k == '__name__':
                continue
            print("%s: %s" % (k, v))

    def write(self):
        f = None
        try:
            f = open(self.path, 'wb')
            self.config.write(f)
        finally:
            if f:
                f.close()

    def set(self, opt, val):
        if not self.config.has_section(self.section):
            self.config.add_section(self.section)
        self.config.set(self.section, opt, val)
        self.write()

    def delete(self, opt):
        if not self.config.has_section(self.section):
            return
        if self.config.remove_option(self.section, opt):
            self.write()