json2c.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """Generate a keymap.c from a configurator export.
  2. """
  3. import json
  4. from milc import cli
  5. import qmk.keymap
  6. import qmk.path
  7. @cli.argument('-o', '--output', arg_only=True, type=qmk.path.normpath, help='File to write to')
  8. @cli.argument('-q', '--quiet', arg_only=True, action='store_true', help="Quiet mode, only output error messages")
  9. @cli.argument('filename', type=qmk.path.FileType('r'), arg_only=True, help='Configurator JSON file')
  10. @cli.subcommand('Creates a keymap.c from a QMK Configurator export.')
  11. def json2c(cli):
  12. """Generate a keymap.c from a configurator export.
  13. 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.
  14. """
  15. try:
  16. # Parse the configurator from json file (or stdin)
  17. user_keymap = json.load(cli.args.filename)
  18. except json.decoder.JSONDecodeError as ex:
  19. cli.log.error('The JSON input does not appear to be valid.')
  20. cli.log.error(ex)
  21. return False
  22. # Environment processing
  23. if cli.args.output and cli.args.output.name == '-':
  24. cli.args.output = None
  25. # Generate the keymap
  26. keymap_c = qmk.keymap.generate_c(user_keymap['keyboard'], user_keymap['layout'], user_keymap['layers'])
  27. if cli.args.output:
  28. cli.args.output.parent.mkdir(parents=True, exist_ok=True)
  29. if cli.args.output.exists():
  30. cli.args.output.replace(cli.args.output.parent / (cli.args.output.name + '.bak'))
  31. cli.args.output.write_text(keymap_c)
  32. if not cli.args.quiet:
  33. cli.log.info('Wrote keymap to %s.', cli.args.output)
  34. else:
  35. print(keymap_c)