Merge pull request #21 from mafagafogigante/typos
[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 = load_config(path)
95 # Update global config
96 c[key] = value
97 # Update config file
98 if key in data:
99 fixup(data, key, value)
100 else:
101 data[key] = value
102 # Save
103 with open(path, 'w') as out:
104 json.dump(data, out, indent=4)
105 os.system('chmod 777 ' + path)
106
107
108 def delete_config(key):
109 """
110 Delete a config key
111 """
112 path = os.environ.get(
113 'HOME',
114 os.environ.get(
115 'USERPROFILE',
116 '')) + os.sep + '.rainbow_config.json'
117 data = load_config(path)
118 # Drop key
119 if key in data and key in c:
120 data.pop(key)
121 c.pop(key)
122 try:
123 data[key] = c[key] = get_default_config(key)
124 except:
125 pass
126 else:
127 raise Exception('No such config key.')
128 # Save
129 with open(path, 'w') as out:
130 json.dump(data, out, indent=4)
131 os.system('chmod 777 ' + path)
132
133
134 def reload_config():
135 """
136 Reload config
137 """
138 rainbow_config = os.environ.get(
139 'HOME',
140 os.environ.get(
141 'USERPROFILE',
142 '')) + os.sep + '.rainbow_config.json'
143 try:
144 data = load_config(rainbow_config)
145 for d in data:
146 c[d] = data[d]
147 except:
148 print('It seems that ~/.rainbow_config.json has wrong format :(')
149
150
151 def init_config():
152 """
153 Init configuration
154 """
155 # Load the initial config
156 config = os.path.dirname(
157 __file__) + '/colorset/config'
158 try:
159 data = load_config(config)
160 for d in data:
161 c[d] = data[d]
162 except:
163 pass
164 # Load user's config
165 rainbow_config = os.environ.get(
166 'HOME',
167 os.environ.get(
168 'USERPROFILE',
169 '')) + os.sep + '.rainbow_config.json'
170 try:
171 data = load_config(rainbow_config)
172 for d in data:
173 c[d] = data[d]
174 except:
175 print('It seems that ~/.rainbow_config.json has wrong format :(')
176 # Load default theme
177 theme_file = os.path.dirname(
178 __file__) + '/colorset/' + c['THEME'] + '.json'
179 try:
180 data = load_config(theme_file)
181 for d in data:
182 c[d] = data[d]
183 except:
184 pass
185
186
187 # Init config
188 init_config()