json_schema.py 2.4 KB

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