commands.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. """Helper functions for commands.
  2. """
  3. import os
  4. import sys
  5. import shutil
  6. from itertools import islice
  7. from pathlib import Path
  8. from milc import cli
  9. import jsonschema
  10. import qmk.keymap
  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, **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. # Write the keymap.c file
  90. keyboard_filesafe = user_keymap['keyboard'].replace('/', '_')
  91. target = f'{keyboard_filesafe}_{user_keymap["keymap"]}'
  92. keyboard_output = Path(f'{KEYBOARD_OUTPUT_PREFIX}{keyboard_filesafe}')
  93. keymap_output = Path(f'{keyboard_output}_{user_keymap["keymap"]}')
  94. c_text = qmk.keymap.generate_c(user_keymap)
  95. keymap_dir = keymap_output / 'src'
  96. keymap_c = keymap_dir / 'keymap.c'
  97. keymap_dir.mkdir(exist_ok=True, parents=True)
  98. keymap_c.write_text(c_text)
  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. *get_make_parallel_args(parallel),
  107. '-r',
  108. '-R',
  109. '-f',
  110. 'builddefs/build_keyboard.mk',
  111. ])
  112. if bootloader:
  113. make_command.append(bootloader)
  114. for key, value in env_vars.items():
  115. make_command.append(f'{key}={value}')
  116. make_command.extend([
  117. f'KEYBOARD={user_keymap["keyboard"]}',
  118. f'KEYMAP={user_keymap["keymap"]}',
  119. f'KEYBOARD_FILESAFE={keyboard_filesafe}',
  120. f'TARGET={target}',
  121. f'KEYBOARD_OUTPUT={keyboard_output}',
  122. f'KEYMAP_OUTPUT={keymap_output}',
  123. f'MAIN_KEYMAP_PATH_1={keymap_output}',
  124. f'MAIN_KEYMAP_PATH_2={keymap_output}',
  125. f'MAIN_KEYMAP_PATH_3={keymap_output}',
  126. f'MAIN_KEYMAP_PATH_4={keymap_output}',
  127. f'MAIN_KEYMAP_PATH_5={keymap_output}',
  128. f'KEYMAP_C={keymap_c}',
  129. f'KEYMAP_PATH={keymap_dir}',
  130. f'VERBOSE={verbose}',
  131. f'COLOR={color}',
  132. 'SILENT=false',
  133. 'QMK_BIN="qmk"',
  134. ])
  135. return make_command
  136. def parse_configurator_json(configurator_file):
  137. """Open and parse a configurator json export
  138. """
  139. user_keymap = json_load(configurator_file)
  140. # Validate against the jsonschema
  141. try:
  142. validate(user_keymap, 'qmk.keymap.v1')
  143. except jsonschema.ValidationError as e:
  144. cli.log.error(f'Invalid JSON keymap: {configurator_file} : {e.message}')
  145. exit(1)
  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 in_virtualenv():
  155. """Check if running inside a virtualenv.
  156. Based on https://stackoverflow.com/a/1883251
  157. """
  158. active_prefix = getattr(sys, "base_prefix", None) or getattr(sys, "real_prefix", None) or sys.prefix
  159. return active_prefix != sys.prefix
  160. def get_chunks(it, size):
  161. """Break down a collection into smaller parts
  162. """
  163. it = iter(it)
  164. return iter(lambda: tuple(islice(it, size)), ())
  165. def dump_lines(output_file, lines, quiet=True):
  166. """Handle dumping to stdout or file
  167. Creates parent folders if required
  168. """
  169. generated = '\n'.join(lines) + '\n'
  170. if output_file and output_file.name != '-':
  171. output_file.parent.mkdir(parents=True, exist_ok=True)
  172. if output_file.exists():
  173. output_file.replace(output_file.parent / (output_file.name + '.bak'))
  174. output_file.write_text(generated, encoding='utf-8')
  175. if not quiet:
  176. cli.log.info(f'Wrote {output_file.name} to {output_file}.')
  177. else:
  178. print(generated)