1 | 1 | import anyconfig |
|
2 | 1 | import os |
|
3 | |||
4 | 1 | from . import utils |
|
5 | |||
6 | |||
7 | 1 | class Reader(): |
|
8 | """Config Reader. Reads, validate and add default values to YAML""" |
||
9 | |||
10 | 1 | def parse(self, config_file=None, specs=None, default_file=None): |
|
11 | """Read a config_file, check the validity with a JSON Schema as specs |
||
12 | and get default values from default_file if asked. |
||
13 | |||
14 | All parameters are optionnal. |
||
15 | |||
16 | If there is no config_file defined, read the venv base |
||
17 | dir and try to get config/app.yml. |
||
18 | |||
19 | If no specs, don't validate anything. |
||
20 | |||
21 | If no default_file, don't merge with default values.""" |
||
22 | |||
23 | 1 | self._config_exists(config_file) |
|
24 | 1 | self._specs_exists(specs) |
|
25 | |||
26 | 1 | self.loaded_config = anyconfig.load(self.config_file, ac_parser='yaml') |
|
27 | |||
28 | 1 | if default_file is not None: |
|
29 | 1 | self._merge_default(default_file) |
|
30 | |||
31 | 1 | if self.specs is None: |
|
32 | 1 | return self.loaded_config |
|
33 | |||
34 | 1 | self._validate() |
|
35 | |||
36 | 1 | return self.loaded_config |
|
37 | |||
38 | |||
39 | 1 | def _validate(self) -> None: |
|
40 | 1 | (rc, err) = anyconfig.validate(self.loaded_config, anyconfig.load(self.specs, ac_parser='yaml')) |
|
0 ignored issues
–
show
Unused Code
introduced
by
![]() |
|||
41 | |||
42 | 1 | if err != '': |
|
43 | 1 | raise ValueError('Your config is not valid: {}'.format(err)) |
|
44 | |||
45 | |||
46 | 1 | def _config_exists(self, config_file: str) -> str: |
|
47 | 1 | self.config_file = utils.get_venv_basedir() + '/config/app.yml' |
|
48 | 1 | if config_file is not None: |
|
49 | 1 | self.config_file = config_file |
|
50 | |||
51 | 1 | if not os.path.isfile(self.config_file): |
|
52 | 1 | raise IOError('Missing config file: "{}" does not exist'.format(self.config_file)) |
|
53 | |||
54 | |||
55 | 1 | def _merge_default(self, default_file: str) -> None: |
|
56 | 1 | if not os.path.isfile(default_file): |
|
57 | 1 | raise IOError("Your default ({}) does not exist".format(default_file)) |
|
58 | |||
59 | 1 | default_config = anyconfig.load(default_file) |
|
60 | 1 | anyconfig.merge(default_config, self.loaded_config) |
|
61 | |||
62 | 1 | self.loaded_config = default_config |
|
63 | |||
64 | |||
65 | 1 | def _specs_exists(self, specs: str) -> None: |
|
66 | 1 | self.specs = specs |
|
67 | 1 | if self.specs is None: |
|
68 | 1 | return |
|
69 | |||
70 | # self.specs = os.path.abspath(os.path.dirname(__file__) + '/static/configspec.ini') |
||
71 | 1 | if not os.path.isfile(self.specs): |
|
72 | raise IOError("Your specs ({}) does not exist".format(self.specs)) |
||
73 |