File: cfg.py

package info (click to toggle)
solfege 2.0.4-4
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 3,200 kB
  • ctags: 1,844
  • sloc: python: 12,160; xml: 5,458; ansic: 1,486; makefile: 562; sh: 233
file content (351 lines) | stat: -rw-r--r-- 10,378 bytes parent folder | download
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# GNU Solfege - eartraining for GNOME
# Copyright (C) 2000, 2001, 2002, 2003  Tom Cato Amundsen
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
"""
TODO:
    - cfg.get_list
    - cfg.set_list
    - watches outside ConfigUtils
>>> import cfg
>>> cfg.initialise(None, "default.config", "~/.cfg-test")
>>> cfg.set_string("section/stringvar", "value")
>>> cfg.get_string("section/stringvar")
'value'
>>> cfg.set_int("section/intvar", 14)
>>> cfg.get_int("section/intvar")
14
>>> cfg.set_float("section/floatvar", 3.141592)
>>> cfg.get_float("section/floatvar") == 3.141592
1
>>> cfg.set_bool("section/boolvar", 4)
>>> cfg.get_bool("section/boolvar")
1
>>> cfg.set_bool("section/boolvar", 0)
>>> cfg.get_bool("section/boolvar")
0
>>> cfg.set_list("section/listv", [1, 2, 3])
>>> cfg.get_list("section/listv")
[1, 2, 3]
>>> c = ConfigUtils("section")
>>> c.get_string("section/stringvar")
'value'
>>> c.get_int("section/intvar")
14
>>> c.get_bool("section/boolvar")
0
>>> c.get_float("section/floatvar") == 3.141592
1
>>> cfg.initialise(None, None, "~/.solfege-cfg-testing")
>>> c.get_string("ss/a")
''
>>> c.get_string("ss/a=hei")
'hei'
>>> c.get_int("ss/a=3")
3
>>> c.get_list("ss/a")
[]
>>> c.get_list("ss/a=[1, 2, 3]")
[1, 2, 3]
"""

import string, re
import types
import os, os.path, sys

# It is a know fact that many windows lusers are $HOMEless
if sys.platform == 'win32':
    if not os.path.exists(os.path.expanduser("~")):
        os.makedirs(os.path.expanduser("~"))

section_re = re.compile("\[(.*?)\]")
value_re = re.compile("(.*?)=(.*)")
comment_re = re.compile("#.*")

# FIXME why did I comment out the lines below. Test in ms windows
# if this still works, and if so, delete the commented lines.
def split(key):
   #if "/" in key:
       return string.split(key, "/")
   #else:
   #    return string.split(key, "\\")

def parse_file_into_dict(dict, filename):
    file = open(filename, "r")
    line = file.readline()
    section = None
    while line:
        section_m = section_re.match(line)
        value_m = value_re.match(line)
        comment_m = comment_re.match(line)
        if section_m:
            section = section_m.groups()[0]
            if not dict.has_key(section):
                dict[section] = {}
        elif value_m:
            assert section
            dict[section][value_m.groups()[0]] = value_m.groups()[1]
        elif line == "\n":
            pass
        elif comment_m:
            pass
        else:
           print filename
           raise Exception("Shit happended line %s" % line)
        line = file.readline()
    file.close()
    return dict


def sync():
    dump(data, _user_filename)

def _maybe_create_key(key):
    global data
    section, k = split(key)
    if not data.has_key(section):
        data[section] = {}

########################
## set_XXXX functions ##
########################

def set_string(key, val):
    global data
    _maybe_create_key(key)
    section, k = split(key)
    oldval = get_string(key)
    data[section][k] = val
    if _watches.has_key(key) and (oldval != get_string(key)):
        for cb in _watches[key].values():
            cb(key)

def set_int(key, val):
    global data, _watches
    assert type(val) == types.IntType
    _maybe_create_key(key)
    section, k = split(key)
    oldval = get_string(key)
    data[section][k] = str(val)
    if _watches.has_key(key) and (oldval != get_string(key)):
        for cb in _watches[key].values():
            cb(key)

def set_float(key, val):
    global data, _watches
    assert type(val) == types.FloatType
    _maybe_create_key(key)
    section, k = split(key)
    oldval = get_string(key)
    data[section][k] = str(val)
    if _watches.has_key(key) and (oldval != get_string(key)):
        for cb in _watches[key].values():
            cb(key)

def set_bool(key, val):
    global data, _watches
    _maybe_create_key(key)
    if val:
        set_string(key, "true")
    else:
        set_string(key, "false")

def set_list(key, val):
    global data, _watches
    set_string(key, str(val))

########################
## get_XXX functions ##
########################

def get_string(key):
    if len(string.split(key, "=")) == 2:
        key, default = string.split(key, "=")
    else:
        default = ""
    section, k = split(key)
    try:
        return data[section][k]
    except KeyError:
        return default

