commands.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. """Helper functions for commands.
  2. """
  3. import json
  4. import os
  5. import platform
  6. import subprocess
  7. import shlex
  8. import shutil
  9. from milc import cli
  10. import qmk.keymap
  11. def create_make_command(keyboard, keymap, target=None):
  12. """Create a make compile command
  13. Args:
  14. keyboard
  15. The path of the keyboard, for example 'plank'
  16. keymap
  17. The name of the keymap, for example 'algernon'
  18. target
  19. Usually a bootloader.
  20. Returns:
  21. A command that can be run to make the specified keyboard and keymap
  22. """
  23. make_args = [keyboard, keymap]
  24. make_cmd = 'gmake' if shutil.which('gmake') else 'make'
  25. if target:
  26. make_args.append(target)
  27. return [make_cmd, ':'.join(make_args)]
  28. def compile_configurator_json(user_keymap, bootloader=None):
  29. """Convert a configurator export JSON file into a C file
  30. Args:
  31. configurator_filename
  32. The configurator JSON export file
  33. bootloader
  34. A bootloader to flash
  35. Returns:
  36. A command to run to compile and flash the C file.
  37. """
  38. # Write the keymap C file
  39. qmk.keymap.write(user_keymap['keyboard'], user_keymap['keymap'], user_keymap['layout'], user_keymap['layers'])
  40. # Return a command that can be run to make the keymap and flash if given
  41. if bootloader is None:
  42. return create_make_command(user_keymap['keyboard'], user_keymap['keymap'])
  43. return create_make_command(user_keymap['keyboard'], user_keymap['keymap'], bootloader)
  44. def parse_configurator_json(configurator_file):
  45. """Open and parse a configurator json export
  46. """
  47. # FIXME(skullydazed/anyone): Add validation here
  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. cli.log.debug('Running command: %s', command)
  61. return subprocess.run(command, *args, **kwargs)