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.

59 lines
2.4 KiB

  1. """Generate a keymap.json from a keymap.c file.
  2. """
  3. import json
  4. from argcomplete.completers import FilesCompleter
  5. from milc import cli
  6. import qmk.keymap
  7. import qmk.path
  8. from qmk.json_encoders import InfoJSONEncoder
  9. from qmk.keyboard import keyboard_completer, keyboard_folder
  10. @cli.argument('--no-cpp', arg_only=True, action='store_false', help='Do not use \'cpp\' on keymap.c')
  11. @cli.argument('-o', '--output', arg_only=True, type=qmk.path.normpath, help='File to write to')
  12. @cli.argument('-q', '--quiet', arg_only=True, action='store_true', help="Quiet mode, only output error messages")
  13. @cli.argument('-kb', '--keyboard', arg_only=True, type=keyboard_folder, completer=keyboard_completer, required=True, help='The keyboard\'s name')
  14. @cli.argument('-km', '--keymap', arg_only=True, required=True, help='The keymap\'s name')
  15. @cli.argument('filename', arg_only=True, completer=FilesCompleter('.c'), help='keymap.c file')
  16. @cli.subcommand('Creates a keymap.json from a keymap.c file.')
  17. def c2json(cli):
  18. """Generate a keymap.json from a keymap.c file.
  19. This command uses the `qmk.keymap` module to generate a keymap.json from a keymap.c file. The generated keymap is written to stdout, or to a file if -o is provided.
  20. """
  21. if cli.args.filename != '-':
  22. cli.args.filename = qmk.path.normpath(cli.args.filename)
  23. # Error checking
  24. if not cli.args.filename.exists():
  25. cli.log.error('C file does not exist!')
  26. cli.print_usage()
  27. return False
  28. # Environment processing
  29. if cli.args.output == ('-'):
  30. cli.args.output = None
  31. # Parse the keymap.c
  32. keymap_json = qmk.keymap.c2json(cli.args.keyboard, cli.args.keymap, cli.args.filename, use_cpp=cli.args.no_cpp)
  33. # Generate the keymap.json
  34. try:
  35. keymap_json = qmk.keymap.generate_json(keymap_json['keymap'], keymap_json['keyboard'], keymap_json['layout'], keymap_json['layers'])
  36. except KeyError:
  37. cli.log.error('Something went wrong. Try to use --no-cpp.')
  38. return False
  39. if cli.args.output:
  40. cli.args.output.parent.mkdir(parents=True, exist_ok=True)
  41. if cli.args.output.exists():
  42. cli.args.output.replace(cli.args.output.parent / (cli.args.output.name + '.bak'))
  43. cli.args.output.write_text(json.dumps(keymap_json, cls=InfoJSONEncoder))
  44. if not cli.args.quiet:
  45. cli.log.info('Wrote keymap to %s.', cli.args.output)
  46. else:
  47. print(json.dumps(keymap_json))