keycodes.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from pathlib import Path
  2. from qmk.json_schema import deep_update, json_load, validate
  3. CONSTANTS_PATH = Path('data/constants/keycodes/')
  4. def _validate(spec):
  5. # first throw it to the jsonschema
  6. validate(spec, 'qmk.keycodes.v1')
  7. # no duplicate keycodes
  8. keycodes = []
  9. for value in spec['keycodes'].values():
  10. keycodes.append(value['key'])
  11. keycodes.extend(value.get('aliases', []))
  12. duplicates = set([x for x in keycodes if keycodes.count(x) > 1])
  13. if duplicates:
  14. raise ValueError(f'Keycode spec contains duplicate keycodes! ({",".join(duplicates)})')
  15. def load_spec(version):
  16. """Build keycode data from the requested spec file
  17. """
  18. if version == 'latest':
  19. version = list_versions()[0]
  20. file = CONSTANTS_PATH / f'keycodes_{version}.hjson'
  21. if not file.exists():
  22. raise ValueError(f'Requested keycode spec ({version}) is invalid!')
  23. # Load base
  24. spec = json_load(file)
  25. # Merge in fragments
  26. fragments = CONSTANTS_PATH.glob(f'keycodes_{version}_*.hjson')
  27. for file in fragments:
  28. deep_update(spec, json_load(file))
  29. # Sort?
  30. spec['keycodes'] = dict(sorted(spec['keycodes'].items()))
  31. # Validate?
  32. _validate(spec)
  33. return spec
  34. def list_versions():
  35. """Return available versions - sorted newest first
  36. """
  37. ret = []
  38. for file in CONSTANTS_PATH.glob('keycodes_[0-9].[0-9].[0-9].hjson'):
  39. ret.append(file.stem.split('_')[1])
  40. ret.sort(reverse=True)
  41. return ret