|
| 1 | +import json |
| 2 | +import logging |
| 3 | +from collections import defaultdict |
| 4 | +from copy import deepcopy |
| 5 | +from glob import glob |
| 6 | +from os.path import basename, join, realpath |
| 7 | +from pprint import pprint |
| 8 | +from schema import Schema |
| 9 | + |
| 10 | +import fire |
| 11 | + |
| 12 | + |
| 13 | +def read(folder, type): |
| 14 | + with open(f"{folder}{type[1:]}.json") as ifile: |
| 15 | + return json.load(ifile) |
| 16 | + |
| 17 | + |
| 18 | +def analy(root, folder="../docs/json"): |
| 19 | + schema = Schema() |
| 20 | + queue = [root] |
| 21 | + |
| 22 | + while queue: |
| 23 | + type = queue.pop() |
| 24 | + schema.add(type, read(folder, type)) |
| 25 | + |
| 26 | + for ref in schema.search("$ref", type): |
| 27 | + if schema.has(ref): |
| 28 | + continue |
| 29 | + |
| 30 | + assert isinstance(ref, str) |
| 31 | + assert ref.startswith("#/") |
| 32 | + queue.append(ref) |
| 33 | + |
| 34 | + return schema |
| 35 | + |
| 36 | + |
| 37 | +def annotate(ifilepath, opath=None, strict=False): |
| 38 | + schema = analy("#/animation") |
| 39 | + |
| 40 | + with open(ifilepath) as ifile: |
| 41 | + icontent = json.load(ifile) |
| 42 | + |
| 43 | + resolved_schema = schema.validate(icontent, "#/animation", strict=strict) |
| 44 | + opath = opath or ifilepath.rstrip(".json") + ".schema.json" |
| 45 | + |
| 46 | + with open(opath, "w") as ofile: |
| 47 | + json.dump(resolved_schema, ofile, indent=2) |
| 48 | + |
| 49 | + icontent["$schema"] = "./" + basename(opath) |
| 50 | + |
| 51 | + with open(ifilepath, "w") as ofile: |
| 52 | + json.dump(icontent, ofile, indent=2) |
| 53 | + |
| 54 | + |
| 55 | +if __name__ == "__main__": |
| 56 | + fire.Fire(annotate) |
0 commit comments