merge with built mute dict
[rainbowstream.git] / rainbowstream / config.py
1 import json
2 import re
3 import os
4 import os.path
5 from collections import OrderedDict
6
7 # Regular expression for comments in config file
8 comment_re = re.compile(
9 '(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?',
10 re.DOTALL | re.MULTILINE
11 )
12
13 # Config dictionary
14 c = {}
15
16
17 def fixup(adict, k, v):
18 """
19 Fix up a key in json format
20 """
21 for key in adict.keys():
22 if key == k:
23 adict[key] = v
24 elif isinstance(adict[key], dict):
25 fixup(adict[key], k, v)
26
27
28 def load_config(filepath):
29 """
30 Load config from filepath
31 """
32 with open(filepath) as f:
33 content = ''.join(f.readlines())
34 match = comment_re.search(content)
35 while match:
36 content = content[:match.start()] + content[match.end():]
37 match = comment_re.search(content)
38 return json.loads(content, object_pairs_hook=OrderedDict)
39
40
41 def get_all_config():
42 """
43 Get all config
44 """
45 try:
46 path = os.path.expanduser("~") + os.sep + '.rainbow_config.json'
47 data = load_config(path)
48 # Hard to set from prompt
49 data.pop('ONLY_LIST', None)
50 data.pop('IGNORE_LIST', None)
51 data.pop('FORMAT', None)
52 return data
53 except:
54 return []
55
56
57 def get_default_config(key):
58 """
59 Get default value of a config key
60 """
61 try:
62 path = os.path.dirname(__file__) + '/colorset/config'
63 data = load_config(path)
64 return data[key]
65 except:
66 raise Exception('This config key does not exist in default.')
67
68
69 def get_config(key):
70 """
71 Get current value of a config key
72 """
73 return c[key]
74
75
76 def set_config(key, value):
77 """
78 Set a config key with specific value
79 """
80 # Modify value
81 if value.isdigit():
82 value = int(value)
83 elif value.lower() == 'true':
84 value = True
85 elif value.lower() == 'false':
86 value = False
87 # Update global config
88 c[key] = value
89 # Load current user config
90 path = os.path.expanduser("~") + os.sep + '.rainbow_config.json'
91 data = {}
92 try:
93 data = load_config(path)
94 except:
95 return
96 # Update config file
97 if key in data:
98 fixup(data, key, value)
99 else:
100 data[key] = value
101 # Save
102 with open(path, 'w') as out:
103 json.dump(data, out, indent=4)
104 os.system('chmod 777 ' + path)
105
106
107 def delete_config(key):
108 """
109 Delete a config key
110 """
111 path = os.path.expanduser("~") + os.sep + '.rainbow_config.json'
112 try:
113 data = load_config(path)
114 except:
115 raise Exception('Config file is messed up.')
116 # Drop key
117 if key in data and key in c:
118 data.pop(key)
119 c.pop(key)
120 try:
121 data[key] = c[key] = get_default_config(key)
122 except:
123 pass
124 else:
125 raise Exception('No such config key.')
126 # Save
127 with open(path, 'w') as out:
128 json.dump(data, out, indent=4)
129 os.system('chmod 777 ' + path)
130
131
132 def reload_config():
133 """
134 Reload config
135 """
136 try:
137 rainbow_config = os.path.expanduser("~") + os.sep + '.rainbow_config.json'
138 data = load_config(rainbow_config)
139 for d in data:
140 c[d] = data[d]
141 except:
142 raise Exception('Can not reload config file with wrong format.')
143
144
145 def init_config():
146 """
147 Init configuration
148 """
149 # Load the initial config
150 config = os.path.dirname(__file__) + \
151 '/colorset/config'
152 try:
153 data = load_config(config)
154 for d in data:
155 c[d] = data[d]
156 except:
157 pass
158 # Load user's config
159 rainbow_config = os.path.expanduser("~") + os.sep + '.rainbow_config.json'
160 try:
161 data = load_config(rainbow_config)
162 for d in data:
163 c[d] = data[d]
164 except ValueError as e:
165 c['USER_JSON_ERROR'] = str(e)
166 # Load default theme
167 theme_file = os.path.dirname(__file__) + \
168 '/colorset/' + c['THEME'] + '.json'
169 try:
170 data = load_config(theme_file)
171 for d in data:
172 c[d] = data[d]
173 except:
174 pass
175
176
177 # Init config
178 init_config()