-
Notifications
You must be signed in to change notification settings - Fork 42
/
config.py
53 lines (40 loc) · 1.37 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
import os
import sys
from copy import deepcopy
import yaml
def load():
try:
with open('hamper.conf') as config_file:
config = yaml.load(config_file)
except IOError:
config = {}
config = replace_env_vars(config)
# Fill in data from the env:
for k, v in os.environ.items():
try:
config[k] = yaml.load(v)
except yaml.error.YAMLError:
config[k] = v
# Special case: database
if 'DATABASE_URL' in os.environ:
config['db'] = os.environ['DATABASE_URL']
for key in ['server', 'port', 'nickname', 'channels']:
if (key not in config) or (not config[key]):
print('You need to define {0} in the config file.'.format(key))
sys.exit()
return config
def replace_env_vars(conf):
"""Fill `conf` with environment variables, where appropriate.
Any value of the from $VAR will be replaced with the environment variable
VAR. If there are sub dictionaries, this function will recurse.
This will preserve the original dictionary, and return a copy.
"""
d = deepcopy(conf)
for key, value in d.items():
if type(value) == dict:
d[key] = replace_env_vars(value)
elif type(value) == str:
if value[0] == '$':
var_name = value[1:]
d[key] = os.environ[var_name]
return d