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