aboutsummaryrefslogtreecommitdiff
path: root/utils/validate_schema.py
blob: 647cc310046b2878c71fac9c77851e2113435225 (plain)
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
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Validate all result files against a given JSON schema.

Author: Gertjan van den Burg

"""


import argparse
import json
import jsonschema
import os


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-s", "--schema-file", help="Schema file", default="./schema.json"
    )
    parser.add_argument("-r", "--result-dir", help="Directory with results")
    parser.add_argument(
        "-v", "--verbose", help="Enable verbose mode", action="store_true"
    )
    return parser.parse_args()


def load_schema(schema_file):
    with open(schema_file, "rb") as fp:
        schema = json.load(fp)
    return schema


def scantree(path):
    """Recursively yield DirEntry objects for given directory."""
    for entry in os.scandir(path):
        if entry.is_dir(follow_symlinks=False):
            yield from scantree(entry.path)
        else:
            yield entry


def validate_file(filename, schema):
    with open(filename, "rb") as fp:
        data = json.load(fp)
    jsonschema.validate(instance=data, schema=schema)


def main():
    args = parse_args()

    log = lambda *a, **kw: print(*a, **kw) if args.verbose else None

    schema = load_schema(args.schema_file)
    for entry in scantree(args.result_dir):
        log("Checking file: %s" % entry.path)
        validate_file(entry.path, schema)


if __name__ == "__main__":
    main()