lib/validate-awesome-privacy.py
86 lines · 2624 bytes
1import json
2import os
3import sys
4import logging
5import yaml
6from termcolor import colored
7from jsonschema import Draft7Validator
8
9# Configure Logging
10LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()
11logging.basicConfig(level=LOG_LEVEL)
12logger = logging.getLogger(__name__)
13
14
15# Determine the project root based on the script's location
16project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17awesome_privacy_path = os.path.join(project_root, 'awesome-privacy.yml')
18schema_path = os.path.join(project_root, 'lib/schema.json')
19
20
21# Log method, accepts a message and optional log level
22# and prints the output to the terminal in right color
23def loggy(message: str, level: str = 'debug'):
24 if level == "info":
25 logger.info(colored(message, 'blue'))
26 elif level == "warning":
27 logger.warning(colored(message, 'yellow'))
28 elif level == "error":
29 logger.error(colored(message, 'red'))
30 elif level == "success":
31 logger.info(colored(message, 'green'))
32 elif level == "debug":
33 logger.debug(colored(message, 'grey'))
34
35
36# Loads a given YAML file and returns the data
37def load_yaml(yaml_path: str):
38 loggy(f"Loading YAML from {yaml_path}", "info")
39 try:
40 with open(yaml_path, 'r') as file:
41 return yaml.safe_load(file)
42 except yaml.YAMLError as e:
43 loggy(f"Failed to load YAML: {e}", "error")
44 sys.exit(1)
45
46
47# Loads a given JSON Schema file and returns the data
48def load_schema(schema_path: str):
49 loggy(f"Loading JSON Schema from {schema_path}", "info")
50 try:
51 with open(schema_path, 'r') as file:
52 return json.load(file)
53 except json.JSONDecodeError as e:
54 loggy(f"Failed to load JSON Schema: {e}", "error")
55 sys.exit(1)
56
57
58# Validates the given YAML data against the given JSON Schema
59def validate_yaml(data, schema):
60 loggy("Beginning validation", "info")
61 validator = Draft7Validator(schema)
62 errors = sorted(validator.iter_errors(data), key=lambda e: e.path)
63 if errors:
64 for error in errors:
65 error_location = "->".join(map(str, error.path))
66 loggy(f"Validation error: {error.message} (at {error_location})", "warning")
67 return False
68 return True
69
70
71# Main method
72def main():
73 loggy("Starting...", "info")
74 yaml_data = load_yaml(awesome_privacy_path)
75 schema = load_schema(schema_path)
76
77 if validate_yaml(yaml_data, schema):
78 loggy("Validation successful!", "success")
79 sys.exit(0)
80 else:
81 loggy("Validation failed.", "error")
82 sys.exit(1)
83
84
85if __name__ == "__main__":
86 main()