json.py 3.0 KB

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