json2c.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. """Generate a keymap.c from a configurator export.
  2. """
  3. import json
  4. import sys
  5. from milc import cli
  6. import qmk.keymap
  7. import qmk.path
  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('filename', type=qmk.path.normpath, arg_only=True, help='Configurator JSON file')
  11. @cli.subcommand('Creates a keymap.c from a QMK Configurator export.')
  12. def json2c(cli):
  13. """Generate a keymap.c from a configurator export.
  14. This command uses the `qmk.keymap` module to generate a keymap.c from a configurator export. The generated keymap is written to stdout, or to a file if -o is provided.
  15. """
  16. try:
  17. # Parse the configurator from stdin
  18. if cli.args.filename and cli.args.filename.name == '-':
  19. user_keymap = json.load(sys.stdin)
  20. else:
  21. # Error checking
  22. if not cli.args.filename.exists():
  23. cli.log.error('JSON file does not exist!')
  24. return False
  25. # Parse the configurator json file
  26. else:
  27. user_keymap = json.loads(cli.args.filename.read_text())
  28. except json.decoder.JSONDecodeError as ex:
  29. cli.log.error('The JSON input does not appear to be valid.')
  30. cli.log.error(ex)
  31. return False
  32. # Environment processing
  33. if cli.args.output and cli.args.output.name == '-':
  34. cli.args.output = None
  35. # Generate the keymap
  36. keymap_c = qmk.keymap.generate_c(user_keymap['keyboard'], user_keymap['layout'], user_keymap['layers'])
  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(keymap_c)
  42. if not cli.args.quiet:
  43. cli.log.info('Wrote keymap to %s.', cli.args.output)
  44. else:
  45. print(keymap_c)