json_schema.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. """Functions that help us generate and use info.json files.
  2. """
  3. import json
  4. from collections.abc import Mapping
  5. from functools import lru_cache
  6. from pathlib import Path
  7. import hjson
  8. import jsonschema
  9. from milc import cli
  10. def json_load(json_file):
  11. """Load a json file from disk.
  12. Note: file must be a Path object.
  13. """
  14. try:
  15. return hjson.load(json_file.open(encoding='utf-8'))
  16. except (json.decoder.JSONDecodeError, hjson.HjsonDecodeError) as e:
  17. cli.log.error('Invalid JSON encountered attempting to load {fg_cyan}%s{fg_reset}:\n\t{fg_red}%s', json_file, e)
  18. exit(1)
  19. except Exception as e:
  20. cli.log.error('Unknown error attempting to load {fg_cyan}%s{fg_reset}:\n\t{fg_red}%s', json_file, e)
  21. exit(1)
  22. @lru_cache(maxsize=0)
  23. def load_jsonschema(schema_name):
  24. """Read a jsonschema file from disk.
  25. """
  26. if Path(schema_name).exists():
  27. return json_load(schema_name)
  28. schema_path = Path(f'data/schemas/{schema_name}.jsonschema')
  29. if not schema_path.exists():
  30. schema_path = Path('data/schemas/false.jsonschema')
  31. return json_load(schema_path)
  32. @lru_cache(maxsize=0)
  33. def compile_schema_store():
  34. """Compile all our schemas into a schema store.
  35. """
  36. schema_store = {}
  37. for schema_file in Path('data/schemas').glob('*.jsonschema'):
  38. schema_data = load_jsonschema(schema_file)
  39. if not isinstance(schema_data, dict):
  40. cli.log.debug('Skipping schema file %s', schema_file)
  41. continue
  42. schema_store[schema_data['$id']] = schema_data
  43. return schema_store
  44. @lru_cache(maxsize=0)
  45. def create_validator(schema):
  46. """Creates a validator for the given schema id.
  47. """
  48. schema_store = compile_schema_store()
  49. resolver = jsonschema.RefResolver.from_schema(schema_store['qmk.keyboard.v1'], store=schema_store)
  50. return jsonschema.Draft7Validator(schema_store[schema], resolver=resolver).validate
  51. def validate(data, schema):
  52. """Validates data against a schema.
  53. """
  54. validator = create_validator(schema)
  55. return validator(data)
  56. def deep_update(origdict, newdict):
  57. """Update a dictionary in place, recursing to do a depth-first deep copy.
  58. """
  59. for key, value in newdict.items():
  60. if isinstance(value, Mapping):
  61. origdict[key] = deep_update(origdict.get(key, {}), value)
  62. else:
  63. origdict[key] = value
  64. return origdict