tvalidate_config.py - pism - [fork] customized build of PISM, the parallel ice sheet model (tillflux branch) (HTM) git clone git://src.adamsgaard.dk/pism (DIR) Log (DIR) Files (DIR) Refs (DIR) LICENSE --- tvalidate_config.py (2695B) --- 1 #!/usr/bin/env python3 2 3 import json 4 import jsonschema 5 import copy 6 7 # Shortcuts to save some typing: 8 integer_t = {"type": "integer"} 9 number_t = {"type": "number"} 10 string_t = {"type": "string"} 11 flag_t = {"type": "flag"} 12 13 # A generic entry: 14 entry = { 15 "type": "object", 16 "properties": { 17 "doc": string_t, 18 "reference": string_t, 19 "comment": string_t 20 }, 21 "required": ["doc", "value", "type"], 22 "additionalProperties": False 23 } 24 25 26 def gen_type(keyword): 27 return {"type": "string", "pattern": "^%s$" % keyword} 28 29 30 # numerical configuration parameters 31 number = copy.deepcopy(entry) 32 number['properties']['value'] = number_t 33 number['properties']['units'] = string_t 34 number['properties']['type'] = gen_type("number") 35 number['required'].append('units') 36 37 # integer configuration parameters 38 integer = copy.deepcopy(number) 39 integer['properties']['value'] = integer_t 40 integer['properties']['type'] = gen_type("integer") 41 42 # strings 43 string = copy.deepcopy(entry) 44 string['properties']['value'] = string_t 45 string['properties']['type'] = gen_type("string") 46 47 # keywords ("choose one of...") 48 keyword = copy.deepcopy(string) 49 keyword['properties']['choices'] = { 50 "type": "array", 51 "minItems": 2, 52 "items": { 53 "type": "string" 54 } 55 } 56 57 # configuration flags 58 flag = copy.deepcopy(entry) 59 flag['properties']['type'] = gen_type("flag") 60 flag['properties']['value'] = flag_t 61 62 # assembled schema 63 config_schema = { 64 "$schema": "http://json-schema.org/draft-04/schema#", 65 "type": "object", 66 "definitions": { 67 "number": number, 68 "integer": integer, 69 "string": string, 70 "keyword": keyword, 71 "flag": flag, 72 }, 73 "properties": { 74 "doc": string_t, 75 "comment": string_t, 76 "reference": string_t, 77 }, 78 "required": ["doc"], 79 "additionalProperties": { 80 "anyOf": [ 81 {"$ref": "#"}, 82 {"$ref": "#/definitions/number"}, 83 {"$ref": "#/definitions/integer"}, 84 {"$ref": "#/definitions/string"}, 85 {"$ref": "#/definitions/keyword"}, 86 {"$ref": "#/definitions/flag"}, 87 ] 88 } 89 } 90 91 92 def reload_data(): 93 f = open("pism_config.json") 94 j = json.load(f) 95 f.close() 96 97 return j 98 99 100 j = reload_data() 101 102 103 def validate_recursively(data, path=[]): 104 try: 105 jsonschema.validate(data, config_schema) 106 except jsonschema.ValidationError as e: 107 if len(e.path) == 0: 108 print("Failed while validating %s" % json.dumps(e.instance)) 109 print("Message:", e.message) 110 print("Path:", ".".join(path)) 111 else: 112 validate_recursively(e.instance, path + list(e.path)) 113 114 115 validate_recursively(j)