Skip to content
validate.py 2.04 KiB
Newer Older
canterburym's avatar
canterburym committed
import sys
from jsonschema import validate, RefResolver, Draft202012Validator
import json
from pathlib import Path
import logging
import argparse


def handle_uri(u):
    print(u)

def load_json(path : str):
    with open(path) as f:
        return json.load(f)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()

    parser.add_argument('-s','--schemadir', action="append", help="Directory containing supporting schema files to use for validation")
    parser.add_argument('-v', '--verbose', action="count", help="Verbose logging (can be specified multiple times)")
    parser.add_argument('-i', '--input', type=argparse.FileType('r'), default=sys.stdin, help="Path to input file (if absent, stdin is used)")
canterburym's avatar
canterburym committed
    parser.add_argument('schema', help="Primary schema to validate against")    

    args = parser.parse_args()

    match args.verbose:
        case v if v and v >= 2:
            logging.basicConfig(level=logging.DEBUG)
        case 1:
            logging.basicConfig(level=logging.INFO)
        case _:
            logging.basicConfig(level=logging.WARNING)

    logging.debug(f"Arguments: {args}")

    instance_doc = json.loads(args.input.read())
    args.input.close()
canterburym's avatar
canterburym committed
    main_schema = load_json(args.schema)    
    schema_dict = { main_schema['$id'] : main_schema }

    if args.schemadir:
        schema_paths = []    
        for d in args.schemadir:
            schema_paths += [f for f in Path(d).rglob("*.schema.json")]
        logging.info(f"Schema files loaded: {schema_paths}")

        schemas_json = [json.load(p.open()) for p in schema_paths]
        schema_dict = schema_dict | { s['$id'] : s for s in schemas_json }

    logging.info(f"Schema IDs loaded: {[k for k in schema_dict.keys()]}")

    logging.debug (f"Instance doc: {instance_doc}")
    logging.debug (f"Main schema: {main_schema}")

    resolver = RefResolver(None, 
                           referrer=None, 
                           store=schema_dict)
    
    v = Draft202012Validator(main_schema, resolver=resolver)

    v.validate(instance_doc)

    logging.info("Done")