forked from StarryPy/StarryPy-Python2-Deprecated
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathconfig.py
150 lines (138 loc) · 5.14 KB
/
config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import io
import json
import logging
import inspect
import sys
import os
from utility_functions import (
recursive_dictionary_update,
path,
Singleton
)
class ConfigurationManager(object):
__metaclass__ = Singleton
logger = logging.getLogger('starrypy.config.ConfigurationManager')
log_format = logging.Formatter(
'%(asctime)s - %(levelname)s - %(name)s # %(message)s'
)
logfile_handle = logging.FileHandler('config.log')
logfile_handle.setLevel(9)
logger.addHandler(logfile_handle)
logfile_handle.setFormatter(log_format)
def __init__(self):
default_config_path = path.preauthChild(
os.path.join('config', 'config.json.default')
)
self.config_path = path.preauthChild(
os.path.join('config', 'config.json')
)
if default_config_path.exists():
try:
with default_config_path.open() as default_config:
default = json.load(default_config)
except ValueError as e:
print 'Error: %s' % e
self.logger.critical(
'The configuration defaults file (config.json.default) '
'contains invalid JSON. Please run it against a JSON '
'linter, such as http://jsonlint.com. Shutting down.'
)
sys.exit()
else:
self.logger.critical(
'The configuration defaults file (config.json.default)'
' doesn\'t exist! Shutting down.'
)
sys.exit()
if self.config_path.exists():
try:
with self.config_path.open() as c:
config = json.load(c)
self.config = recursive_dictionary_update(default, config)
except ValueError as e:
print 'Error: %s' % e
self.logger.critical(
'The configuration file (config.json) contains invalid '
'JSON. Please run it against a JSON linter, such as '
'http://jsonlint.com. Shutting down.'
)
sys.exit()
else:
self.logger.warning(
'The configuration file (config.json)'
' doesn\'t exist! Creating one from defaults.'
)
try:
with self.config_path.open('w') as f:
json.dump(
default,
f,
indent=4,
separators=(',', ': '),
sort_keys=True,
ensure_ascii=False
)
except IOError:
self.logger.critical(
'Couldn\'t write a default configuration file. '
'Please check that StarryPy has write access in the '
'config/ directory.'
)
self.logger.critical('Exiting...')
sys.exit()
self.logger.warning(
'StarryPy will now exit. Please examine config.json '
'and adjust the variables appropriately.'
)
sys.exit()
self.logger.debug('Created configuration manager.')
self.save()
def save(self):
try:
with io.open(self.config_path.path, 'w') as config:
self.logger.debug('Writing configuration file.')
config.write(
json.dumps(
self.config,
indent=4,
separators=(',', ': '),
sort_keys=True,
ensure_ascii=False
)
)
except Exception as e:
self.logger.critical(
'Tried to save the configuration file, failed.\n%s', str(e)
)
raise
def __getattr__(self, item):
if item in ['config', 'config_path']:
return super(ConfigurationManager, self).__getattribute__(item)
elif item == 'plugin_config':
caller = inspect.stack()[1][0].f_locals['self'].__class__.name
if caller in self.config['plugin_config']:
return self.config['plugin_config'][caller]
else:
return {}
else:
if item in self.config:
return self.config[item]
else:
self.logger.error(
'Couldn\'t find configuration option %s in '
'configuration file.', item
)
raise AttributeError
def __setattr__(self, key, value):
if key == 'config':
super(ConfigurationManager, self).__setattr__(key, value)
self.save()
elif key == 'config_path':
super(ConfigurationManager, self).__setattr__(key, value)
elif key == 'plugin_config':
caller = inspect.stack()[1][0].f_locals['self'].__class__.name
self.config['plugin_config'][caller] = value
self.save()
else:
self.config[key] = value
self.save()