commands.py 7.6 KB

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