veirify_config.py
1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import pykwalify.core
import yaml,sys,logging
from pykwalify.errors import PyKwalifyException,SchemaError
def check_and_return_config(yaml_file:str,schema_file:str)->dict:
"""
Check if yaml_file is valid for the schema_file and return an dictionnary of the config file
Args:
yaml_file (str): Path to the config_file to be validated
schema_file (str): Path to the schema file
Returns:
dict: Dictionnary of the config file (with values)
"""
# disable pykwalify error to clean the output
logging.disable(logging.ERROR)
try:
c = pykwalify.core.Core(source_file=yaml_file, schema_files=[schema_file])
return c.validate(raise_exception=True)
except SchemaError:
for error in c.errors:
print("Error :",str(error).split(". Path")[0])
print("Path to error :",error.path)
# error.value is the value causing the error
# print(error.value)
# error.scalar_type is the type (defined by schema) that the value should match
# print(error.scalar_type)
# error.path is the path to the error in the yaml file
# print(error.path)
def read_and_check_config_file(yaml_file:str):
"""
Read the schema key of the config file to retrieve schema name and proceed to the checking of that config file
Call check_and_return_config function and print its return.
Args:
yaml_file (str): path to the config file
"""
with open(yaml_file, 'r') as stream:
try:
config_file = yaml.safe_load(stream)
result = check_and_return_config(yaml_file,config_file["schema"])
if result is None:
print("Error when reading and validating config file, please check the errors right above")
else:
print(result)
except yaml.YAMLError as exc:
print(exc)
read_and_check_config_file(sys.argv[1])