commands.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. """Helper functions for commands.
  2. """
  3. import json
  4. import os
  5. import sys
  6. import shutil
  7. from pathlib import Path
  8. from subprocess import DEVNULL
  9. from time import strftime
  10. from milc import cli
  11. import qmk.keymap
  12. from qmk.constants import QMK_FIRMWARE, KEYBOARD_OUTPUT_PREFIX
  13. from qmk.json_schema import json_load
  14. time_fmt = '%Y-%m-%d-%H:%M:%S'
  15. def _find_make():
  16. """Returns the correct make command for this environment.
  17. """
  18. make_cmd = os.environ.get('MAKE')
  19. if not make_cmd:
  20. make_cmd = 'gmake' if shutil.which('gmake') else 'make'
  21. return make_cmd
  22. def create_make_target(target, parallel=1, **env_vars):
  23. """Create a make command
  24. Args:
  25. target
  26. Usually a make rule, such as 'clean' or 'all'.
  27. parallel
  28. The number of make jobs to run in parallel
  29. **env_vars
  30. Environment variables to be passed to make.
  31. Returns:
  32. A command that can be run to make the specified keyboard and keymap
  33. """
  34. env = []
  35. make_cmd = _find_make()
  36. for key, value in env_vars.items():
  37. env.append(f'{key}={value}')
  38. return [make_cmd, '-j', str(parallel), *env, target]
  39. def create_make_command(keyboard, keymap, target=None, parallel=1, **env_vars):
  40. """Create a make compile command
  41. Args:
  42. keyboard
  43. The path of the keyboard, for example 'plank'
  44. keymap
  45. The name of the keymap, for example 'algernon'
  46. target
  47. Usually a bootloader.
  48. parallel
  49. The number of make jobs to run in parallel
  50. **env_vars
  51. Environment variables to be passed to make.
  52. Returns:
  53. A command that can be run to make the specified keyboard and keymap
  54. """
  55. make_args = [keyboard, keymap]
  56. if target:
  57. make_args.append(target)
  58. return create_make_target(':'.join(make_args), parallel, **env_vars)
  59. def get_git_version(current_time=None, repo_dir='.', check_dir='.'):
  60. """Returns the current git version for a repo, or the current time.
  61. """
  62. git_describe_cmd = ['git', 'describe', '--abbrev=6', '--dirty', '--always', '--tags']
  63. if current_time is None:
  64. current_time = strftime(time_fmt)
  65. if repo_dir != '.':
  66. repo_dir = Path('lib') / repo_dir
  67. if check_dir != '.':
  68. check_dir = repo_dir / check_dir
  69. if Path(check_dir).exists():
  70. git_describe = cli.run(git_describe_cmd, stdin=DEVNULL, cwd=repo_dir)
  71. if git_describe.returncode == 0:
  72. return git_describe.stdout.strip()
  73. else:
  74. cli.log.warn(f'"{" ".join(git_describe_cmd)}" returned error code {git_describe.returncode}')
  75. print(git_describe.stderr)
  76. return current_time
  77. return current_time
  78. def create_version_h(skip_git=False, skip_all=False):
  79. """Generate version.h contents
  80. """
  81. if skip_all:
  82. current_time = "1970-01-01-00:00:00"
  83. else:
  84. current_time = None
  85. if skip_git:
  86. git_version = "NA"
  87. chibios_version = "NA"
  88. chibios_contrib_version = "NA"
  89. else:
  90. git_version = get_git_version(current_time)
  91. chibios_version = get_git_version(current_time, "chibios", "os")
  92. chibios_contrib_version = get_git_version(current_time, "chibios-contrib", "os")
  93. version_h_lines = f"""/* This file was automatically generated. Do not edit or copy.
  94. */
  95. #pragma once
  96. #define QMK_VERSION "{git_version}"
  97. #define QMK_BUILDDATE "{current_time}"
  98. #define CHIBIOS_VERSION "{chibios_version}"
  99. #define CHIBIOS_CONTRIB_VERSION "{chibios_contrib_version}"
  100. """
  101. return version_h_lines
  102. def compile_configurator_json(user_keymap, bootloader=None, parallel=1, **env_vars):
  103. """Convert a configurator export JSON file into a C file and then compile it.
  104. Args:
  105. user_keymap
  106. A deserialized keymap export
  107. bootloader
  108. A bootloader to flash
  109. parallel
  110. The number of make jobs to run in parallel
  111. Returns:
  112. A command to run to compile and flash the C file.
  113. """
  114. # Write the keymap.c file
  115. keyboard_filesafe = user_keymap['keyboard'].replace('/', '_')
  116. target = f'{keyboard_filesafe}_{user_keymap["keymap"]}'
  117. keyboard_output = Path(f'{KEYBOARD_OUTPUT_PREFIX}{keyboard_filesafe}')
  118. keymap_output = Path(f'{keyboard_output}_{user_keymap["keymap"]}')
  119. c_text = qmk.keymap.generate_c(user_keymap['keyboard'], user_keymap['layout'], user_keymap['layers'])
  120. keymap_dir = keymap_output / 'src'
  121. keymap_c = keymap_dir / 'keymap.c'
  122. keymap_dir.mkdir(exist_ok=True, parents=True)
  123. keymap_c.write_text(c_text)
  124. version_h = Path('quantum/version.h')
  125. version_h.write_text(create_version_h())
  126. # Return a command that can be run to make the keymap and flash if given
  127. verbose = 'true' if cli.config.general.verbose else 'false'
  128. color = 'true' if cli.config.general.color else 'false'
  129. make_command = [_find_make()]
  130. if not cli.config.general.verbose:
  131. make_command.append('-s')
  132. make_command.extend([
  133. '-j',
  134. str(parallel),
  135. '-r',
  136. '-R',
  137. '-f',
  138. 'build_keyboard.mk',
  139. ])
  140. if bootloader:
  141. make_command.append(bootloader)
  142. for key, value in env_vars.items():
  143. make_command.append(f'{key}={value}')
  144. make_command.extend([
  145. f'KEYBOARD={user_keymap["keyboard"]}',
  146. f'KEYMAP={user_keymap["keymap"]}',
  147. f'KEYBOARD_FILESAFE={keyboard_filesafe}',
  148. f'TARGET={target}',
  149. f'KEYBOARD_OUTPUT={keyboard_output}',
  150. f'KEYMAP_OUTPUT={keymap_output}',
  151. f'MAIN_KEYMAP_PATH_1={keymap_output}',
  152. f'MAIN_KEYMAP_PATH_2={keymap_output}',
  153. f'MAIN_KEYMAP_PATH_3={keymap_output}',
  154. f'MAIN_KEYMAP_PATH_4={keymap_output}',
  155. f'MAIN_KEYMAP_PATH_5={keymap_output}',
  156. f'KEYMAP_C={keymap_c}',
  157. f'KEYMAP_PATH={keymap_dir}',
  158. f'VERBOSE={verbose}',
  159. f'COLOR={color}',
  160. 'SILENT=false',
  161. f'QMK_BIN={"bin/qmk" if "DEPRECATED_BIN_QMK" in os.environ else "qmk"}',
  162. ])
  163. return make_command
  164. def parse_configurator_json(configurator_file):
  165. """Open and parse a configurator json export
  166. """
  167. # FIXME(skullydazed/anyone): Add validation here
  168. user_keymap = json.load(configurator_file)
  169. orig_keyboard = user_keymap['keyboard']
  170. aliases = json_load(Path('data/mappings/keyboard_aliases.json'))
  171. if orig_keyboard in aliases:
  172. if 'target' in aliases[orig_keyboard]:
  173. user_keymap['keyboard'] = aliases[orig_keyboard]['target']
  174. if 'layouts' in aliases[orig_keyboard] and user_keymap['layout'] in aliases[orig_keyboard]['layouts']:
  175. user_keymap['layout'] = aliases[orig_keyboard]['layouts'][user_keymap['layout']]
  176. return user_keymap
  177. def git_get_username():
  178. """Retrieves user's username from Git config, if set.
  179. """
  180. git_username = cli.run(['git', 'config', '--get', 'user.name'])
  181. if git_username.returncode == 0 and git_username.stdout:
  182. return git_username.stdout.strip()
  183. def git_check_repo():
  184. """Checks that the .git directory exists inside QMK_HOME.
  185. This is a decent enough indicator that the qmk_firmware directory is a
  186. proper Git repository, rather than a .zip download from GitHub.
  187. """
  188. dot_git_dir = QMK_FIRMWARE / '.git'
  189. return dot_git_dir.is_dir()
  190. def git_get_branch():
  191. """Returns the current branch for a repo, or None.
  192. """
  193. git_branch = cli.run(['git', 'branch', '--show-current'])
  194. if not git_branch.returncode != 0 or not git_branch.stdout:
  195. # Workaround for Git pre-2.22
  196. git_branch = cli.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
  197. if git_branch.returncode == 0:
  198. return git_branch.stdout.strip()
  199. def git_is_dirty():
  200. """Returns 1 if repo is dirty, or 0 if clean
  201. """
  202. git_diff_staged_cmd = ['git', 'diff', '--quiet']
  203. git_diff_unstaged_cmd = [*git_diff_staged_cmd, '--cached']
  204. unstaged = cli.run(git_diff_staged_cmd)
  205. staged = cli.run(git_diff_unstaged_cmd)
  206. return unstaged.returncode != 0 or staged.returncode != 0
  207. def git_get_remotes():
  208. """Returns the current remotes for a repo.
  209. """
  210. remotes = {}
  211. git_remote_show_cmd = ['git', 'remote', 'show']
  212. git_remote_get_cmd = ['git', 'remote', 'get-url']
  213. git_remote_show = cli.run(git_remote_show_cmd)
  214. if git_remote_show.returncode == 0:
  215. for name in git_remote_show.stdout.splitlines():
  216. git_remote_name = cli.run([*git_remote_get_cmd, name])
  217. remotes[name.strip()] = {"url": git_remote_name.stdout.strip()}
  218. return remotes
  219. def git_check_deviation(active_branch):
  220. """Return True if branch has custom commits
  221. """
  222. cli.run(['git', 'fetch', 'upstream', active_branch])
  223. deviations = cli.run(['git', '--no-pager', 'log', f'upstream/{active_branch}...{active_branch}'])
  224. return bool(deviations.returncode)
  225. def in_virtualenv():
  226. """Check if running inside a virtualenv.
  227. Based on https://stackoverflow.com/a/1883251
  228. """
  229. active_prefix = getattr(sys, "base_prefix", None) or getattr(sys, "real_prefix", None) or sys.prefix
  230. return active_prefix != sys.prefix