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
)
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 data
.pop('QUOTE_FORMAT', None)
53 data
.pop('NOTIFY_FORMAT', None)
59 def get_default_config(key
):
61 Get default value of a config key
64 path
= os
.path
.dirname(__file__
) + '/colorset/config'
65 data
= load_config(path
)
68 raise Exception('This config key does not exist in default.')
73 Get current value of a config key
78 def set_config(key
, value
):
80 Set a config key with specific value
85 elif value
.lower() == 'true':
87 elif value
.lower() == 'false':
89 # Update global config
91 # Load current user config
92 path
= os
.path
.expanduser("~") + os
.sep
+ '.rainbow_config.json'
95 data
= load_config(path
)
100 fixup(data
, key
, value
)
104 with
open(path
, 'w') as out
:
105 json
.dump(data
, out
, indent
=4)
106 os
.system('chmod 777 ' + path
)
109 def delete_config(key
):
113 path
= os
.path
.expanduser("~") + os
.sep
+ '.rainbow_config.json'
115 data
= load_config(path
)
117 raise Exception('Config file is messed up.')
119 if key
in data
and key
in c
:
123 data
[key
] = c
[key
] = get_default_config(key
)
127 raise Exception('No such config key.')
129 with
open(path
, 'w') as out
:
130 json
.dump(data
, out
, indent
=4)
131 os
.system('chmod 777 ' + path
)
139 rainbow_config
= os
.path
.expanduser("~") + \
140 os
.sep
+ '.rainbow_config.json'
141 data
= load_config(rainbow_config
)
145 raise Exception('Can not reload config file with wrong format.')
152 # Load the initial config
153 config
= os
.path
.dirname(__file__
) + \
156 data
= load_config(config
)
162 rainbow_config
= os
.path
.expanduser("~") + os
.sep
+ '.rainbow_config.json'
164 data
= load_config(rainbow_config
)
167 except (IOError, ValueError) as e
:
168 c
['USER_JSON_ERROR'] = str(e
)
170 theme_file
= os
.path
.dirname(__file__
) + \
171 '/colorset/' + c
['THEME'] + '.json'
173 data
= load_config(theme_file
)