c2json.py 2.1 KB

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