1
|
|
|
#!/usr/bin/env python |
2
|
|
|
# -*- coding: utf-8 -*- |
3
|
|
|
|
4
|
|
|
# Copyright (c) 2017 Adam.Dybbroe |
5
|
|
|
|
6
|
|
|
# Author(s): |
7
|
|
|
|
8
|
|
|
# Adam.Dybbroe <[email protected]> |
9
|
|
|
|
10
|
|
|
# This program is free software: you can redistribute it and/or modify |
11
|
|
|
# it under the terms of the GNU General Public License as published by |
12
|
|
|
# the Free Software Foundation, either version 3 of the License, or |
13
|
|
|
# (at your option) any later version. |
14
|
|
|
|
15
|
|
|
# This program is distributed in the hope that it will be useful, |
16
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
17
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
18
|
|
|
# GNU General Public License for more details. |
19
|
|
|
|
20
|
|
|
# You should have received a copy of the GNU General Public License |
21
|
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
22
|
|
|
|
23
|
|
|
"""Pyhspectral configuration directory and file handling |
24
|
|
|
""" |
25
|
|
|
|
26
|
|
|
import logging |
27
|
|
|
import os |
28
|
|
|
import yaml |
29
|
|
|
from collections import Mapping |
30
|
|
|
import pkg_resources |
31
|
|
|
|
32
|
|
|
|
33
|
|
|
LOG = logging.getLogger(__name__) |
34
|
|
|
|
35
|
|
|
BUILTIN_CONFIG_FILE = pkg_resources.resource_filename(__name__, |
36
|
|
|
os.path.join('etc', 'pyspectral.yaml')) |
37
|
|
|
|
38
|
|
|
CONFIG_FILE = os.environ.get('PSP_CONFIG_FILE') |
39
|
|
|
|
40
|
|
|
if CONFIG_FILE is not None and (not os.path.exists(CONFIG_FILE) or |
41
|
|
|
not os.path.isfile(CONFIG_FILE)): |
42
|
|
|
raise IOError(str(CONFIG_FILE) + " pointed to by the environment " + |
43
|
|
|
"variable PSP_CONFIG_FILE is not a file or does not exist!") |
44
|
|
|
|
45
|
|
|
|
46
|
|
|
def recursive_dict_update(d, u): |
47
|
|
|
"""Recursive dictionary update using |
48
|
|
|
|
49
|
|
|
Copied from: |
50
|
|
|
|
51
|
|
|
http://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth |
52
|
|
|
|
53
|
|
|
""" |
54
|
|
|
for k, v in u.items(): |
55
|
|
|
if isinstance(v, Mapping): |
56
|
|
|
r = recursive_dict_update(d.get(k, {}), v) |
57
|
|
|
d[k] = r |
58
|
|
|
else: |
59
|
|
|
d[k] = u[k] |
60
|
|
|
return d |
61
|
|
|
|
62
|
|
|
|
63
|
|
|
def get_config(): |
64
|
|
|
"""Get the configuration from file""" |
65
|
|
|
if CONFIG_FILE is not None: |
66
|
|
|
configfile = CONFIG_FILE |
67
|
|
|
else: |
68
|
|
|
configfile = BUILTIN_CONFIG_FILE |
69
|
|
|
|
70
|
|
|
config = {} |
71
|
|
|
with open(configfile, 'r') as fp_: |
72
|
|
|
config = recursive_dict_update(config, yaml.load(fp_)) |
73
|
|
|
|
74
|
|
|
return config |
75
|
|
|
|