def get_int(key):
   if len(string.split(key, "=")) == 2:
      key, default = string.split(key, "=")
   else:
      default = 0
   section, k = split(key)
   try:
       # UGH win32 fix
       if not data[section][k]:
           return 0
       return int(float(data[section][k]))
   except KeyError:
       return int(default)

def get_float(key):
   if len(string.split(key, "=")) == 2:
      key, default = string.split(key, "=")
   else:
      default = 0
   section, k = split(key)
   try:
       return float(data[section][k])
   except KeyError:
       return float(default)


def get_bool(key):
    if get_string(key) == 'true':
        return 1
    elif get_string(key) == 'false':
        return 0
    else:
        print "warning: cfg.get_bool: value of '%s' is not true or false" % key
        return 0

def get_list(key):
    return eval(get_string(key))

######################################
## reading and writing the database ##
######################################

def dump(dict, fn):
    f = open(fn, 'w')
    for section in dict.keys():
        f.write("[%s]\n" % section)
        for name in dict[section].keys():
            f.write("%s=%s\n" % (name, dict[section][name]))
        f.write("\n")
    f.close()

def drop_user_config():
    """
    Reread the config data, but only read the systems defaults, not
    .solfegerc in the users $HOME.
    """
    global data, _watches, _watch_counter
    data = {}
    _watches = {}
    _watch_counter = 0
    data = parse_file_into_dict(data, _system_filename)

def reread_data():
    global data, _watches, _watch_counter
    _watches = {}
    _watch_counter = 0
    if _app_defaults_filename:
        data = parse_file_into_dict({}, _app_defaults_filename)
    if _system_filename:
        data = parse_file_into_dict(data, _system_filename)
    if _user_filename and os.path.isfile(_user_filename):
        data = parse_file_into_dict(data, _user_filename)

def initialise(app_defaults_filename, system_filename, user_filename):
    """
    app_defaults_filename: file must exist!
    system_filename: sys admin can override app_defaults_filename
    user_filename: the state of the app is stored here, also user config.
    """
    global data, _watches, _watch_counter
    global _app_defaults_filename, _system_filename, _user_filename
    _watches = {}
    _watch_counter = 0
    _app_defaults_filename = app_defaults_filename
    _system_filename = system_filename
    _user_filename = user_filename = os.path.expanduser(user_filename)
    if app_defaults_filename:
        try:
            data = parse_file_into_dict({}, app_defaults_filename)
        except:
            raise Exception("Solfege install is completely broken.\nCannot find required file %s" % app_defaults_filename)
    else:
        data = {}
    if system_filename and os.path.isfile(system_filename):
        data = parse_file_into_dict(data, system_filename)
    if os.path.isfile(user_filename):
        data = parse_file_into_dict(data, user_filename)


class ConfigUtils(object):
    def __init__(self, exname):
        self.m_exname = exname
    def add_watch(self, name, callback):
        global _watches, _watch_counter
        name = self._expand_name(name)
        if not _watches.has_key(name):
            _watches[name] = {}
        _watches[name][_watch_counter] = callback
        _watch_counter += 1
        return _watch_counter - 1
    def remove_watch(self, name, id):
        global _watches, _watch_counter
        name = self._expand_name(name)
        if _watches.has_key(name):
            if _watches[name].has_key(id):
                del _watches[name][id]
                if _watches[name] == {}:
                    del _watches[name]
            else:
                print "warning: remove_watch: id don't exist:", id
        else:
            print "warning: remove_watch: name is not watched:", name
    def _expand_name(self, name):
        if string.count(name, "/") == 0:
            return "%s/%s" % (self.m_exname, name)
        return name
    ######
    # set
    ######
    def set_string(self, name, val):
        set_string(self._expand_name(name), val)
    def set_int(self, name, val):
        set_int(self._expand_name(name), val)
    def set_float(self, name, val):
        set_float(self._expand_name(name), val)
    def set_bool(self, name, val):
        set_bool(self._expand_name(name), val)
    def set_list(self, name, val):
        set_list(self._expand_name(name), val)
    ######
    # get
    ######
    def _get(self, func, name, default=""):
        return func(self._expand_name(name)+default)
    def get_string(self, name):
        r = self._get(get_string, name)
        if r is None:
            return ""
        else:
            return r
    def get_int(self, name):
        return self._get(get_int, name)
    def get_int_with_default(self, name, default):
        assert type(default) is type(0)
        return self.get_int(name+"=%i" % default)
    def get_float(self, name):
        return self._get(get_float, name)
    def get_bool(self, name):
        return self._get(get_bool, name)
    def get_list(self, name):
        if '=' in name:
           return eval(self._get(get_string, name))
        return eval(self._get(get_string, name, "=[]"))


if __name__ == '__main__':
    import doctest, cfg
    print doctest.testmod(cfg)