Passed
Push — master ( c492a3...708e45 )
by Emmanuel
94:29
created

stakkr.configreader.Config.display_errors()   A

Complexity

Conditions 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 7
nop 1
dl 0
loc 9
ccs 7
cts 7
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
# coding: utf-8
2 1
"""Simple Config Reader."""
3
4 1
from os import path
5 1
from sys import stderr
6 1
import anyconfig
7 1
from jsonschema.exceptions import _Error
8 1
from stakkr.file_utils import get_file, find_project_dir
9 1
from yaml import FullLoader
10
11
12 1
class Config:
13
    """
14
    Parser of Stakkr.
15
16
    Set default values and validate stakkr.yml with specs
17
    """
18
19 1
    def __init__(self, config_file: str):
20
        """
21
        Build list of files to validate a config, set default values
22
        Then the given config file
23
        """
24 1
        self.config_file, self.project_dir = get_config_and_project_dir(config_file)
25 1
        self._build_config_files_list()
26 1
        self._build_config_schemas_list()
27 1
        self.error = ''
28
29 1
    def display_errors(self):
30
        """Display errors in STDERR."""
31 1
        from click import style
32
33 1
        msg = 'Failed validating config ('
34 1
        msg += ', '.join(self.config_files)
35 1
        msg += '):\n    - {}\n'.format(self.error)
36 1
        msg += '\nMake sure you have the right services.\n'
37 1
        stderr.write(style(msg, fg='red'))
38
39 1
    def read(self):
40
        """
41
        Parse the configs and validate it.
42
43
        It could be either local or from a local services
44
        (first local then packages by alphabetical order).
45
        """
46 1
        schema = anyconfig.load(self.spec_files, Loader=FullLoader)
47 1
        config = anyconfig.load(self.config_files, Loader=FullLoader)
48
49
        # Make sure the compiled configuration is valid
50 1
        try:
51 1
            anyconfig.validate(config, schema, safe=False)
52 1
        except _Error as error:
53 1
            error_path = ' -> '.join(map(str, error.path))
54 1
            self.error = '{} ({})'.format(error.message, error_path)
55 1
            return False
56
57 1
        config['project_dir'] = path.realpath(path.dirname(self.config_file))
58 1
        if config['project_name'] == '':
59 1
            config['project_name'] = path.basename(config['project_dir'])
60
61 1
        return config
62
63 1
    def _build_config_files_list(self):
64 1
        self.config_files = [
65
            # Stakkr default config
66
            get_file('static', 'config_default.yml'),
67
            '{}/services/*/config_default.yml'.format(self.project_dir)]
68
        # Stakkr main config file finally with user's values
69 1
        self.config_files += [self.config_file]
70
71 1
    def _build_config_schemas_list(self):
72 1
        self.spec_files = [
73
            # Stakkr config validation
74
            get_file('static', 'config_schema.yml'),
75
            '{}/services/*/config_schema.yml'.format(self.project_dir)]
76
77
78 1
def get_config_and_project_dir(config_file: str):
79
    """Guess config file name and project dir"""
80 1
    if config_file is not None:
81 1
        config_file = path.abspath(config_file)
82 1
        project_dir = path.dirname(config_file)
83
    else:
84 1
        project_dir = find_project_dir()
85
        config_file = '{}/stakkr.yml'.format(project_dir)
86
87
    return config_file, project_dir
88