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)
57 def get_default_config(key
):
59 Get default value of a config key
62 path
= os
.path
.dirname(__file__
) + '/colorset/config'
63 data
= load_config(path
)
66 raise Exception('This config key does not exist in default.')
71 Get current value of a config key
76 def set_config(key
, value
):
78 Set a config key with specific value
83 elif value
.lower() == 'true':
85 elif value
.lower() == 'false':
87 # Update global config
89 # Load current user config
90 path
= os
.path
.expanduser("~") + os
.sep
+ '.rainbow_config.json'
93 data
= load_config(path
)
98 fixup(data
, key
, value
)
102 with
open(path
, 'w') as out
:
103 json
.dump(data
, out
, indent
=4)
104 os
.system('chmod 777 ' + path
)
107 def delete_config(key
):
111 path
= os
.path
.expanduser("~") + os
.sep
+ '.rainbow_config.json'
113 data
= load_config(path
)
115 raise Exception('Config file is messed up.')
117 if key
in data
and key
in c
:
121 data
[key
] = c
[key
] = get_default_config(key
)
125 raise Exception('No such config key.')
127 with
open(path
, 'w') as out
:
128 json
.dump(data
, out
, indent
=4)
129 os
.system('chmod 777 ' + path
)
137 rainbow_config
= os
.path
.expanduser("~") + \
138 os
.sep
+ '.rainbow_config.json'
139 data
= load_config(rainbow_config
)
143 raise Exception('Can not reload config file with wrong format.')
150 # Load the initial config
151 config
= os
.path
.dirname(__file__
) + \
154 data
= load_config(config
)
160 rainbow_config
= os
.path
.expanduser("~") + os
.sep
+ '.rainbow_config.json'
162 data
= load_config(rainbow_config
)
165 except (IOError, ValueError) as e
:
166 c
['USER_JSON_ERROR'] = str(e
)
168 theme_file
= os
.path
.dirname(__file__
) + \
169 '/colorset/' + c
['THEME'] + '.json'
171 data
= load_config(theme_file
)