commands.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. """Helper functions for commands.
  2. """
  3. import os
  4. import sys
  5. import shutil
  6. from pathlib import Path
  7. from time import strftime
  8. from itertools import islice
  9. from subprocess import DEVNULL
  10. from milc import cli
  11. import jsonschema
  12. import qmk.keymap
  13. from qmk.constants import QMK_FIRMWARE, KEYBOARD_OUTPUT_PREFIX
  14. from qmk.json_schema import json_load, validate
  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, dry_run=False, parallel=1, **env_vars):
  23. """Create a make command
  24. Args:
  25. target
  26. Usually a make rule, such as 'clean' or 'all'.
  27. dry_run
  28. make -n -- don't actually build
  29. parallel
  30. The number of make jobs to run in parallel
  31. **env_vars
  32. Environment variables to be passed to make.
  33. Returns:
  34. A command that can be run to make the specified keyboard and keymap
  35. """
  36. env = []
  37. make_cmd = _find_make()
  38. for key, value in env_vars.items():
  39. env.append(f'{key}={value}')
  40. return [make_cmd, *(['-n'] if dry_run else []), *get_make_parallel_args(parallel), *env, target]
  41. def create_make_command(keyboard, keymap, target=None, dry_run=False, parallel=1, **env_vars):
  42. """Create a make compile command
  43. Args:
  44. keyboard
  45. The path of the keyboard, for example 'plank'
  46. keymap
  47. The name of the keymap, for example 'algernon'
  48. target
  49. Usually a bootloader.
  50. dry_run
  51. make -n -- don't actually build
  52. parallel
  53. The number of make jobs to run in parallel
  54. **env_vars
  55. Environment variables to be passed to make.
  56. Returns:
  57. A command that can be run to make the specified keyboard and keymap
  58. """
  59. make_args = [keyboard, keymap]
  60. if target:
  61. make_args.append(target)
  62. return create_make_target(':'.join(make_args), dry_run=dry_run, parallel=parallel, **env_vars)
  63. def get_git_version(current_time=None, repo_dir='.', check_dir='.'):
  64. """Returns the current git version for a repo, or the current time.
  65. """
  66. git_describe_cmd = ['git', 'describe', '--abbrev=6', '--dirty', '--always', '--tags']
  67. if current_time is None:
  68. current_time = strftime('%Y-%m-%d-%H:%M:%S')
  69. if repo_dir != '.':
  70. repo_dir = Path('lib') / repo_dir
  71. if check_dir != '.':
  72. check_dir = repo_dir / check_dir
  73. if Path(check_dir).exists():
  74. git_describe = cli.run(git_describe_cmd, stdin=DEVNULL, cwd=repo_dir)
  75. if git_describe.returncode == 0:
  76. return git_describe.stdout.strip()
  77. else:
  78. cli.log.warn(f'"{" ".join(git_describe_cmd)}" returned error code {git_describe.returncode}')
  79. print(git_describe.stderr)
  80. return current_time
  81. return current_time
  82. def get_make_parallel_args(parallel=1):
  83. """Returns the arguments for running the specified number of parallel jobs.
  84. """
  85. parallel_args = []
  86. if int(parallel) <= 0:
  87. # 0 or -1 means -j without argument (unlimited jobs)
  88. parallel_args.append('--jobs')
  89. else:
  90. parallel_args.append('--jobs=' + str(parallel))
  91. if int(parallel) != 1:
  92. # If more than 1 job is used, synchronize parallel output by target
  93. parallel_args.append('--output-sync=target')
  94. return parallel_args
  95. def compile_configurator_json(user_keymap, bootloader=None, parallel=1, **env_vars):
  96. """Convert a configurator export JSON file into a C file and then compile it.
  97. Args:
  98. user_keymap
  99. A deserialized keymap export
  100. bootloader
  101. A bootloader to flash
  102. parallel
  103. The number of make jobs to run in parallel
  104. Returns:
  105. A command to run to compile and flash the C file.
  106. """
  107. # In case the user passes a keymap.json from a keymap directory directly to the CLI.
  108. # e.g.: qmk compile - < keyboards/clueboard/california/keymaps/default/keymap.json
  109. user_keymap["keymap"] = user_keymap.get("keymap", "default_json")
  110. # Write the keymap.c file
  111. keyboard_filesafe = user_keymap['keyboard'].replace('/', '_')
  112. target = f'{keyboard_filesafe}_{user_keymap["keymap"]}'
  113. keyboard_output = Path(f'{KEYBOARD_OUTPUT_PREFIX}{keyboard_filesafe}')
  114. keymap_output = Path(f'{keyboard_output}_{user_keymap["keymap"]}')
  115. c_text = qmk.keymap.generate_c(user_keymap)
  116. keymap_dir = keymap_output / 'src'
  117. keymap_c = keymap_dir / 'keymap.c'
  118. keymap_dir.mkdir(exist_ok=True, parents=True)
  119. keymap_c.write_text(c_text)
  120. # Return a command that can be run to make the keymap and flash if given
  121. verbose = 'true' if cli.config.general.verbose else 'false'
  122. color = 'true' if cli.config.general.color else 'false'
  123. make_command = [_find_make()]
  124. if not cli.config.general.verbose:
  125. make_command.append('-s')
  126. make_command.extend([
  127. *get_make_parallel_args(parallel),
  128. '-r',
  129. '-R',
  130. '-f',
  131. 'builddefs/build_keyboard.mk',
  132. ])
  133. if bootloader:
  134. make_command.append(bootloader)
  135. for key, value in env_vars.items():
  136. make_command.append(f'{key}={value}')
  137. make_command.extend([
  138. f'KEYBOARD={user_keymap["keyboard"]}',
  139. f'KEYMAP={user_keymap["keymap"]}',
  140. f'KEYBOARD_FILESAFE={keyboard_filesafe}',
  141. f'TARGET={target}',
  142. f'KEYBOARD_OUTPUT={keyboard_output}',
  143. f'KEYMAP_OUTPUT={keymap_output}',
  144. f'MAIN_KEYMAP_PATH_1={keymap_output}',
  145. f'MAIN_KEYMAP_PATH_2={keymap_output}',
  146. f'MAIN_KEYMAP_PATH_3={keymap_output}',
  147. f'MAIN_KEYMAP_PATH_4={keymap_output}',
  148. f'MAIN_KEYMAP_PATH_5={keymap_output}',
  149. f'KEYMAP_C={keymap_c}',
  150. f'KEYMAP_PATH={keymap_dir}',
  151. f'VERBOSE={verbose}',
  152. f'COLOR={color}',
  153. 'SILENT=false',
  154. 'QMK_BIN="qmk"',
  155. ])
  156. return make_command
  157. def parse_configurator_json(configurator_file):
  158. """Open and parse a configurator json export
  159. """
  160. user_keymap = json_load(configurator_file)
  161. # Validate against the jsonschema
  162. try:
  163. validate(user_keymap, 'qmk.keymap.v1')
  164. except jsonschema.ValidationError as e:
  165. cli.log.error(f'Invalid JSON keymap: {configurator_file} : {e.message}')
  166. exit(1)
  167. orig_keyboard = user_keymap['keyboard']
  168. aliases = json_load(Path('data/mappings/keyboard_aliases.json'))
  169. if orig_keyboard in aliases:
  170. if 'target' in aliases[orig_keyboard]:
  171. user_keymap['keyboard'] = aliases[orig_keyboard]['target']
  172. if 'layouts' in aliases[orig_keyboard] and user_keymap['layout'] in aliases[orig_keyboard]['layouts']:
  173. user_keymap['layout'] = aliases[orig_keyboard]['layouts'][user_keymap['layout']]
  174. return user_keymap
  175. def git_get_username():
  176. """Retrieves user's username from Git config, if set.
  177. """
  178. git_username = cli.run(['git', 'config', '--get', 'user.name'])
  179. if git_username.returncode == 0 and git_username.stdout:
  180. return git_username.stdout.strip()
  181. def git_check_repo():
  182. """Checks that the .git directory exists inside QMK_HOME.
  183. This is a decent enough indicator that the qmk_firmware directory is a
  184. proper Git repository, rather than a .zip download from GitHub.
  185. """
  186. dot_git_dir = QMK_FIRMWARE / '.git'
  187. return dot_git_dir.is_dir()
  188. def git_get_branch():
  189. """Returns the current branch for a repo, or None.
  190. """
  191. git_branch = cli.run(['git', 'branch', '--show-current'])
  192. if not git_branch.returncode != 0 or not git_branch.stdout:
  193. # Workaround for Git pre-2.22
  194. git_branch = cli.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
  195. if git_branch.returncode == 0:
  196. return git_branch.stdout.strip()
  197. def git_get_tag():
  198. """Returns the current tag for a repo, or None.
  199. """
  200. git_tag = cli.run(['git', 'describe', '--abbrev=0', '--tags'])
  201. if git_tag.returncode == 0:
  202. return git_tag.stdout.strip()
  203. def git_is_dirty():
  204. """Returns 1 if repo is dirty, or 0 if clean
  205. """
  206. git_diff_staged_cmd = ['git', 'diff', '--quiet']
  207. git_diff_unstaged_cmd = [*git_diff_staged_cmd, '--cached']
  208. unstaged = cli.run(git_diff_staged_cmd)
  209. staged = cli.run(git_diff_unstaged_cmd)
  210. return unstaged.returncode != 0 or staged.returncode != 0
  211. def git_get_remotes():
  212. """Returns the current remotes for a repo.
  213. """
  214. remotes = {}
  215. git_remote_show_cmd = ['git', 'remote', 'show']
  216. git_remote_get_cmd = ['git', 'remote', 'get-url']
  217. git_remote_show = cli.run(git_remote_show_cmd)
  218. if git_remote_show.returncode == 0:
  219. for name in git_remote_show.stdout.splitlines():
  220. git_remote_name = cli.run([*git_remote_get_cmd, name])
  221. remotes[name.strip()] = {"url": git_remote_name.stdout.strip()}
  222. return remotes
  223. def git_check_deviation(active_branch):
  224. """Return True if branch has custom commits
  225. """
  226. cli.run(['git', 'fetch', 'upstream', active_branch])
  227. deviations = cli.run(['git', '--no-pager', 'log', f'upstream/{active_branch}...{active_branch}'])
  228. return bool(deviations.returncode)
  229. def in_virtualenv():
  230. """Check if running inside a virtualenv.
  231. Based on https://stackoverflow.com/a/1883251
  232. """
  233. active_prefix = getattr(sys, "base_prefix", None) or getattr(sys, "real_prefix", None) or sys.prefix
  234. return active_prefix != sys.prefix
  235. def get_chunks(it, size):
  236. """Break down a collection into smaller parts
  237. """
  238. it = iter(it)
  239. return iter(lambda: tuple(islice(it, size)), ())
  240. def dump_lines(output_file, lines, quiet=True):
  241. """Handle dumping to stdout or file
  242. Creates parent folders if required
  243. """
  244. generated = '\n'.join(lines) + '\n'
  245. if output_file and output_file.name != '-':
  246. output_file.parent.mkdir(parents=True, exist_ok=True)
  247. if output_file.exists():
  248. output_file.replace(output_file.parent / (output_file.name + '.bak'))
  249. output_file.write_text(generated, encoding='utf-8')
  250. if not quiet:
  251. cli.log.info(f'Wrote {output_file.name} to {output_file}.')
  252. else:
  253. print(generated)