c2json.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. from qmk.errors import CppError
  11. @cli.argument('--no-cpp', arg_only=True, action='store_false', help='Do not use \'cpp\' on keymap.c')
  12. @cli.argument('-o', '--output', arg_only=True, type=qmk.path.normpath, help='File to write to')
  13. @cli.argument('-q', '--quiet', arg_only=True, action='store_true', help="Quiet mode, only output error messages")
  14. @cli.argument('-kb', '--keyboard', arg_only=True, type=keyboard_folder, completer=keyboard_completer, required=True, help='The keyboard\'s name')
  15. @cli.argument('-km', '--keymap', arg_only=True, required=True, help='The keymap\'s name')
  16. @cli.argument('filename', arg_only=True, completer=FilesCompleter('.c'), help='keymap.c file')
  17. @cli.subcommand('Creates a keymap.json from a keymap.c file.')
  18. def c2json(cli):
  19. """Generate a keymap.json from a keymap.c file.
  20. 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.
  21. """
  22. if cli.args.filename != '-':
  23. cli.args.filename = qmk.path.normpath(cli.args.filename)
  24. # Error checking
  25. if not cli.args.filename.exists():
  26. cli.log.error('C file does not exist!')
  27. cli.print_usage()
  28. return False
  29. # Environment processing
  30. if cli.args.output == ('-'):
  31. cli.args.output = None
  32. # Parse the keymap.c
  33. try:
  34. keymap_json = qmk.keymap.c2json(cli.args.keyboard, cli.args.keymap, cli.args.filename, use_cpp=cli.args.no_cpp)
  35. except CppError as e:
  36. if cli.config.general.verbose:
  37. cli.log.debug('The C pre-processor ran into a fatal error: %s', e)
  38. cli.log.error('Something went wrong. Try to use --no-cpp.\nUse the CLI in verbose mode to find out more.')
  39. return False
  40. # Generate the keymap.json
  41. try:
  42. keymap_json = qmk.keymap.generate_json(keymap_json['keymap'], keymap_json['keyboard'], keymap_json['layout'], keymap_json['layers'])
  43. except KeyError:
  44. cli.log.error('Something went wrong. Try to use --no-cpp.')
  45. return False
  46. if cli.args.output:
  47. cli.args.output.parent.mkdir(parents=True, exist_ok=True)
  48. if cli.args.output.exists():
  49. cli.args.output.replace(cli.args.output.parent / (cli.args.output.name + '.bak'))
  50. cli.args.output.write_text(json.dumps(keymap_json, cls=InfoJSONEncoder))
  51. if not cli.args.quiet:
  52. cli.log.info('Wrote keymap to %s.', cli.args.output)
  53. else:
  54. print(json.dumps(keymap_json))