|
1
|
|
|
# -*- coding: utf-8 -*- |
|
2
|
1 |
|
"""Simple Config Reader""" |
|
3
|
|
|
|
|
4
|
1 |
|
import os |
|
5
|
1 |
|
import sys |
|
6
|
1 |
|
from configobj import ConfigObj, flatten_errors |
|
7
|
1 |
|
from validate import Validator |
|
8
|
1 |
|
from stakkr import package_utils |
|
9
|
|
|
|
|
10
|
|
|
|
|
11
|
1 |
|
class Config(): |
|
12
|
|
|
"""Parser of Stakkr. Set default values and validate |
|
13
|
|
|
conf/compose.ini with conf/configspec.ini |
|
14
|
|
|
""" |
|
15
|
|
|
|
|
16
|
1 |
|
def __init__(self, config_file: str = None): |
|
17
|
|
|
"""If no config given, read the default one""" |
|
18
|
1 |
|
self.errors = dict() |
|
19
|
1 |
|
self.config_file = package_utils.get_venv_basedir() + '/conf/compose.ini' |
|
20
|
1 |
|
if config_file is not None: |
|
21
|
1 |
|
self.config_file = config_file |
|
22
|
|
|
|
|
23
|
|
|
|
|
24
|
1 |
|
def display_errors(self): |
|
25
|
|
|
"""Display errors in STDOUT""" |
|
26
|
1 |
|
from click import style |
|
27
|
|
|
|
|
28
|
1 |
|
print(style('Failed validating {}: '.format(self.config_file), fg='red'), file=sys.stderr) |
|
29
|
1 |
|
for key, error in self.errors.items(): |
|
30
|
1 |
|
print(' - "{}" : {}'.format(style(key, fg='yellow'), error), file=sys.stderr) |
|
31
|
|
|
|
|
32
|
|
|
|
|
33
|
1 |
|
def read(self): |
|
34
|
|
|
"""Read the default values and overriden ones""" |
|
35
|
1 |
|
if os.path.isfile(self.config_file) is False: |
|
36
|
1 |
|
raise IOError('Config file {} does not exist'.format(self.config_file)) |
|
37
|
|
|
|
|
38
|
1 |
|
return self._parse() |
|
39
|
|
|
|
|
40
|
|
|
|
|
41
|
1 |
|
def _parse(self): |
|
42
|
|
|
"""Parse the config from configspecs that is a file either local or from a package""" |
|
43
|
|
|
|
|
44
|
1 |
|
config_spec_file = package_utils.get_file('static', 'configspec.ini') |
|
45
|
1 |
|
config = ConfigObj(infile=self.config_file, configspec=config_spec_file) |
|
46
|
|
|
|
|
47
|
1 |
|
validator = Validator() |
|
48
|
1 |
|
validated = config.validate(validator, preserve_errors=True) |
|
49
|
1 |
|
if validated is not True: |
|
50
|
1 |
|
self._register_errors(config, validated) |
|
51
|
1 |
|
return False |
|
52
|
|
|
|
|
53
|
1 |
|
return config |
|
54
|
|
|
|
|
55
|
|
|
|
|
56
|
1 |
|
def _register_errors(self, config: dict, validated): |
|
57
|
1 |
|
for [section_list, key, error] in flatten_errors(config, validated): |
|
58
|
1 |
|
if key is not None: |
|
|
|
|
|
|
59
|
1 |
|
error = 'Missing' if error is False else str(error) |
|
|
|
|
|
|
60
|
|
|
self.errors[key] = error |
|
61
|
|
|
|