c2json.py 2.2 KB

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