1+ #!/usr/bin/env python
2+ import json
3+ import yaml
4+ import sys
5+
6+ from typing import Any
7+ from jsonschema import validate , ValidationError
8+
9+
10+ class ParseSchemaError (Exception ):
11+ pass
12+
13+
14+ class YamlValidationError (Exception ):
15+ pass
16+
17+
18+ class OpenFileError (Exception ):
19+ pass
20+
21+
22+ class NotEnoughArgsError (Exception ):
23+ pass
24+
25+
26+ class YamlValidator :
27+ """
28+ Yaml validator validates a given yaml file against
29+ a chosen template.
30+ """
31+ def __init__ (self , schema_path : str ) -> None :
32+ self .schema = self ._parse_json_file (schema_path )
33+
34+ def _open_file (self , path : str ) -> Any :
35+ try :
36+ return open (path )
37+ except OSError as exc :
38+ raise OpenFileError (f"::error:: failed to open file { path } : { exc } " )
39+
40+ def _parse_json_file (self , json_path : str ) -> dict [str , Any ]:
41+ return json .load (self ._open_file (json_path ))
42+
43+ def _get_yaml_file (self , yaml_path : str ):
44+ return yaml .load (self ._open_file (yaml_path ), Loader = yaml .SafeLoader )
45+
46+ def validate (self , path : str ) -> bool :
47+ try :
48+ _ = validate (instance = self ._get_yaml_file (path ), schema = self .schema )
49+ except ValidationError as exc :
50+ raise YamlValidationError (f"error:: validation failed: { str (exc .message )} " )
51+ return True
52+
53+
54+ def parse_arg (index : int ) -> str :
55+ try :
56+ return sys .argv [index ]
57+ except IndexError :
58+ raise NotEnoughArgsError (
59+ "Missing Args: Example usage -> validate-yaml.py <schema_path> <yaml_path>"
60+ )
61+
62+
63+ if __name__ == "__main__" :
64+ schema_path = parse_arg (1 )
65+ yaml_path = parse_arg (2 )
66+ validator = YamlValidator (schema_path = schema_path )
67+ validator .validate (yaml_path )
0 commit comments