keyboard stuff
1"""Convert raw KLE to JSON
2"""
3import json
4import os
5from pathlib import Path
6
7from argcomplete.completers import FilesCompleter
8from milc import cli
9from kle2xy import KLE2xy
10
11from qmk.converter import kle2qmk
12from qmk.json_encoders import InfoJSONEncoder
13
14
15@cli.argument('filename', completer=FilesCompleter('.json'), help='The KLE raw txt to convert')
16@cli.argument('-f', '--force', action='store_true', help='Flag to overwrite current info.json')
17@cli.subcommand('Convert a KLE layout to a Configurator JSON', hidden=False if cli.config.user.developer else True)
18def kle2json(cli):
19 """Convert a KLE layout to QMK's layout format.
20 """ # If filename is a path
21 if cli.args.filename.startswith("/") or cli.args.filename.startswith("./"):
22 file_path = Path(cli.args.filename)
23 # Otherwise assume it is a file name
24 else:
25 file_path = Path(os.environ['ORIG_CWD'], cli.args.filename)
26 # Check for valid file_path for more graceful failure
27 if not file_path.exists():
28 cli.log.error('File {fg_cyan}%s{style_reset_all} was not found.', file_path)
29 return False
30 out_path = file_path.parent
31 raw_code = file_path.read_text(encoding='utf-8')
32 # Check if info.json exists, allow overwrite with force
33 if Path(out_path, "info.json").exists() and not cli.args.force:
34 cli.log.error('File {fg_cyan}%s/info.json{style_reset_all} already exists, use -f or --force to overwrite.', out_path)
35 return False
36 try:
37 # Convert KLE raw to x/y coordinates (using kle2xy package from skullydazed)
38 kle = KLE2xy(raw_code)
39 except Exception as e:
40 cli.log.error('Could not parse KLE raw data: %s', raw_code)
41 cli.log.exception(e)
42 return False
43 keyboard = {
44 'keyboard_name': kle.name,
45 'url': '',
46 'maintainer': 'qmk',
47 'layouts': {
48 'LAYOUT': {
49 'layout': kle2qmk(kle)
50 }
51 },
52 }
53
54 # Write our info.json
55 keyboard = json.dumps(keyboard, indent=4, separators=(', ', ': '), sort_keys=False, cls=InfoJSONEncoder)
56 info_json_file = out_path / 'info.json'
57
58 info_json_file.write_text(keyboard)
59 cli.log.info('Wrote out {fg_cyan}%s/info.json', out_path)