json.py 3.9 KB

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