1*b31d048aSAmithash Prasad#!/usr/bin/env python3 2*b31d048aSAmithash Prasad# Copyright 2021-present Facebook. All Rights Reserved. 3*b31d048aSAmithash Prasadimport argparse 4*b31d048aSAmithash Prasadimport json 5*b31d048aSAmithash Prasadimport sys 6*b31d048aSAmithash Prasad 7*b31d048aSAmithash Prasadimport jsonschema.validators 8*b31d048aSAmithash Prasad 9*b31d048aSAmithash Prasad 10*b31d048aSAmithash Prasaddef validator(schema_path): 11*b31d048aSAmithash Prasad with open(schema_path) as f: 12*b31d048aSAmithash Prasad schema = json.load(f) 13*b31d048aSAmithash Prasad validator = jsonschema.Draft202012Validator(schema) 14*b31d048aSAmithash Prasad return validator 15*b31d048aSAmithash Prasad 16*b31d048aSAmithash Prasad 17*b31d048aSAmithash Prasaddef validate_json_conf(schema, js): 18*b31d048aSAmithash Prasad v = validator(schema) 19*b31d048aSAmithash Prasad try: 20*b31d048aSAmithash Prasad with open(js) as f: 21*b31d048aSAmithash Prasad data = json.load(f) 22*b31d048aSAmithash Prasad v.validate(data) 23*b31d048aSAmithash Prasad return True 24*b31d048aSAmithash Prasad except jsonschema.exceptions.ValidationError as e: 25*b31d048aSAmithash Prasad print("Validation failed", file=sys.stderr) 26*b31d048aSAmithash Prasad print(e, file=sys.stderr) 27*b31d048aSAmithash Prasad return False 28*b31d048aSAmithash Prasad 29*b31d048aSAmithash Prasad 30*b31d048aSAmithash Prasaddef main(): 31*b31d048aSAmithash Prasad parser = argparse.ArgumentParser( 32*b31d048aSAmithash Prasad description="JSON Schema Validator", 33*b31d048aSAmithash Prasad formatter_class=argparse.ArgumentDefaultsHelpFormatter, 34*b31d048aSAmithash Prasad ) 35*b31d048aSAmithash Prasad parser.add_argument( 36*b31d048aSAmithash Prasad "input", 37*b31d048aSAmithash Prasad nargs="+", 38*b31d048aSAmithash Prasad help="Input handler configuration", 39*b31d048aSAmithash Prasad ) 40*b31d048aSAmithash Prasad parser.add_argument( 41*b31d048aSAmithash Prasad "-s", 42*b31d048aSAmithash Prasad "--schema", 43*b31d048aSAmithash Prasad default=None, 44*b31d048aSAmithash Prasad help="Schema to validate against", 45*b31d048aSAmithash Prasad ) 46*b31d048aSAmithash Prasad args = parser.parse_args() 47*b31d048aSAmithash Prasad if args.schema is None: 48*b31d048aSAmithash Prasad print("FAILURE: Schema is required. See help") 49*b31d048aSAmithash Prasad sys.exit(1) 50*b31d048aSAmithash Prasad schema = args.schema 51*b31d048aSAmithash Prasad files = args.input 52*b31d048aSAmithash Prasad for f in files: 53*b31d048aSAmithash Prasad if validate_json_conf(schema, f): 54*b31d048aSAmithash Prasad print("SUCCESS: ", f) 55*b31d048aSAmithash Prasad else: 56*b31d048aSAmithash Prasad print("FAILURE: ", f, file=sys.stderr) 57*b31d048aSAmithash Prasad sys.exit(1) 58*b31d048aSAmithash Prasad 59*b31d048aSAmithash Prasad 60*b31d048aSAmithash Prasadif __name__ == "__main__": 61*b31d048aSAmithash Prasad main() 62