commands.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. """Helper functions for commands.
  2. """
  3. import os
  4. import sys
  5. import json
  6. import shutil
  7. from itertools import islice
  8. from pathlib import Path
  9. from milc import cli
  10. import jsonschema
  11. from qmk.constants import KEYBOARD_OUTPUT_PREFIX
  12. from qmk.json_schema import json_load, validate
  13. def _find_make():
  14. """Returns the correct make command for this environment.
  15. """
  16. make_cmd = os.environ.get('MAKE')
  17. if not make_cmd:
  18. make_cmd = 'gmake' if shutil.which('gmake') else 'make'
  19. return make_cmd
  20. def create_make_target(target, dry_run=False, parallel=1, **env_vars):
  21. """Create a make command
  22. Args:
  23. target
  24. Usually a make rule, such as 'clean' or 'all'.
  25. dry_run
  26. make -n -- don't actually build
  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, *(['-n'] if dry_run else []), *get_make_parallel_args(parallel), *env, target]
  39. def create_make_command(keyboard, keymap, target=None, dry_run=False, 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. dry_run
  49. make -n -- don't actually build
  50. parallel
  51. The number of make jobs to run in parallel
  52. **env_vars
  53. Environment variables to be passed to make.
  54. Returns:
  55. A command that can be run to make the specified keyboard and keymap
  56. """
  57. make_args = [keyboard, keymap]
  58. if target:
  59. make_args.append(target)
  60. return create_make_target(':'.join(make_args), dry_run=dry_run, parallel=parallel, **env_vars)
  61. def get_make_parallel_args(parallel=1):
  62. """Returns the arguments for running the specified number of parallel jobs.
  63. """
  64. parallel_args = []
  65. if int(parallel) <= 0:
  66. # 0 or -1 means -j without argument (unlimited jobs)
  67. parallel_args.append('--jobs')
  68. else:
  69. parallel_args.append('--jobs=' + str(parallel))
  70. if int(parallel) != 1:
  71. # If more than 1 job is used, synchronize parallel output by target
  72. parallel_args.append('--output-sync=target')
  73. return parallel_args
  74. def compile_configurator_json(user_keymap, bootloader=None, parallel=1, clean=False, **env_vars):
  75. """Convert a configurator export JSON file into a C file and then compile it.
  76. Args:
  77. user_keymap
  78. A deserialized keymap export
  79. bootloader
  80. A bootloader to flash
  81. parallel
  82. The number of make jobs to run in parallel
  83. Returns:
  84. A command to run to compile and flash the C file.
  85. """
  86. # In case the user passes a keymap.json from a keymap directory directly to the CLI.
  87. # e.g.: qmk compile - < keyboards/clueboard/california/keymaps/default/keymap.json
  88. user_keymap["keymap"] = user_keymap.get("keymap", "default_json")
  89. keyboard_filesafe = user_keymap['keyboard'].replace('/', '_')
  90. target = f'{keyboard_filesafe}_{user_keymap["keymap"]}'
  91. keyboard_output = Path(f'{KEYBOARD_OUTPUT_PREFIX}{keyboard_filesafe}')
  92. keymap_output = Path(f'{keyboard_output}_{user_keymap["keymap"]}')
  93. keymap_dir = keymap_output / 'src'
  94. keymap_json = keymap_dir / 'keymap.json'
  95. if clean:
  96. if keyboard_output.exists():
  97. shutil.rmtree(keyboard_output)
  98. if keymap_output.exists():
  99. shutil.rmtree(keymap_output)
  100. # begin with making the deepest folder in the tree
  101. keymap_dir.mkdir(exist_ok=True, parents=True)
  102. # Compare minified to ensure consistent comparison
  103. new_content = json.dumps(user_keymap, separators=(',', ':'))
  104. if keymap_json.exists():
  105. old_content = json.dumps(json.loads(keymap_json.read_text(encoding='utf-8')), separators=(',', ':'))
  106. if old_content == new_content:
  107. new_content = None
  108. # Write the keymap.json file if different
  109. if new_content:
  110. keymap_json.write_text(new_content, encoding='utf-8')
  111. # Return a command that can be run to make the keymap and flash if given
  112. verbose = 'true' if cli.config.general.verbose else 'false'
  113. color = 'true' if cli.config.general.color else 'false'
  114. make_command = [_find_make()]
  115. if not cli.config.general.verbose:
  116. make_command.append('-s')
  117. make_command.extend([
  118. *get_make_parallel_args(parallel),
  119. '-r',
  120. '-R',
  121. '-f',
  122. 'builddefs/build_keyboard.mk',
  123. ])
  124. if bootloader:
  125. make_command.append(bootloader)
  126. for key, value in env_vars.items():
  127. make_command.append(f'{key}={value}')
  128. make_command.extend([
  129. f'KEYBOARD={user_keymap["keyboard"]}',
  130. f'KEYMAP={user_keymap["keymap"]}',
  131. f'KEYBOARD_FILESAFE={keyboard_filesafe}',
  132. f'TARGET={target}',
  133. f'KEYBOARD_OUTPUT={keyboard_output}',
  134. f'KEYMAP_OUTPUT={keymap_output}',
  135. f'MAIN_KEYMAP_PATH_1={keymap_output}',
  136. f'MAIN_KEYMAP_PATH_2={keymap_output}',
  137. f'MAIN_KEYMAP_PATH_3={keymap_output}',
  138. f'MAIN_KEYMAP_PATH_4={keymap_output}',
  139. f'MAIN_KEYMAP_PATH_5={keymap_output}',
  140. f'KEYMAP_JSON={keymap_json}',
  141. f'KEYMAP_PATH={keymap_dir}',
  142. f'VERBOSE={verbose}',
  143. f'COLOR={color}',
  144. 'SILENT=false',
  145. 'QMK_BIN="qmk"',
  146. ])
  147. return make_command
  148. def parse_configurator_json(configurator_file):
  149. """Open and parse a configurator json export
  150. """
  151. user_keymap = json_load(configurator_file)
  152. # Validate against the jsonschema
  153. try:
  154. validate(user_keymap, 'qmk.keymap.v1')
  155. except jsonschema.ValidationError as e:
  156. cli.log.error(f'Invalid JSON keymap: {configurator_file} : {e.message}')
  157. exit(1)
  158. orig_keyboard = user_keymap['keyboard']
  159. aliases = json_load(Path('data/mappings/keyboard_aliases.hjson'))
  160. if orig_keyboard in aliases:
  161. if 'target' in aliases[orig_keyboard]:
  162. user_keymap['keyboard'] = aliases[orig_keyboard]['target']
  163. if 'layouts' in aliases[orig_keyboard] and user_keymap['layout'] in aliases[orig_keyboard]['layouts']:
  164. user_keymap['layout'] = aliases[orig_keyboard]['layouts'][user_keymap['layout']]
  165. return user_keymap
  166. def build_environment(args):
  167. """Common processing for cli.args.env
  168. """
  169. envs = {}
  170. for env in args:
  171. if '=' in env:
  172. key, value = env.split('=', 1)
  173. envs[key] = value
  174. else:
  175. cli.log.warning('Invalid environment variable: %s', env)
  176. return envs
  177. def in_virtualenv():
  178. """Check if running inside a virtualenv.
  179. Based on https://stackoverflow.com/a/1883251
  180. """
  181. active_prefix = getattr(sys, "base_prefix", None) or getattr(sys, "real_prefix", None) or sys.prefix
  182. return active_prefix != sys.prefix
  183. def get_chunks(it, size):
  184. """Break down a collection into smaller parts
  185. """
  186. it = iter(it)
  187. return iter(lambda: tuple(islice(it, size)), ())
  188. def dump_lines(output_file, lines, quiet=True):
  189. """Handle dumping to stdout or file
  190. Creates parent folders if required
  191. """
  192. generated = '\n'.join(lines) + '\n'
  193. if output_file and output_file.name != '-':
  194. output_file.parent.mkdir(parents=True, exist_ok=True)
  195. if output_file.exists():
  196. output_file.replace(output_file.parent / (output_file.name + '.bak'))
  197. output_file.write_text(generated, encoding='utf-8')
  198. if not quiet:
  199. cli.log.info(f'Wrote {output_file.name} to {output_file}.')
  200. else:
  201. print(generated)