json.py 3.7 KB

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