Debian Codegraph @

scripts/schema/validator.py

raw symbols SCIP
1 #!/bin/python3
2
3 # A simple script to validate that a schema is valid for a file.
4
5 import argparse
6 import tomllib
7 import jsonschema_rs
8 import re
9 import traceback
10
11
12 def main():
13 parser = argparse.ArgumentParser(
14 description="Validates a file against a JSON schema"
15 )
16 parser.add_argument(
17 "-f", "--file", type=str, required=True, help="The file to check."
18 )
19 parser.add_argument(
20 "-s", "--schema", type=str, required=True, help="The schema to use."
21 )
22 parser.add_argument(
23 "--uncomment",
24 required=False,
25 action="store_true",
26 help="Uncomment the settings inside the file.",
27 )
28 parser.add_argument(
29 "--should_fail",
30 required=False,
31 action="store_true",
32 help="Whether the checked file should fail.",
33 )
34 args = parser.parse_args()
35
36 file = args.file
37 schema = args.schema
38 should_fail = args.should_fail
39 uncomment = args.uncomment
40
41 with open(file, "rb") as f, open(schema) as s:
42 try:
43 validator = jsonschema_rs.validator_for(s.read())
44 except:
45 print("Couldn't create validator.")
46 exit()
47
48 if uncomment:
49 read_file = f.read().decode("utf-8")
50 read_file = re.sub(r"^#([a-zA-Z\[])", r"\1", read_file, flags=re.MULTILINE)
51 read_file = re.sub(
52 r"^#(\s\s+)([a-zA-Z\[])", r"\2", read_file, flags=re.MULTILINE
53 )
54 print(f"uncommented file: \n{read_file}\n=====\n")
55
56 toml_str = tomllib.loads(read_file)
57 else:
58 toml_str = tomllib.load(f)
59
60 try:
61 validator.validate(toml_str)
62 if should_fail:
63 print("Fail! Should have errored.")
64 exit(1)
65 else:
66 print("All good!")
67 except jsonschema_rs.ValidationError as err:
68 print(f"Caught error: `{err}`")
69 print(traceback.format_exc())
70
71 if should_fail:
72 print("Caught error, good!")
73 else:
74 print("Fail!")
75 exit(1)
76
77
78 if __name__ == "__main__":
79 main()