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