commands.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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 pathlib import Path
  10. from time import strftime
  11. from milc import cli
  12. import qmk.keymap
  13. from qmk.constants import KEYBOARD_OUTPUT_PREFIX
  14. from qmk.json_schema import json_load
  15. time_fmt = '%Y-%m-%d-%H:%M:%S'
  16. def _find_make():
  17. """Returns the correct make command for this environment.
  18. """
  19. make_cmd = os.environ.get('MAKE')
  20. if not make_cmd:
  21. make_cmd = 'gmake' if shutil.which('gmake') else 'make'
  22. return make_cmd
  23. def create_make_command(keyboard, keymap, target=None, parallel=1, **env_vars):
  24. """Create a make compile command
  25. Args:
  26. keyboard
  27. The path of the keyboard, for example 'plank'
  28. keymap
  29. The name of the keymap, for example 'algernon'
  30. target
  31. Usually a bootloader.
  32. parallel
  33. The number of make jobs to run in parallel
  34. **env_vars
  35. Environment variables to be passed to make.
  36. Returns:
  37. A command that can be run to make the specified keyboard and keymap
  38. """
  39. env = []
  40. make_args = [keyboard, keymap]
  41. make_cmd = _find_make()
  42. if target:
  43. make_args.append(target)
  44. for key, value in env_vars.items():
  45. env.append(f'{key}={value}')
  46. return [make_cmd, '-j', str(parallel), *env, ':'.join(make_args)]
  47. def get_git_version(repo_dir='.', check_dir='.'):
  48. """Returns the current git version for a repo, or the current time.
  49. """
  50. git_describe_cmd = ['git', 'describe', '--abbrev=6', '--dirty', '--always', '--tags']
  51. if Path(check_dir).exists():
  52. git_describe = cli.run(git_describe_cmd, cwd=repo_dir)
  53. if git_describe.returncode == 0:
  54. return git_describe.stdout.strip()
  55. else:
  56. cli.log.warn(f'"{" ".join(git_describe_cmd)}" returned error code {git_describe.returncode}')
  57. print(git_describe.stderr)
  58. return strftime(time_fmt)
  59. return strftime(time_fmt)
  60. def write_version_h(git_version, build_date, chibios_version, chibios_contrib_version):
  61. """Generate and write quantum/version.h
  62. """
  63. version_h = [
  64. f'#define QMK_VERSION "{git_version}"',
  65. f'#define QMK_BUILDDATE "{build_date}"',
  66. f'#define CHIBIOS_VERSION "{chibios_version}"',
  67. f'#define CHIBIOS_CONTRIB_VERSION "{chibios_contrib_version}"',
  68. ]
  69. version_h_file = Path('quantum/version.h')
  70. version_h_file.write_text('\n'.join(version_h))
  71. def compile_configurator_json(user_keymap, bootloader=None, parallel=1, **env_vars):
  72. """Convert a configurator export JSON file into a C file and then compile it.
  73. Args:
  74. user_keymap
  75. A deserialized keymap export
  76. bootloader
  77. A bootloader to flash
  78. parallel
  79. The number of make jobs to run in parallel
  80. Returns:
  81. A command to run to compile and flash the C file.
  82. """
  83. # Write the keymap.c file
  84. keyboard_filesafe = user_keymap['keyboard'].replace('/', '_')
  85. target = f'{keyboard_filesafe}_{user_keymap["keymap"]}'
  86. keyboard_output = Path(f'{KEYBOARD_OUTPUT_PREFIX}{keyboard_filesafe}')
  87. keymap_output = Path(f'{keyboard_output}_{user_keymap["keymap"]}')
  88. c_text = qmk.keymap.generate_c(user_keymap['keyboard'], user_keymap['layout'], user_keymap['layers'])
  89. keymap_dir = keymap_output / 'src'
  90. keymap_c = keymap_dir / 'keymap.c'
  91. keymap_dir.mkdir(exist_ok=True, parents=True)
  92. keymap_c.write_text(c_text)
  93. # Write the version.h file
  94. git_version = get_git_version()
  95. build_date = strftime('%Y-%m-%d-%H:%M:%S')
  96. chibios_version = get_git_version("lib/chibios", "lib/chibios/os")
  97. chibios_contrib_version = get_git_version("lib/chibios-contrib", "lib/chibios-contrib/os")
  98. write_version_h(git_version, build_date, chibios_version, chibios_contrib_version)
  99. # Return a command that can be run to make the keymap and flash if given
  100. verbose = 'true' if cli.config.general.verbose else 'false'
  101. color = 'true' if cli.config.general.color else 'false'
  102. make_command = [_find_make()]
  103. if not cli.config.general.verbose:
  104. make_command.append('-s')
  105. make_command.extend([
  106. '-j',
  107. str(parallel),
  108. '-r',
  109. '-R',
  110. '-f',
  111. 'build_keyboard.mk',
  112. ])
  113. if bootloader:
  114. make_command.append(bootloader)
  115. for key, value in env_vars.items():
  116. make_command.append(f'{key}={value}')
  117. make_command.extend([
  118. f'GIT_VERSION={git_version}',
  119. f'BUILD_DATE={build_date}',
  120. f'CHIBIOS_VERSION={chibios_version}',
  121. f'CHIBIOS_CONTRIB_VERSION={chibios_contrib_version}',
  122. f'KEYBOARD={user_keymap["keyboard"]}',
  123. f'KEYMAP={user_keymap["keymap"]}',
  124. f'KEYBOARD_FILESAFE={keyboard_filesafe}',
  125. f'TARGET={target}',
  126. f'KEYBOARD_OUTPUT={keyboard_output}',
  127. f'KEYMAP_OUTPUT={keymap_output}',
  128. f'MAIN_KEYMAP_PATH_1={keymap_output}',
  129. f'MAIN_KEYMAP_PATH_2={keymap_output}',
  130. f'MAIN_KEYMAP_PATH_3={keymap_output}',
  131. f'MAIN_KEYMAP_PATH_4={keymap_output}',
  132. f'MAIN_KEYMAP_PATH_5={keymap_output}',
  133. f'KEYMAP_C={keymap_c}',
  134. f'KEYMAP_PATH={keymap_dir}',
  135. f'VERBOSE={verbose}',
  136. f'COLOR={color}',
  137. 'SILENT=false',
  138. f'QMK_BIN={"bin/qmk" if "DEPRECATED_BIN_QMK" in os.environ else "qmk"}',
  139. ])
  140. return make_command
  141. def parse_configurator_json(configurator_file):
  142. """Open and parse a configurator json export
  143. """
  144. # FIXME(skullydazed/anyone): Add validation here
  145. user_keymap = json.load(configurator_file)
  146. orig_keyboard = user_keymap['keyboard']
  147. aliases = json_load(Path('data/mappings/keyboard_aliases.json'))
  148. if orig_keyboard in aliases:
  149. if 'target' in aliases[orig_keyboard]:
  150. user_keymap['keyboard'] = aliases[orig_keyboard]['target']
  151. if 'layouts' in aliases[orig_keyboard] and user_keymap['layout'] in aliases[orig_keyboard]['layouts']:
  152. user_keymap['layout'] = aliases[orig_keyboard]['layouts'][user_keymap['layout']]
  153. return user_keymap
  154. def run(command, *args, **kwargs):
  155. """Run a command with subprocess.run
  156. """
  157. platform_id = platform.platform().lower()
  158. if isinstance(command, str):
  159. raise TypeError('`command` must be a non-text sequence such as list or tuple.')
  160. if 'windows' in platform_id:
  161. safecmd = map(str, command)
  162. safecmd = map(shlex.quote, safecmd)
  163. safecmd = ' '.join(safecmd)
  164. command = [os.environ['SHELL'], '-c', safecmd]
  165. return subprocess.run(command, *args, **kwargs)