fix serious bug in import HTMLParser in Python > 3.4
[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 path = os.environ.get(
46 'HOME',
47 os.environ.get(
48 'USERPROFILE',
49 '')) + os.sep + '.rainbow_config.json'
50 data = load_config(path)
51 # Hard to set from prompt
52 data.pop('ONLY_LIST', None)
53 data.pop('IGNORE_LIST', None)
54 return data
55
56
57 def get_default_config(key):
58 """
59 Get default value of a config key
60 """
61 path = os.path.dirname(
62 __file__) + '/colorset/config'
63 try:
64 data = load_config(path)
65 except:
66 raise Exception('No such config key.')
67 return data[key]
68
69
70 def get_config(key):
71 """
72 Get current value of a config key
73 """
74 return c[key]
75
76
77 def set_config(key, value):
78 """
79 Set a config key with specific value
80 """
81 # Modify value
82 if value.isdigit():
83 value = int(value)
84 elif value.lower() == 'true':
85 value = True
86 elif value.lower() == 'false':
87 value = False
88 # Fix up
89 path = os.environ.get(
90 'HOME',
91 os.environ.get(
92 'USERPROFILE',
93 '')) + os.sep + '.rainbow_config.json'
94 data = {}
95 try:
96 data = load_config(path)
97 except:
98 pass
99 # Update global config
100 c[key] = value
101 # Update config file
102 if key in data:
103 fixup(data, key, value)
104 else:
105 data[key] = value
106 # Save
107 with open(path, 'w') as out:
108 json.dump(data, out, indent=4)
109 os.system('chmod 777 ' + path)
110
111
112 def delete_config(key):
113 """
114 Delete a config key
115 """
116 path = os.environ.get(
117 'HOME',
118 os.environ.get(
119 'USERPROFILE',
120 '')) + os.sep + '.rainbow_config.json'
121 data = load_config(path)
122 # Drop key
123 if key in data and key in c:
124 data.pop(key)
125 c.pop(key)
126 try:
127 data[key] = c[key] = get_default_config(key)
128 except:
129 pass
130 else:
131 raise Exception('No such config key.')
132 # Save
133 with open(path, 'w') as out:
134 json.dump(data, out, indent=4)
135 os.system('chmod 777 ' + path)
136
137
138 def reload_config():
139 """
140 Reload config
141 """
142 rainbow_config = os.environ.get(
143 'HOME',
144 os.environ.get(
145 'USERPROFILE',
146 '')) + os.sep + '.rainbow_config.json'
147 try:
148 data = load_config(rainbow_config)
149 for d in data:
150 c[d] = data[d]
151 except:
152 print('It seems that ~/.rainbow_config.json has wrong format :(')
153
154
155 def init_config():
156 """
157 Init configuration
158 """
159 # Load the initial config
160 config = os.path.dirname(
161 __file__) + '/colorset/config'
162 try:
163 data = load_config(config)
164 for d in data:
165 c[d] = data[d]
166 except:
167 pass
168 # Load user's config
169 rainbow_config = os.environ.get(
170 'HOME',
171 os.environ.get(
172 'USERPROFILE',
173 '')) + os.sep + '.rainbow_config.json'
174 try:
175 data = load_config(rainbow_config)
176 for d in data:
177 c[d] = data[d]
178 except:
179 pass
180 # Load default theme
181 theme_file = os.path.dirname(
182 __file__) + '/colorset/' + c['THEME'] + '.json'
183 try:
184 data = load_config(theme_file)
185 for d in data:
186 c[d] = data[d]
187 except:
188 pass
189
190
191 # Init config
192 init_config()