[IDF] Add IDF schema validation based on version
[pharos.git] / config / utils / validate_schema.py
1 #!/usr/bin/python
2 ##############################################################################
3 # Copyright (c) 2018 Enea AB and others.
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9 """This module validates a PDF file against the schema."""
10 import argparse
11 import jsonschema
12 import yaml
13
14 PARSER = argparse.ArgumentParser()
15 PARSER.add_argument("--yaml", "-y", type=str, required=True)
16 PARSER.add_argument("--schema", "-s", type=str, required=True)
17 ARGS = PARSER.parse_args()
18
19 with open(ARGS.yaml) as _:
20     _DICT = yaml.safe_load(_)
21
22 with open(ARGS.schema) as _:
23     _SCHEMA = yaml.safe_load(_)
24
25 # Draft 4 (latest supported by py-jsonschema) does not support value-based
26 # decisions properly, see related github issue:
27 # https://github.com/json-schema-org/json-schema-spec/issues/64
28 # Workaround: build 'version_x.y: true' on the fly based on 'version: x.y'
29 def schema_version_workaround(node):
30     """Traverse nested dictionaries and handle 'version' key where found."""
31     if 'version' in node:
32         node['version_{0}'.format(node['version'])] = True
33     for item in node.items():
34         if type(item) is dict:
35             schema_version_workaround(item)
36 schema_version_workaround(_DICT)
37 if 'idf' in _DICT:
38   schema_version_workaround(_DICT['idf'])
39
40 _VALIDATOR = jsonschema.Draft4Validator(_SCHEMA)
41 for error in _VALIDATOR.iter_errors(_DICT):
42     raise RuntimeError(str(error))