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
18 Determine the user's config file location
20 if 'RAINBOW_CONFIG' in os
.environ
:
21 return os
.environ
['RAINBOW_CONFIG']
23 return os
.path
.expanduser("~") + os
.sep
+ '.rainbow_config.json'
25 def fixup(adict
, k
, v
):
27 Fix up a key in json format
29 for key
in adict
.keys():
32 elif isinstance(adict
[key
], dict):
33 fixup(adict
[key
], k
, v
)
36 def load_config(filepath
):
38 Load config from filepath
40 with
open(filepath
) as f
:
41 content
= ''.join(f
.readlines())
42 match
= comment_re
.search(content
)
44 content
= content
[:match
.start()] + content
[match
.end():]
45 match
= comment_re
.search(content
)
46 return json
.loads(content
, object_pairs_hook
=OrderedDict
)
54 path
= user_filepath()
55 data
= load_config(path
)
56 # Hard to set from prompt
57 data
.pop('ONLY_LIST', None)
58 data
.pop('IGNORE_LIST', None)
59 data
.pop('FORMAT', None)
60 data
.pop('QUOTE_FORMAT', None)
61 data
.pop('NOTIFY_FORMAT', None)
67 def get_default_config(key
):
69 Get default value of a config key
72 path
= os
.path
.dirname(__file__
) + '/colorset/config'
73 data
= load_config(path
)
76 raise Exception('This config key does not exist in default.')
81 Get current value of a config key
86 def set_config(key
, value
):
88 Set a config key with specific value
93 elif value
.lower() == 'true':
95 elif value
.lower() == 'false':
97 # Update global config
99 # Load current user config
100 path
= user_filepath()
103 data
= load_config(path
)
108 fixup(data
, key
, value
)
112 with
open(path
, 'w') as out
:
113 json
.dump(data
, out
, indent
=4)
114 os
.system('chmod 777 ' + path
)
117 def delete_config(key
):
121 path
= user_filepath()
123 data
= load_config(path
)
125 raise Exception('Config file is messed up.')
127 if key
in data
and key
in c
:
131 data
[key
] = c
[key
] = get_default_config(key
)
135 raise Exception('No such config key.')
137 with
open(path
, 'w') as out
:
138 json
.dump(data
, out
, indent
=4)
139 os
.system('chmod 777 ' + path
)
147 rainbow_config
= user_filepath()
148 data
= load_config(rainbow_config
)
152 raise Exception('Can not reload config file with wrong format.')
159 # Load the initial config
160 config
= os
.path
.dirname(__file__
) + \
163 data
= load_config(config
)
169 rainbow_config
= user_filepath()
171 data
= load_config(rainbow_config
)
174 except (IOError, ValueError) as e
:
175 c
['USER_JSON_ERROR'] = str(e
)
177 theme_file
= os
.path
.dirname(__file__
) + \
178 '/colorset/' + c
['THEME'] + '.json'
180 data
= load_config(theme_file
)