|
| 1 | +import json |
| 2 | +import re |
| 3 | +import os |
| 4 | + |
| 5 | +pattern = r"v?\d+\.\d+\.\d+" |
| 6 | + |
| 7 | + |
| 8 | +def check(obj, version, parents=""): |
| 9 | + """ |
| 10 | + This functions recursively parses all fields in the schema looking for |
| 11 | + version names that would not be the same as the one mentionned |
| 12 | + in the 'version' field |
| 13 | + """ |
| 14 | + errors = [] |
| 15 | + # if field is a string, we check for a potential version |
| 16 | + if isinstance(obj, str): |
| 17 | + tmp = re.search(pattern, obj) |
| 18 | + if tmp and tmp[0] != version: |
| 19 | + errors += [(parents, tmp[0])] |
| 20 | + # if field is a list, we check every item |
| 21 | + elif isinstance(obj, list): |
| 22 | + for idx, k in enumerate(obj): |
| 23 | + errors += check(k, version, parents=parents + f"[{str(idx)}]") |
| 24 | + # if field is a dict, we check every value |
| 25 | + elif isinstance(obj, dict): |
| 26 | + for k in obj: |
| 27 | + # not checking the fields |
| 28 | + if k != "fields": |
| 29 | + errors += check( |
| 30 | + obj[k], |
| 31 | + version, |
| 32 | + parents=parents + "." + k if parents else k |
| 33 | + ) |
| 34 | + return errors |
| 35 | + |
| 36 | + |
| 37 | +to_check = [] |
| 38 | + |
| 39 | +if "schema.json" in os.listdir(): |
| 40 | + to_check.append("schema.json") |
| 41 | + |
| 42 | +elif "datapackage.json" in os.listdir(): |
| 43 | + with open("datapackage.json", "r") as f: |
| 44 | + datapackage = json.load(f) |
| 45 | + for r in datapackage["resources"]: |
| 46 | + to_check.append(r["schema"]) |
| 47 | + |
| 48 | +else: |
| 49 | + raise Exception("No required file found") |
| 50 | + |
| 51 | +for schema_path in to_check: |
| 52 | + with open(schema_path, "r") as f: |
| 53 | + schema = json.load(f) |
| 54 | + version = schema["version"] |
| 55 | + |
| 56 | + errors = check(schema, version) |
| 57 | + if errors: |
| 58 | + message = ( |
| 59 | + f"Versions are mismatched within the schema '{schema['name']}', " |
| 60 | + f"expected version '{version}' but:" |
| 61 | + ) |
| 62 | + for e in errors: |
| 63 | + message += f"\n- {e[0]} has version '{e[1]}'" |
| 64 | + raise Exception(message) |
0 commit comments