Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/util/configfile.py
blob: dead00a0a87d171bb32aeed07060cba3df9bb58c (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
#!/usr/bin/env python
#
# Copyright (c) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

import gobject


class ConfigFile(gobject.GObject):
    """Load/save a simple (key = value) config file"""

    __gsignals__ = {
        'configuration-loaded': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
                                 ()),
        'configuration-saved': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
                                ()),
    }

    def __init__(self, config_file_path, valid_keys={}):
        gobject.GObject.__init__(self)

        self._config_file_path = config_file_path
        self._valid_keys = valid_keys
        self._config_hash = {}
        self._is_loaded = False

    def set_valid_keys(self, valid_keys):
        self._valid_keys = valid_keys

    def is_loaded(self):
        return self._is_loaded

    def get(self, key, empty_if_not_loaded=False):
        if not key in self._valid_keys:
            raise RuntimeError("Unknown config value %s" % key)

        if key in self._config_hash:
            value = self._config_hash[key]
        else:
            if self._valid_keys[key]["type"] == "text":
                value = ""
            elif self._valid_keys[key]["type"] == "boolean":
                value = False
            elif self._valid_keys[key]["type"] == "integer":
                value = 0

        return value

    def set(self, key, value):
        if not key in self._valid_keys:
            raise RuntimeError("Unknown config value %s" % key)

        self._config_hash[key] = value

    def load(self):
        try:
            config_file = open(self._config_file_path, 'r')
            lines = config_file.readlines()
            config_file.close()
            for line in lines:
                line = line.strip()
                k, v = line.split('=')
                k = k.strip(' ')
                v = v.strip(' ')
                if not k in self._valid_keys:
                    raise RuntimeError("Unknown config value %s" % k)
                value_type = self._valid_keys[k]["type"]
                if value_type == "text":
                    value = v
                elif value_type == "boolean":
                    value = eval(v)
                elif value_type == "integer":
                    value = int(v)
                self._config_hash[k] = value
            self._is_loaded = True
            self.emit('configuration-loaded')
        except Exception, e:
            print e

        return self._is_loaded

    def save(self):
        config_file = open(self._config_file_path, 'w')
        for k in self._config_hash.keys():
            v = self._config_hash[k]
            l = "%s = %s\n" % (k, v)
            config_file.write(l)
        config_file.close()
        self.emit('configuration-saved')

    def dump_keys(self):
        print "\n\nDumping keys\n\n"
        for k in self._config_hash.keys():
            v = self._config_hash[k]
            l = "%s = %s\n" % (k, v)
            print l


def test_save_load(test_config_file):
    keys = {}
    keys["nick"] = {"type": "text"}
    keys["account_id"] = {"type": "text"}
    keys["server"] = {"type": "text"}
    keys["port"] = {"type": "text"}
    keys["password"] = {"type": "text"}
    keys["register"] = {"type": "text"}

    c = ConfigFile(test_config_file)
    c.set_valid_keys(keys)
    c.set("nick", "rgs")
    c.set("account_id", "rgs@andromeda")
    c.set("server", "andromeda")
    c.set("port", 5223)
    c.set("password", "97c74fa0dc3b39b8c87f119fa53cced2b7040786")
    c.set("register", True)

    c.save()

    c = ConfigFile(test_config_file)
    c.set_valid_keys(keys)
    c.load()
    c.dump_keys()


def _configuration_saved_cb(config_file_obj):
    print "_configuration_saved_cb called"
    config_file_obj.dump_keys()


def _configuration_loaded_cb(config_file_obj):
    print "_configuration_loaded_cb called"
    config_file_obj.dump_keys()


def test_signals(test_config_file):
    keys = {}
    keys["nick"] = {"type": "text"}
    keys["account_id"] = {"type": "text"}
    keys["server"] = {"type": "text"}
    keys["port"] = {"type": "text"}
    keys["password"] = {"type": "text"}
    keys["register"] = {"type": "text"}

    c = ConfigFile(test_config_file)
    c.connect('configuration-saved', _configuration_saved_cb)
    c.set_valid_keys(keys)
    c.set("nick", "rgs")
    c.set("account_id", "rgs@andromeda")
    c.set("server", "andromeda")
    c.set("port", 5223)
    c.set("password", "97c74fa0dc3b39b8c87f119fa53cced2b7040786")
    c.set("register", True)

    c.save()

    c = ConfigFile(test_config_file)
    c.connect('configuration-loaded', _configuration_loaded_cb)
    c.set_valid_keys(keys)
    c.load()


if __name__ == "__main__":
    test_save_load("/tmp/configfile.0001")
    test_signals("/tmp/configfile.0002")