json.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """JSON Formatting Script
  2. Spits out a JSON file formatted with one of QMK's formatters.
  3. """
  4. import json
  5. from jsonschema import ValidationError
  6. from milc import cli
  7. from qmk.info import info_json
  8. from qmk.json_schema import json_load, keyboard_validate
  9. from qmk.json_encoders import InfoJSONEncoder, KeymapJSONEncoder
  10. from qmk.path import normpath
  11. @cli.argument('json_file', arg_only=True, type=normpath, help='JSON file to format')
  12. @cli.argument('-f', '--format', choices=['auto', 'keyboard', 'keymap'], default='auto', arg_only=True, help='JSON formatter to use (Default: autodetect)')
  13. @cli.subcommand('Generate an info.json file for a keyboard.', hidden=False if cli.config.user.developer else True)
  14. def format_json(cli):
  15. """Format a json file.
  16. """
  17. json_file = json_load(cli.args.json_file)
  18. if cli.args.format == 'auto':
  19. try:
  20. keyboard_validate(json_file)
  21. json_encoder = InfoJSONEncoder
  22. except ValidationError as e:
  23. cli.log.warning('File %s did not validate as a keyboard:\n\t%s', cli.args.json_file, e)
  24. cli.log.info('Treating %s as a keymap file.', cli.args.json_file)
  25. json_encoder = KeymapJSONEncoder
  26. elif cli.args.format == 'keyboard':
  27. json_encoder = InfoJSONEncoder
  28. elif cli.args.format == 'keymap':
  29. json_encoder = KeymapJSONEncoder
  30. else:
  31. # This should be impossible
  32. cli.log.error('Unknown format: %s', cli.args.format)
  33. return False
  34. if json_encoder == KeymapJSONEncoder and 'layout' in json_file:
  35. # Attempt to format the keycodes.
  36. layout = json_file['layout']
  37. info_data = info_json(json_file['keyboard'])
  38. if layout in info_data.get('layout_aliases', {}):
  39. layout = json_file['layout'] = info_data['layout_aliases'][layout]
  40. if layout in info_data.get('layouts'):
  41. for layer_num, layer in enumerate(json_file['layers']):
  42. current_layer = []
  43. last_row = 0
  44. for keymap_key, info_key in zip(layer, info_data['layouts'][layout]['layout']):
  45. if last_row != info_key['y']:
  46. current_layer.append('JSON_NEWLINE')
  47. last_row = info_key['y']
  48. current_layer.append(keymap_key)
  49. json_file['layers'][layer_num] = current_layer
  50. # Display the results
  51. print(json.dumps(json_file, cls=json_encoder))