You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
2.2 KiB

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