logo

qmk_firmware

custom branch of QMK firmware git clone https://anongit.hacktivis.me/git/qmk_firmware.git

json.py (4348B)


  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, validate
  9. from qmk.json_encoders import InfoJSONEncoder, KeymapJSONEncoder, UserspaceJSONEncoder, CommunityModuleJSONEncoder
  10. from qmk.path import normpath
  11. def _detect_json_format(file, json_data):
  12. """Detect the format of a json file.
  13. """
  14. json_encoder = None
  15. try:
  16. validate(json_data, 'qmk.user_repo.v1_1')
  17. json_encoder = UserspaceJSONEncoder
  18. except ValidationError:
  19. pass
  20. if json_encoder is None:
  21. try:
  22. validate(json_data, 'qmk.user_repo.v1')
  23. json_encoder = UserspaceJSONEncoder
  24. except ValidationError:
  25. pass
  26. if json_encoder is None:
  27. try:
  28. validate(json_data, 'qmk.community_module.v1')
  29. json_encoder = CommunityModuleJSONEncoder
  30. except ValidationError:
  31. pass
  32. if json_encoder is None:
  33. try:
  34. validate(json_data, 'qmk.keyboard.v1')
  35. json_encoder = InfoJSONEncoder
  36. except ValidationError as e:
  37. cli.log.warning('File %s did not validate as a keyboard info.json or userspace qmk.json:\n\t%s', file, e)
  38. cli.log.info('Treating %s as a keymap file.', file)
  39. json_encoder = KeymapJSONEncoder
  40. return json_encoder
  41. def _get_json_encoder(file, json_data):
  42. """Get the json encoder for a file.
  43. """
  44. json_encoder = None
  45. if cli.args.format == 'auto':
  46. json_encoder = _detect_json_format(file, json_data)
  47. elif cli.args.format == 'keyboard':
  48. json_encoder = InfoJSONEncoder
  49. elif cli.args.format == 'keymap':
  50. json_encoder = KeymapJSONEncoder
  51. elif cli.args.format == 'userspace':
  52. json_encoder = UserspaceJSONEncoder
  53. elif cli.args.format == 'community_module':
  54. json_encoder = CommunityModuleJSONEncoder
  55. else:
  56. # This should be impossible
  57. cli.log.error('Unknown format: %s', cli.args.format)
  58. return json_encoder
  59. @cli.argument('json_file', arg_only=True, type=normpath, help='JSON file to format')
  60. @cli.argument('-f', '--format', choices=['auto', 'keyboard', 'keymap', 'userspace', 'community_module'], default='auto', arg_only=True, help='JSON formatter to use (Default: autodetect)')
  61. @cli.argument('-i', '--inplace', action='store_true', arg_only=True, help='If set, will operate in-place on the input file')
  62. @cli.argument('-p', '--print', action='store_true', arg_only=True, help='If set, will print the formatted json to stdout ')
  63. @cli.subcommand('Generate an info.json file for a keyboard.', hidden=False if cli.config.user.developer else True)
  64. def format_json(cli):
  65. """Format a json file.
  66. """
  67. json_data = json_load(cli.args.json_file)
  68. json_encoder = _get_json_encoder(cli.args.json_file, json_data)
  69. if json_encoder is None:
  70. return False
  71. if json_encoder == KeymapJSONEncoder and 'layout' in json_data:
  72. # Attempt to format the keycodes.
  73. layout = json_data['layout']
  74. info_data = info_json(json_data['keyboard'])
  75. if layout in info_data.get('layout_aliases', {}):
  76. layout = json_data['layout'] = info_data['layout_aliases'][layout]
  77. if layout in info_data.get('layouts'):
  78. for layer_num, layer in enumerate(json_data['layers']):
  79. current_layer = []
  80. last_row = 0
  81. for keymap_key, info_key in zip(layer, info_data['layouts'][layout]['layout']):
  82. if last_row != info_key['y']:
  83. current_layer.append('JSON_NEWLINE')
  84. last_row = info_key['y']
  85. current_layer.append(keymap_key)
  86. json_data['layers'][layer_num] = current_layer
  87. output = json.dumps(json_data, cls=json_encoder, sort_keys=True)
  88. if cli.args.inplace:
  89. with open(cli.args.json_file, 'w+', encoding='utf-8', newline='\n') as outfile:
  90. outfile.write(output + '\n')
  91. # Display the results if print was set
  92. # We don't operate in-place by default, so also display to stdout
  93. # if in-place is not set.
  94. if cli.args.print or not cli.args.inplace:
  95. print(output)