json2c.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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', 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. cli.args.filename = qmk.path.normpath(cli.args.filename)
  16. # Error checking
  17. if not cli.args.filename.exists():
  18. cli.log.error('JSON file does not exist!')
  19. cli.print_usage()
  20. exit(1)
  21. if str(cli.args.filename) == '-':
  22. # TODO(skullydazed/anyone): Read file contents from STDIN
  23. cli.log.error('Reading from STDIN is not (yet) supported.')
  24. cli.print_usage()
  25. exit(1)
  26. # Environment processing
  27. if cli.args.output == ('-'):
  28. cli.args.output = None
  29. # Parse the configurator json
  30. with cli.args.filename.open('r') as fd:
  31. user_keymap = json.load(fd)
  32. # Generate the keymap
  33. keymap_c = qmk.keymap.generate(user_keymap['keyboard'], user_keymap['layout'], user_keymap['layers'])
  34. if cli.args.output:
  35. cli.args.output.parent.mkdir(parents=True, exist_ok=True)
  36. if cli.args.output.exists():
  37. cli.args.output.replace(cli.args.output.name + '.bak')
  38. cli.args.output.write_text(keymap_c)
  39. if not cli.args.quiet:
  40. cli.log.info('Wrote keymap to %s.', cli.args.output)
  41. else:
  42. print(keymap_c)