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.

236 lines
6.7 KiB

New CLI subcommand to create clang-compatible compilation database (`compile_commands.json`) (#14370) * pulled source from dev branch * missed a file from origin * formatting * revised argument names. relaxed matching rules to work for avr too * add docstrings * added docs. tightened up regex * remove unused imports * cleaning up command file. use existing qmk dir constant * rename parser library file * move lib functions into command file. there are only 2 and they aren't large * currently debugging... * more robustly find config * updated docs * remove unused imports * reuse make executable from the main make command * pulled source from dev branch * missed a file from origin * formatting * revised argument names. relaxed matching rules to work for avr too * add docstrings * added docs. tightened up regex * remove unused imports * cleaning up command file. use existing qmk dir constant * rename parser library file * move lib functions into command file. there are only 2 and they aren't large * currently debugging... * more robustly find config * updated docs * remove unused imports * reuse make executable from the main make command * remove MAKEFLAGS from environment for better control over process management * Update .gitignore Co-authored-by: Michael Forster <forster@google.com> * add a usage line to docs * doc change as suggested Co-authored-by: Nick Brassel <nick@tzarc.org> * rename command * remove debug print statements * generate-compilation-database: fix arg handling * generate-comilation-db: improve error handling * use cli.run() instead of Popen() Co-authored-by: Xton <cdewan@apple.com> Co-authored-by: Christon DeWan <cmdpix@mac.com> Co-authored-by: Michael Forster <forster@google.com> Co-authored-by: Nick Brassel <nick@tzarc.org>
2 years ago
New CLI subcommand to create clang-compatible compilation database (`compile_commands.json`) (#14370) * pulled source from dev branch * missed a file from origin * formatting * revised argument names. relaxed matching rules to work for avr too * add docstrings * added docs. tightened up regex * remove unused imports * cleaning up command file. use existing qmk dir constant * rename parser library file * move lib functions into command file. there are only 2 and they aren't large * currently debugging... * more robustly find config * updated docs * remove unused imports * reuse make executable from the main make command * pulled source from dev branch * missed a file from origin * formatting * revised argument names. relaxed matching rules to work for avr too * add docstrings * added docs. tightened up regex * remove unused imports * cleaning up command file. use existing qmk dir constant * rename parser library file * move lib functions into command file. there are only 2 and they aren't large * currently debugging... * more robustly find config * updated docs * remove unused imports * reuse make executable from the main make command * remove MAKEFLAGS from environment for better control over process management * Update .gitignore Co-authored-by: Michael Forster <forster@google.com> * add a usage line to docs * doc change as suggested Co-authored-by: Nick Brassel <nick@tzarc.org> * rename command * remove debug print statements * generate-compilation-database: fix arg handling * generate-comilation-db: improve error handling * use cli.run() instead of Popen() Co-authored-by: Xton <cdewan@apple.com> Co-authored-by: Christon DeWan <cmdpix@mac.com> Co-authored-by: Michael Forster <forster@google.com> Co-authored-by: Nick Brassel <nick@tzarc.org>
2 years ago
New CLI subcommand to create clang-compatible compilation database (`compile_commands.json`) (#14370) * pulled source from dev branch * missed a file from origin * formatting * revised argument names. relaxed matching rules to work for avr too * add docstrings * added docs. tightened up regex * remove unused imports * cleaning up command file. use existing qmk dir constant * rename parser library file * move lib functions into command file. there are only 2 and they aren't large * currently debugging... * more robustly find config * updated docs * remove unused imports * reuse make executable from the main make command * pulled source from dev branch * missed a file from origin * formatting * revised argument names. relaxed matching rules to work for avr too * add docstrings * added docs. tightened up regex * remove unused imports * cleaning up command file. use existing qmk dir constant * rename parser library file * move lib functions into command file. there are only 2 and they aren't large * currently debugging... * more robustly find config * updated docs * remove unused imports * reuse make executable from the main make command * remove MAKEFLAGS from environment for better control over process management * Update .gitignore Co-authored-by: Michael Forster <forster@google.com> * add a usage line to docs * doc change as suggested Co-authored-by: Nick Brassel <nick@tzarc.org> * rename command * remove debug print statements * generate-compilation-database: fix arg handling * generate-comilation-db: improve error handling * use cli.run() instead of Popen() Co-authored-by: Xton <cdewan@apple.com> Co-authored-by: Christon DeWan <cmdpix@mac.com> Co-authored-by: Michael Forster <forster@google.com> Co-authored-by: Nick Brassel <nick@tzarc.org>
2 years ago
New CLI subcommand to create clang-compatible compilation database (`compile_commands.json`) (#14370) * pulled source from dev branch * missed a file from origin * formatting * revised argument names. relaxed matching rules to work for avr too * add docstrings * added docs. tightened up regex * remove unused imports * cleaning up command file. use existing qmk dir constant * rename parser library file * move lib functions into command file. there are only 2 and they aren't large * currently debugging... * more robustly find config * updated docs * remove unused imports * reuse make executable from the main make command * pulled source from dev branch * missed a file from origin * formatting * revised argument names. relaxed matching rules to work for avr too * add docstrings * added docs. tightened up regex * remove unused imports * cleaning up command file. use existing qmk dir constant * rename parser library file * move lib functions into command file. there are only 2 and they aren't large * currently debugging... * more robustly find config * updated docs * remove unused imports * reuse make executable from the main make command * remove MAKEFLAGS from environment for better control over process management * Update .gitignore Co-authored-by: Michael Forster <forster@google.com> * add a usage line to docs * doc change as suggested Co-authored-by: Nick Brassel <nick@tzarc.org> * rename command * remove debug print statements * generate-compilation-database: fix arg handling * generate-comilation-db: improve error handling * use cli.run() instead of Popen() Co-authored-by: Xton <cdewan@apple.com> Co-authored-by: Christon DeWan <cmdpix@mac.com> Co-authored-by: Michael Forster <forster@google.com> Co-authored-by: Nick Brassel <nick@tzarc.org>
2 years ago
New CLI subcommand to create clang-compatible compilation database (`compile_commands.json`) (#14370) * pulled source from dev branch * missed a file from origin * formatting * revised argument names. relaxed matching rules to work for avr too * add docstrings * added docs. tightened up regex * remove unused imports * cleaning up command file. use existing qmk dir constant * rename parser library file * move lib functions into command file. there are only 2 and they aren't large * currently debugging... * more robustly find config * updated docs * remove unused imports * reuse make executable from the main make command * pulled source from dev branch * missed a file from origin * formatting * revised argument names. relaxed matching rules to work for avr too * add docstrings * added docs. tightened up regex * remove unused imports * cleaning up command file. use existing qmk dir constant * rename parser library file * move lib functions into command file. there are only 2 and they aren't large * currently debugging... * more robustly find config * updated docs * remove unused imports * reuse make executable from the main make command * remove MAKEFLAGS from environment for better control over process management * Update .gitignore Co-authored-by: Michael Forster <forster@google.com> * add a usage line to docs * doc change as suggested Co-authored-by: Nick Brassel <nick@tzarc.org> * rename command * remove debug print statements * generate-compilation-database: fix arg handling * generate-comilation-db: improve error handling * use cli.run() instead of Popen() Co-authored-by: Xton <cdewan@apple.com> Co-authored-by: Christon DeWan <cmdpix@mac.com> Co-authored-by: Michael Forster <forster@google.com> Co-authored-by: Nick Brassel <nick@tzarc.org>
2 years ago
New CLI subcommand to create clang-compatible compilation database (`compile_commands.json`) (#14370) * pulled source from dev branch * missed a file from origin * formatting * revised argument names. relaxed matching rules to work for avr too * add docstrings * added docs. tightened up regex * remove unused imports * cleaning up command file. use existing qmk dir constant * rename parser library file * move lib functions into command file. there are only 2 and they aren't large * currently debugging... * more robustly find config * updated docs * remove unused imports * reuse make executable from the main make command * pulled source from dev branch * missed a file from origin * formatting * revised argument names. relaxed matching rules to work for avr too * add docstrings * added docs. tightened up regex * remove unused imports * cleaning up command file. use existing qmk dir constant * rename parser library file * move lib functions into command file. there are only 2 and they aren't large * currently debugging... * more robustly find config * updated docs * remove unused imports * reuse make executable from the main make command * remove MAKEFLAGS from environment for better control over process management * Update .gitignore Co-authored-by: Michael Forster <forster@google.com> * add a usage line to docs * doc change as suggested Co-authored-by: Nick Brassel <nick@tzarc.org> * rename command * remove debug print statements * generate-compilation-database: fix arg handling * generate-comilation-db: improve error handling * use cli.run() instead of Popen() Co-authored-by: Xton <cdewan@apple.com> Co-authored-by: Christon DeWan <cmdpix@mac.com> Co-authored-by: Michael Forster <forster@google.com> Co-authored-by: Nick Brassel <nick@tzarc.org>
2 years ago
  1. """Helper functions for commands.
  2. """
  3. import os
  4. import sys
  5. import shutil
  6. from pathlib import Path
  7. from milc import cli
  8. import jsonschema
  9. import qmk.keymap
  10. from qmk.constants import KEYBOARD_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. return [make_cmd, *(['-n'] if dry_run else []), *get_make_parallel_args(parallel), *env, target]
  38. def create_make_command(keyboard, keymap, target=None, dry_run=False, parallel=1, **env_vars):
  39. """Create a make compile command
  40. Args:
  41. keyboard
  42. The path of the keyboard, for example 'plank'
  43. keymap
  44. The name of the keymap, for example 'algernon'
  45. target
  46. Usually a bootloader.
  47. dry_run
  48. make -n -- don't actually build
  49. parallel
  50. The number of make jobs to run in parallel
  51. **env_vars
  52. Environment variables to be passed to make.
  53. Returns:
  54. A command that can be run to make the specified keyboard and keymap
  55. """
  56. make_args = [keyboard, keymap]
  57. if target:
  58. make_args.append(target)
  59. return create_make_target(':'.join(make_args), dry_run=dry_run, parallel=parallel, **env_vars)
  60. def get_make_parallel_args(parallel=1):
  61. """Returns the arguments for running the specified number of parallel jobs.
  62. """
  63. parallel_args = []
  64. if int(parallel) <= 0:
  65. # 0 or -1 means -j without argument (unlimited jobs)
  66. parallel_args.append('--jobs')
  67. else:
  68. parallel_args.append('--jobs=' + str(parallel))
  69. if int(parallel) != 1:
  70. # If more than 1 job is used, synchronize parallel output by target
  71. parallel_args.append('--output-sync=target')
  72. return parallel_args
  73. def compile_configurator_json(user_keymap, bootloader=None, parallel=1, **env_vars):
  74. """Convert a configurator export JSON file into a C file and then compile it.
  75. Args:
  76. user_keymap
  77. A deserialized keymap export
  78. bootloader
  79. A bootloader to flash
  80. parallel
  81. The number of make jobs to run in parallel
  82. Returns:
  83. A command to run to compile and flash the C file.
  84. """
  85. # In case the user passes a keymap.json from a keymap directory directly to the CLI.
  86. # e.g.: qmk compile - < keyboards/clueboard/california/keymaps/default/keymap.json
  87. user_keymap["keymap"] = user_keymap.get("keymap", "default_json")
  88. # Write the keymap.c file
  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. c_text = qmk.keymap.generate_c(user_keymap)
  94. keymap_dir = keymap_output / 'src'
  95. keymap_c = keymap_dir / 'keymap.c'
  96. keymap_dir.mkdir(exist_ok=True, parents=True)
  97. keymap_c.write_text(c_text)
  98. # Return a command that can be run to make the keymap and flash if given
  99. verbose = 'true' if cli.config.general.verbose else 'false'
  100. color = 'true' if cli.config.general.color else 'false'
  101. make_command = [_find_make()]
  102. if not cli.config.general.verbose:
  103. make_command.append('-s')
  104. make_command.extend([
  105. *get_make_parallel_args(parallel),
  106. '-r',
  107. '-R',
  108. '-f',
  109. 'builddefs/build_keyboard.mk',
  110. ])
  111. if bootloader:
  112. make_command.append(bootloader)
  113. for key, value in env_vars.items():
  114. make_command.append(f'{key}={value}')
  115. make_command.extend([
  116. f'KEYBOARD={user_keymap["keyboard"]}',
  117. f'KEYMAP={user_keymap["keymap"]}',
  118. f'KEYBOARD_FILESAFE={keyboard_filesafe}',
  119. f'TARGET={target}',
  120. f'KEYBOARD_OUTPUT={keyboard_output}',
  121. f'KEYMAP_OUTPUT={keymap_output}',
  122. f'MAIN_KEYMAP_PATH_1={keymap_output}',
  123. f'MAIN_KEYMAP_PATH_2={keymap_output}',
  124. f'MAIN_KEYMAP_PATH_3={keymap_output}',
  125. f'MAIN_KEYMAP_PATH_4={keymap_output}',
  126. f'MAIN_KEYMAP_PATH_5={keymap_output}',
  127. f'KEYMAP_C={keymap_c}',
  128. f'KEYMAP_PATH={keymap_dir}',
  129. f'VERBOSE={verbose}',
  130. f'COLOR={color}',
  131. 'SILENT=false',
  132. 'QMK_BIN="qmk"',
  133. ])
  134. return make_command
  135. def parse_configurator_json(configurator_file):
  136. """Open and parse a configurator json export
  137. """
  138. user_keymap = json_load(configurator_file)
  139. # Validate against the jsonschema
  140. try:
  141. validate(user_keymap, 'qmk.keymap.v1')
  142. except jsonschema.ValidationError as e:
  143. cli.log.error(f'Invalid JSON keymap: {configurator_file} : {e.message}')
  144. exit(1)
  145. orig_keyboard = user_keymap['keyboard']
  146. aliases = json_load(Path('data/mappings/keyboard_aliases.json'))
  147. if orig_keyboard in aliases:
  148. if 'target' in aliases[orig_keyboard]:
  149. user_keymap['keyboard'] = aliases[orig_keyboard]['target']
  150. if 'layouts' in aliases[orig_keyboard] and user_keymap['layout'] in aliases[orig_keyboard]['layouts']:
  151. user_keymap['layout'] = aliases[orig_keyboard]['layouts'][user_keymap['layout']]
  152. return user_keymap
  153. def in_virtualenv():
  154. """Check if running inside a virtualenv.
  155. Based on https://stackoverflow.com/a/1883251
  156. """
  157. active_prefix = getattr(sys, "base_prefix", None) or getattr(sys, "real_prefix", None) or sys.prefix
  158. return active_prefix != sys.prefix
  159. def dump_lines(output_file, lines, quiet=True):
  160. """Handle dumping to stdout or file
  161. Creates parent folders if required
  162. """
  163. generated = '\n'.join(lines) + '\n'
  164. if output_file and output_file.name != '-':
  165. output_file.parent.mkdir(parents=True, exist_ok=True)
  166. if output_file.exists():
  167. output_file.replace(output_file.parent / (output_file.name + '.bak'))
  168. output_file.write_text(generated)
  169. if not quiet:
  170. cli.log.info(f'Wrote {output_file.name} to {output_file}.')
  171. else:
  172. print(generated)