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.

159 lines
6.9 KiB

Configuration system for CLI (#6708) * Rework how bin/qmk handles subcommands * qmk config wip * Code to show all configs * Fully working `qmk config` command * Mark some CLI arguments so they don't pollute the config file * Fleshed out config support, nicer subcommand support * sync with installable cli * pyformat * Add a test for subcommand_modules * Documentation for the `qmk config` command * split config_token on space so qmk config is more predictable * Rework how subcommands are imported * Document `arg_only` * Document deleting from CLI * Document how multiple operations work * Add cli config to the doc index * Add tests for the cli commands * Make running the tests more reliable * Be more selective about building all default keymaps * Update new-keymap to fit the new subcommand style * Add documentation about writing CLI scripts * Document new-keyboard * Update docs/cli_configuration.md Co-Authored-By: noroadsleft <18669334+noroadsleft@users.noreply.github.com> * Update docs/cli_development.md Co-Authored-By: noroadsleft <18669334+noroadsleft@users.noreply.github.com> * Update docs/cli_development.md Co-Authored-By: noroadsleft <18669334+noroadsleft@users.noreply.github.com> * Update docs/cli_development.md Co-Authored-By: noroadsleft <18669334+noroadsleft@users.noreply.github.com> * Address yan's comments. * Apply suggestions from code review suggestions from @noahfrederick Co-Authored-By: Noah Frederick <code@noahfrederick.com> * Apply suggestions from code review Co-Authored-By: Noah Frederick <code@noahfrederick.com> * Remove pip3 from the test runner
4 years ago
Configuration system for CLI (#6708) * Rework how bin/qmk handles subcommands * qmk config wip * Code to show all configs * Fully working `qmk config` command * Mark some CLI arguments so they don't pollute the config file * Fleshed out config support, nicer subcommand support * sync with installable cli * pyformat * Add a test for subcommand_modules * Documentation for the `qmk config` command * split config_token on space so qmk config is more predictable * Rework how subcommands are imported * Document `arg_only` * Document deleting from CLI * Document how multiple operations work * Add cli config to the doc index * Add tests for the cli commands * Make running the tests more reliable * Be more selective about building all default keymaps * Update new-keymap to fit the new subcommand style * Add documentation about writing CLI scripts * Document new-keyboard * Update docs/cli_configuration.md Co-Authored-By: noroadsleft <18669334+noroadsleft@users.noreply.github.com> * Update docs/cli_development.md Co-Authored-By: noroadsleft <18669334+noroadsleft@users.noreply.github.com> * Update docs/cli_development.md Co-Authored-By: noroadsleft <18669334+noroadsleft@users.noreply.github.com> * Update docs/cli_development.md Co-Authored-By: noroadsleft <18669334+noroadsleft@users.noreply.github.com> * Address yan's comments. * Apply suggestions from code review suggestions from @noahfrederick Co-Authored-By: Noah Frederick <code@noahfrederick.com> * Apply suggestions from code review Co-Authored-By: Noah Frederick <code@noahfrederick.com> * Remove pip3 from the test runner
4 years ago
  1. """Compile a QMK Firmware.
  2. You can compile a keymap already in the repo or using a QMK Configurator export.
  3. """
  4. from subprocess import DEVNULL
  5. from argcomplete.completers import FilesCompleter
  6. from dotty_dict import dotty
  7. from milc import cli
  8. import qmk.path
  9. from qmk.decorators import automagic_keyboard, automagic_keymap, lru_cache
  10. from qmk.commands import compile_configurator_json, create_make_command, parse_configurator_json
  11. from qmk.info import info_json
  12. from qmk.keyboard import keyboard_completer, is_keyboard_target, list_keyboards
  13. from qmk.keymap import keymap_completer, list_keymaps
  14. from qmk.metadata import true_values, false_values
  15. @lru_cache()
  16. def _keyboard_list():
  17. """Returns a list of keyboards matching cli.config.compile.keyboard.
  18. """
  19. if cli.config.compile.keyboard == 'all':
  20. return list_keyboards()
  21. elif cli.config.compile.keyboard.startswith('all-'):
  22. return list_keyboards()
  23. return [cli.config.compile.keyboard]
  24. def keyboard_keymap_iter():
  25. """Iterates over the keyboard/keymap for this command and yields a pairing of each.
  26. """
  27. for keyboard in _keyboard_list():
  28. continue_flag = False
  29. if cli.args.filter:
  30. info_data = dotty(info_json(keyboard))
  31. for filter in cli.args.filter:
  32. if '=' in filter:
  33. key, value = filter.split('=', 1)
  34. if value in true_values:
  35. value = True
  36. elif value in false_values:
  37. value = False
  38. elif value.isdigit():
  39. value = int(value)
  40. elif '.' in value and value.replace('.').isdigit():
  41. value = float(value)
  42. if info_data.get(key) != value:
  43. continue_flag = True
  44. break
  45. if continue_flag:
  46. continue
  47. if cli.config.compile.keymap == 'all':
  48. for keymap in list_keymaps(keyboard):
  49. yield keyboard, keymap
  50. else:
  51. yield keyboard, cli.config.compile.keymap
  52. @cli.argument('filename', nargs='?', arg_only=True, type=qmk.path.FileType('r'), completer=FilesCompleter('.json'), help='The configurator export to compile')
  53. @cli.argument('-kb', '--keyboard', type=is_keyboard_target, completer=keyboard_completer, help='The keyboard to build a firmware for. Ignored when a configurator export is supplied.')
  54. @cli.argument('-km', '--keymap', completer=keymap_completer, help='The keymap to build a firmware for. Ignored when a configurator export is supplied.')
  55. @cli.argument('-n', '--dry-run', arg_only=True, action='store_true', help="Don't actually build, just show the make command to be run.")
  56. @cli.argument('-j', '--parallel', type=int, default=1, help="Set the number of parallel make jobs to run.")
  57. @cli.argument('-f', '--filter', arg_only=True, action='append', default=[], help="Filter your list against info.json.")
  58. @cli.argument('-e', '--env', arg_only=True, action='append', default=[], help="Set a variable to be passed to make. May be passed multiple times.")
  59. @cli.argument('-c', '--clean', arg_only=True, action='store_true', help="Remove object files before compiling.")
  60. @cli.subcommand('Compile a QMK Firmware.')
  61. @automagic_keyboard
  62. @automagic_keymap
  63. def compile(cli):
  64. """Compile a QMK Firmware.
  65. If a Configurator export is supplied this command will create a new keymap, overwriting an existing keymap if one exists.
  66. If a keyboard and keymap are provided this command will build a firmware based on that.
  67. """
  68. envs = {'REQUIRE_PLATFORM_KEY': ''}
  69. silent = cli.config.compile.keyboard == 'all' or cli.config.compile.keyboard.startswith('all-') or cli.config.compile.keymap == 'all'
  70. # Setup the environment
  71. for env in cli.args.env:
  72. if '=' in env:
  73. key, value = env.split('=', 1)
  74. if key in envs:
  75. cli.log.warning('Overwriting existing environment variable %s=%s with %s=%s!', key, envs[key], key, value)
  76. envs[key] = value
  77. else:
  78. cli.log.warning('Invalid environment variable: %s', env)
  79. if cli.config.compile.keyboard.startswith('all-'):
  80. envs['REQUIRE_PLATFORM_KEY'] = cli.config.compile.keyboard[4:]
  81. # Run clean if necessary
  82. if cli.args.clean and not cli.args.filename and not cli.args.dry_run:
  83. for keyboard, keymap in keyboard_keymap_iter():
  84. cli.log.info('Cleaning previous build files for keyboard {fg_cyan}%s{fg_reset} keymap {fg_cyan}%s', keyboard, keymap)
  85. _, _, make_cmd = create_make_command(keyboard, keymap, 'clean', cli.config.compile.parallel, silent, **envs)
  86. cli.run(make_cmd, capture_output=False, stdin=DEVNULL)
  87. # Determine the compile command(s)
  88. commands = None
  89. if cli.args.filename:
  90. # If a configurator JSON was provided generate a keymap and compile it
  91. user_keymap = parse_configurator_json(cli.args.filename)
  92. commands = [compile_configurator_json(user_keymap, parallel=cli.config.compile.parallel, **envs)]
  93. elif cli.config.compile.keyboard and cli.config.compile.keymap:
  94. if cli.args.filter:
  95. cli.log.info('Generating the list of keyboards to compile, this may take some time.')
  96. commands = [create_make_command(keyboard, keymap, parallel=cli.config.compile.parallel, silent=silent, **envs) for keyboard, keymap in keyboard_keymap_iter()]
  97. elif not cli.config.compile.keyboard:
  98. cli.log.error('Could not determine keyboard!')
  99. elif not cli.config.compile.keymap:
  100. cli.log.error('Could not determine keymap!')
  101. # Compile the firmware, if we're able to
  102. if commands:
  103. returncodes = []
  104. for keyboard, keymap, command in commands:
  105. print()
  106. cli.log.info('Compiling QMK Firmware for keyboard {fg_cyan}%s{fg_reset} and keymap {fg_cyan}%s', keyboard, keymap)
  107. cli.log.debug('Running make command: {fg_blue}%s', ' '.join(command))
  108. if not cli.args.dry_run:
  109. compile = cli.run(command, capture_output=False)
  110. returncodes.append(compile.returncode)
  111. if compile.returncode == 0:
  112. cli.log.info('Success!')
  113. else:
  114. cli.log.error('Failed!')
  115. if any(returncodes):
  116. print()
  117. cli.log.error('Could not compile all targets, look above this message for more details. Failing target(s):')
  118. for i, returncode in enumerate(returncodes):
  119. if returncode != 0:
  120. keyboard, keymap, command = commands[i]
  121. cli.echo('\tkeyboard: {fg_cyan}%s{fg_reset} keymap: {fg_cyan}%s', keyboard, keymap)
  122. elif cli.args.filter:
  123. cli.log.error('No keyboards found after applying filter(s)!')
  124. return False
  125. else:
  126. cli.log.error('You must supply a configurator export, both `--keyboard` and `--keymap`, or be in a directory for a keyboard or keymap.')
  127. cli.print_help()
  128. return False