keycodes.py 1.4 KB

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