commands.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. if target:
  23. make_args.append(target)
  24. return ['make', ':'.join(make_args)]
  25. def compile_configurator_json(user_keymap, bootloader=None):
  26. """Convert a configurator export JSON file into a C file
  27. Args:
  28. configurator_filename
  29. The configurator JSON export file
  30. bootloader
  31. A bootloader to flash
  32. Returns:
  33. A command to run to compile and flash the C file.
  34. """
  35. # Write the keymap C file
  36. qmk.keymap.write(user_keymap['keyboard'], user_keymap['keymap'], user_keymap['layout'], user_keymap['layers'])
  37. # Return a command that can be run to make the keymap and flash if given
  38. if bootloader is None:
  39. return create_make_command(user_keymap['keyboard'], user_keymap['keymap'])
  40. return create_make_command(user_keymap['keyboard'], user_keymap['keymap'], bootloader)
  41. def parse_configurator_json(configurator_file):
  42. """Open and parse a configurator json export
  43. """
  44. user_keymap = json.load(configurator_file)
  45. return user_keymap
  46. def run(command, *args, **kwargs):
  47. """Run a command with subprocess.run
  48. """
  49. platform_id = platform.platform().lower()
  50. if isinstance(command, str):
  51. raise TypeError('`command` must be a non-text sequence such as list or tuple.')
  52. if 'windows' in platform_id:
  53. safecmd = map(shlex.quote, command)
  54. safecmd = ' '.join(safecmd)
  55. command = [os.environ['SHELL'], '-c', safecmd]
  56. return subprocess.run(command, *args, **kwargs)