Mercurial > hg > config
comparison python/prefs.py @ 143:31a41264d51f
add a naive prefs reader
author | Jeff Hammel <jhammel@mozilla.com> |
---|---|
date | Tue, 31 May 2011 15:34:36 -0700 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
142:09c10061838c | 143:31a41264d51f |
---|---|
1 import re | |
2 comment = re.compile('/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/', re.MULTILINE) | |
3 | |
4 def read(filename): | |
5 token = '##//' # magical token | |
6 lines = [i.strip() for i in file(filename).readlines() if i.strip()] | |
7 retval = {} | |
8 _lines = [] | |
9 for line in lines: | |
10 if line.startswith('#'): | |
11 continue | |
12 if '//' in line: | |
13 line = line.replace('//', token) | |
14 _lines.append(line) | |
15 string = '\n'.join(_lines) | |
16 string = re.sub(comment, '', string) | |
17 def pref(a, b): | |
18 retval[a] = b | |
19 lines = [i.strip().rstrip(';') for i in string.split('\n') if i.strip()] | |
20 for line in lines: | |
21 try: | |
22 _globals = {'retval': retval, 'pref': pref, 'user_pref': pref, 'true': True, 'false': False} | |
23 eval(line, _globals, {}) | |
24 except SyntaxError: | |
25 print line | |
26 import pdb; pdb.set_trace() | |
27 for key in retval: | |
28 if isinstance(retval[key], basestring) and token in retval[key]: | |
29 retval[key] = retval[key].replace(token, '//') | |
30 return retval | |
31 | |
32 def write(filename, prefs, pref_string='user_pref("%s", %s);'): | |
33 f = file(filename, 'w') | |
34 for key, value in prefs.items(): | |
35 if value is True: | |
36 print >> f, pref_string % (key, 'true') | |
37 elif value is False: | |
38 print >> f, pref_string % (key, 'true') | |
39 elif isinstance(value, basestring): | |
40 print >> f, pref_string % (key, repr(string(value))) | |
41 else: | |
42 print >> f, pref_string % (key, value) # should be numeric! | |
43 f.close() | |
44 | |
45 if __name__ == '__main__': | |
46 import sys | |
47 if not sys.argv[1:]: | |
48 sys.exit(1) | |
49 print read(sys.argv[1]) |