Passed
Push — master ( 0fd795...73442f )
by Emmanuel
14:19
created

configreader.Config._parse()   A

Complexity

Conditions 2

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 9
nop 1
dl 0
loc 13
ccs 9
cts 9
cp 1
crap 2
rs 9.95
c 0
b 0
f 0
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:
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable key does not seem to be defined.
Loading history...
59 1
                error = 'Missing' if error is False else str(error)
0 ignored issues
show
introduced by
The variable error does not seem to be defined for all execution paths.
Loading history...
60
                self.errors[key] = error
61