commands.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. """Helper functions for commands.
  2. """
  3. import json
  4. import os
  5. import platform
  6. import subprocess
  7. import shlex
  8. import qmk.keymap
  9. def create_make_command(keyboard, keymap, target=None):
  10. """Create a make compile command
  11. Args:
  12. keyboard
  13. The path of the keyboard, for example 'plank'
  14. keymap
  15. The name of the keymap, for example 'algernon'
  16. target
  17. Usually a bootloader.
  18. Returns:
  19. A command that can be run to make the specified keyboard and keymap
  20. """
  21. make_args = [keyboard, keymap]
  22. make_cmd = 'make'
  23. platform_id = platform.platform().lower()
  24. if 'freebsd' in platform_id:
  25. make_cmd = 'gmake'
  26. if target:
  27. make_args.append(target)
  28. return [make_cmd, ':'.join(make_args)]
  29. def compile_configurator_json(user_keymap, bootloader=None):
  30. """Convert a configurator export JSON file into a C file
  31. Args:
  32. configurator_filename
  33. The configurator JSON export file
  34. bootloader
  35. A bootloader to flash
  36. Returns:
  37. A command to run to compile and flash the C file.
  38. """
  39. # Write the keymap C file
  40. qmk.keymap.write(user_keymap['keyboard'], user_keymap['keymap'], user_keymap['layout'], user_keymap['layers'])
  41. # Return a command that can be run to make the keymap and flash if given
  42. if bootloader is None:
  43. return create_make_command(user_keymap['keyboard'], user_keymap['keymap'])
  44. return create_make_command(user_keymap['keyboard'], user_keymap['keymap'], bootloader)
  45. def parse_configurator_json(configurator_file):
  46. """Open and parse a configurator json export
  47. """
  48. user_keymap = json.load(configurator_file)
  49. return user_keymap
  50. def run(command, *args, **kwargs):
  51. """Run a command with subprocess.run
  52. """
  53. platform_id = platform.platform().lower()
  54. if isinstance(command, str):
  55. raise TypeError('`command` must be a non-text sequence such as list or tuple.')
  56. if 'windows' in platform_id:
  57. safecmd = map(shlex.quote, command)
  58. safecmd = ' '.join(safecmd)
  59. command = [os.environ['SHELL'], '-c', safecmd]
  60. return subprocess.run(command, *args, **kwargs)