5 from collections
import OrderedDict
7 # Regular expression for comments in config file
8 comment_re
= re
.compile(
9 '(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?',
10 re
.DOTALL | re
.MULTILINE
17 def fixup(adict
, k
, v
):
19 Fix up a key in json format
21 for key
in adict
.keys():
24 elif isinstance(adict
[key
], dict):
25 fixup(adict
[key
], k
, v
)
28 def load_config(filepath
):
30 Load config from filepath
32 with
open(filepath
) as f
:
33 content
= ''.join(f
.readlines())
34 match
= comment_re
.search(content
)
36 content
= content
[:match
.start()] + content
[match
.end():]
37 match
= comment_re
.search(content
)
38 return json
.loads(content
, object_pairs_hook
=OrderedDict
)
45 path
= os
.path
.expanduser("~") + os
.sep
+ '.rainbow_config.json'
46 data
= load_config(path
)
47 # Hard to set from prompt
48 data
.pop('ONLY_LIST', None)
49 data
.pop('IGNORE_LIST', None)
50 data
.pop('FORMAT', None)
54 def get_default_config(key
):
56 Get default value of a config key
58 path
= os
.path
.dirname(
59 __file__
) + '/colorset/config'
61 data
= load_config(path
)
63 raise Exception('No such config key.')
69 Get current value of a config key
74 def set_config(key
, value
):
76 Set a config key with specific value
81 elif value
.lower() == 'true':
83 elif value
.lower() == 'false':
86 path
= os
.path
.expanduser("~") + os
.sep
+ '.rainbow_config.json'
89 data
= load_config(path
)
92 # Update global config
96 fixup(data
, key
, value
)
100 with
open(path
, 'w') as out
:
101 json
.dump(data
, out
, indent
=4)
102 os
.system('chmod 777 ' + path
)
105 def delete_config(key
):
109 path
= os
.path
.expanduser("~") + os
.sep
+ '.rainbow_config.json'
110 data
= load_config(path
)
112 if key
in data
and key
in c
:
116 data
[key
] = c
[key
] = get_default_config(key
)
120 raise Exception('No such config key.')
122 with
open(path
, 'w') as out
:
123 json
.dump(data
, out
, indent
=4)
124 os
.system('chmod 777 ' + path
)
131 rainbow_config
= os
.path
.expanduser("~") + os
.sep
+ '.rainbow_config.json'
133 data
= load_config(rainbow_config
)
137 print('It seems that ~/.rainbow_config.json has wrong format :(')
144 # Load the initial config
145 config
= os
.path
.dirname(
146 __file__
) + '/colorset/config'
148 data
= load_config(config
)
154 rainbow_config
= os
.path
.expanduser("~") + os
.sep
+ '.rainbow_config.json'
156 data
= load_config(rainbow_config
)
162 theme_file
= os
.path
.dirname(
163 __file__
) + '/colorset/' + c
['THEME'] + '.json'
165 data
= load_config(theme_file
)