You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

334 lines
9.5 KiB

  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, *get_make_parallel_args(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, 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 repo_dir != '.':
  64. repo_dir = Path('lib') / repo_dir
  65. if check_dir != '.':
  66. check_dir = repo_dir / check_dir
  67. if Path(check_dir).exists():
  68. git_describe = cli.run(git_describe_cmd, stdin=DEVNULL, cwd=repo_dir)
  69. if git_describe.returncode == 0:
  70. return git_describe.stdout.strip()
  71. else:
  72. cli.log.warn(f'"{" ".join(git_describe_cmd)}" returned error code {git_describe.returncode}')
  73. print(git_describe.stderr)
  74. return current_time
  75. return current_time
  76. def get_make_parallel_args(parallel=1):
  77. """Returns the arguments for running the specified number of parallel jobs.
  78. """
  79. parallel_args = []
  80. if int(parallel) <= 0:
  81. # 0 or -1 means -j without argument (unlimited jobs)
  82. parallel_args.append('--jobs')
  83. else:
  84. parallel_args.append('--jobs=' + str(parallel))
  85. if int(parallel) != 1:
  86. # If more than 1 job is used, synchronize parallel output by target
  87. parallel_args.append('--output-sync=target')
  88. return parallel_args
  89. def create_version_h(skip_git=False, skip_all=False):
  90. """Generate version.h contents
  91. """
  92. if skip_all:
  93. current_time = "1970-01-01-00:00:00"
  94. else:
  95. current_time = strftime(time_fmt)
  96. if skip_git:
  97. git_version = "NA"
  98. chibios_version = "NA"
  99. chibios_contrib_version = "NA"
  100. else:
  101. git_version = get_git_version(current_time)
  102. chibios_version = get_git_version(current_time, "chibios", "os")
  103. chibios_contrib_version = get_git_version(current_time, "chibios-contrib", "os")
  104. version_h_lines = f"""/* This file was automatically generated. Do not edit or copy.
  105. */
  106. #pragma once
  107. #define QMK_VERSION "{git_version}"
  108. #define QMK_BUILDDATE "{current_time}"
  109. #define CHIBIOS_VERSION "{chibios_version}"
  110. #define CHIBIOS_CONTRIB_VERSION "{chibios_contrib_version}"
  111. """
  112. return version_h_lines
  113. def compile_configurator_json(user_keymap, bootloader=None, parallel=1, **env_vars):
  114. """Convert a configurator export JSON file into a C file and then compile it.
  115. Args:
  116. user_keymap
  117. A deserialized keymap export
  118. bootloader
  119. A bootloader to flash
  120. parallel
  121. The number of make jobs to run in parallel
  122. Returns:
  123. A command to run to compile and flash the C file.
  124. """
  125. # Write the keymap.c file
  126. keyboard_filesafe = user_keymap['keyboard'].replace('/', '_')
  127. target = f'{keyboard_filesafe}_{user_keymap["keymap"]}'
  128. keyboard_output = Path(f'{KEYBOARD_OUTPUT_PREFIX}{keyboard_filesafe}')
  129. keymap_output = Path(f'{keyboard_output}_{user_keymap["keymap"]}')
  130. c_text = qmk.keymap.generate_c(user_keymap['keyboard'], user_keymap['layout'], user_keymap['layers'])
  131. keymap_dir = keymap_output / 'src'
  132. keymap_c = keymap_dir / 'keymap.c'
  133. keymap_dir.mkdir(exist_ok=True, parents=True)
  134. keymap_c.write_text(c_text)
  135. version_h = Path('quantum/version.h')
  136. version_h.write_text(create_version_h())
  137. # Return a command that can be run to make the keymap and flash if given
  138. verbose = 'true' if cli.config.general.verbose else 'false'
  139. color = 'true' if cli.config.general.color else 'false'
  140. make_command = [_find_make()]
  141. if not cli.config.general.verbose:
  142. make_command.append('-s')
  143. make_command.extend([
  144. *get_make_parallel_args(parallel),
  145. '-r',
  146. '-R',
  147. '-f',
  148. 'build_keyboard.mk',
  149. ])
  150. if bootloader:
  151. make_command.append(bootloader)
  152. for key, value in env_vars.items():
  153. make_command.append(f'{key}={value}')
  154. make_command.extend([
  155. f'KEYBOARD={user_keymap["keyboard"]}',
  156. f'KEYMAP={user_keymap["keymap"]}',
  157. f'KEYBOARD_FILESAFE={keyboard_filesafe}',
  158. f'TARGET={target}',
  159. f'KEYBOARD_OUTPUT={keyboard_output}',
  160. f'KEYMAP_OUTPUT={keymap_output}',
  161. f'MAIN_KEYMAP_PATH_1={keymap_output}',
  162. f'MAIN_KEYMAP_PATH_2={keymap_output}',
  163. f'MAIN_KEYMAP_PATH_3={keymap_output}',
  164. f'MAIN_KEYMAP_PATH_4={keymap_output}',
  165. f'MAIN_KEYMAP_PATH_5={keymap_output}',
  166. f'KEYMAP_C={keymap_c}',
  167. f'KEYMAP_PATH={keymap_dir}',
  168. f'VERBOSE={verbose}',
  169. f'COLOR={color}',
  170. 'SILENT=false',
  171. f'QMK_BIN={"bin/qmk" if "DEPRECATED_BIN_QMK" in os.environ else "qmk"}',
  172. ])
  173. return make_command
  174. def parse_configurator_json(configurator_file):
  175. """Open and parse a configurator json export
  176. """
  177. # FIXME(skullydazed/anyone): Add validation here
  178. user_keymap = json.load(configurator_file)
  179. orig_keyboard = user_keymap['keyboard']
  180. aliases = json_load(Path('data/mappings/keyboard_aliases.json'))
  181. if orig_keyboard in aliases:
  182. if 'target' in aliases[orig_keyboard]:
  183. user_keymap['keyboard'] = aliases[orig_keyboard]['target']
  184. if 'layouts' in aliases[orig_keyboard] and user_keymap['layout'] in aliases[orig_keyboard]['layouts']:
  185. user_keymap['layout'] = aliases[orig_keyboard]['layouts'][user_keymap['layout']]
  186. return user_keymap
  187. def git_get_username():
  188. """Retrieves user's username from Git config, if set.
  189. """
  190. git_username = cli.run(['git', 'config', '--get', 'user.name'])
  191. if git_username.returncode == 0 and git_username.stdout:
  192. return git_username.stdout.strip()
  193. def git_check_repo():
  194. """Checks that the .git directory exists inside QMK_HOME.
  195. This is a decent enough indicator that the qmk_firmware directory is a
  196. proper Git repository, rather than a .zip download from GitHub.
  197. """
  198. dot_git_dir = QMK_FIRMWARE / '.git'
  199. return dot_git_dir.is_dir()
  200. def git_get_branch():
  201. """Returns the current branch for a repo, or None.
  202. """
  203. git_branch = cli.run(['git', 'branch', '--show-current'])
  204. if not git_branch.returncode != 0 or not git_branch.stdout:
  205. # Workaround for Git pre-2.22
  206. git_branch = cli.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
  207. if git_branch.returncode == 0:
  208. return git_branch.stdout.strip()
  209. def git_is_dirty():
  210. """Returns 1 if repo is dirty, or 0 if clean
  211. """
  212. git_diff_staged_cmd = ['git', 'diff', '--quiet']
  213. git_diff_unstaged_cmd = [*git_diff_staged_cmd, '--cached']
  214. unstaged = cli.run(git_diff_staged_cmd)
  215. staged = cli.run(git_diff_unstaged_cmd)
  216. return unstaged.returncode != 0 or staged.returncode != 0
  217. def git_get_remotes():
  218. """Returns the current remotes for a repo.
  219. """
  220. remotes = {}
  221. git_remote_show_cmd = ['git', 'remote', 'show']
  222. git_remote_get_cmd = ['git', 'remote', 'get-url']
  223. git_remote_show = cli.run(git_remote_show_cmd)
  224. if git_remote_show.returncode == 0:
  225. for name in git_remote_show.stdout.splitlines():
  226. git_remote_name = cli.run([*git_remote_get_cmd, name])
  227. remotes[name.strip()] = {"url": git_remote_name.stdout.strip()}
  228. return remotes
  229. def git_check_deviation(active_branch):
  230. """Return True if branch has custom commits
  231. """
  232. cli.run(['git', 'fetch', 'upstream', active_branch])
  233. deviations = cli.run(['git', '--no-pager', 'log', f'upstream/{active_branch}...{active_branch}'])
  234. return bool(deviations.returncode)
  235. def in_virtualenv():
  236. """Check if running inside a virtualenv.
  237. Based on https://stackoverflow.com/a/1883251
  238. """
  239. active_prefix = getattr(sys, "base_prefix", None) or getattr(sys, "real_prefix", None) or sys.prefix
  240. return active_prefix != sys.prefix