add info and colored
[rainbowstream.git] / rainbowstream / config.py
... / ...
CommitLineData
1import json
2import re
3import os
4import os.path
5from collections import OrderedDict
6
7# Regular expression for comments in config file
8comment_re = re.compile(
9 '(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?',
10 re.DOTALL | re.MULTILINE
11)
12
13# Config dictionary
14c = {}
15
16
17def 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
28def 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
41def 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
57def 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
69def get_config(key):
70 """
71 Get current value of a config key
72 """
73 return c[key]
74
75
76def 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
107def 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
132def reload_config():
133 """
134 Reload config
135 """
136 try:
137 rainbow_config = os.path.expanduser("~") + \
138 os.sep + '.rainbow_config.json'
139 data = load_config(rainbow_config)
140 for d in data:
141 c[d] = data[d]
142 except:
143 raise Exception('Can not reload config file with wrong format.')
144
145
146def init_config():
147 """
148 Init configuration
149 """
150 # Load the initial config
151 config = os.path.dirname(__file__) + \
152 '/colorset/config'
153 try:
154 data = load_config(config)
155 for d in data:
156 c[d] = data[d]
157 except:
158 pass
159 # Load user's config
160 rainbow_config = os.path.expanduser("~") + os.sep + '.rainbow_config.json'
161 try:
162 data = load_config(rainbow_config)
163 for d in data:
164 c[d] = data[d]
165 except (IOError, ValueError) as e:
166 c['USER_JSON_ERROR'] = str(e)
167 # Load default theme
168 theme_file = os.path.dirname(__file__) + \
169 '/colorset/' + c['THEME'] + '.json'
170 try:
171 data = load_config(theme_file)
172 for d in data:
173 c[d] = data[d]
174 except:
175 pass
176
177
178# Init config
179init_config()