mass_compile.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. """Compile all keyboards.
  2. This will compile everything in parallel, for testing purposes.
  3. """
  4. import os
  5. from typing import List
  6. from pathlib import Path
  7. from subprocess import DEVNULL
  8. from milc import cli
  9. import shlex
  10. from qmk.constants import QMK_FIRMWARE
  11. from qmk.commands import find_make, get_make_parallel_args, build_environment
  12. from qmk.search import search_keymap_targets, search_make_targets
  13. from qmk.build_targets import BuildTarget, JsonKeymapBuildTarget
  14. from qmk.util import maybe_exit_config
  15. def mass_compile_targets(targets: List[BuildTarget], clean: bool, dry_run: bool, no_temp: bool, parallel: int, print_failures: bool, **env):
  16. if len(targets) == 0:
  17. return
  18. os.environ.setdefault('SKIP_SCHEMA_VALIDATION', '1')
  19. make_cmd = find_make()
  20. builddir = Path(QMK_FIRMWARE) / '.build'
  21. makefile = builddir / 'parallel_kb_builds.mk'
  22. if dry_run:
  23. cli.log.info('Compilation targets:')
  24. for target in sorted(targets, key=lambda t: (t.keyboard, t.keymap)):
  25. extra_args = ' '.join([f"-e {shlex.quote(f'{k}={v}')}" for k, v in target.extra_args.items()])
  26. cli.log.info(f"{{fg_cyan}}qmk compile -kb {target.keyboard} -km {target.keymap} {extra_args}{{fg_reset}}")
  27. else:
  28. if clean:
  29. cli.run([make_cmd, 'clean'], capture_output=False, stdin=DEVNULL)
  30. builddir.mkdir(parents=True, exist_ok=True)
  31. with open(makefile, "w") as f:
  32. # yapf: disable
  33. f.write(
  34. f"""\
  35. # This file is auto-generated by qmk mass-compile
  36. # Do not edit this file directly.
  37. all: print_failures
  38. .PHONY: all_targets print_failures
  39. print_failures: all_targets
  40. """# noqa
  41. )
  42. if print_failures:
  43. f.write(
  44. f"""\
  45. @for f in $$(ls .build/failed.log.{os.getpid()}.* 2>/dev/null | sort); do \\
  46. echo; \\
  47. echo "======================================================================================"; \\
  48. echo "Failed build log: $$f"; \\
  49. echo "------------------------------------------------------"; \\
  50. cat $$f; \\
  51. echo "------------------------------------------------------"; \\
  52. done
  53. """# noqa
  54. )
  55. # yapf: enable
  56. for target in sorted(targets, key=lambda t: (t.keyboard, t.keymap)):
  57. keyboard_name = target.keyboard
  58. keymap_name = target.keymap
  59. keyboard_safe = keyboard_name.replace('/', '_')
  60. target_filename = target.target_name(**env)
  61. target.configure(parallel=1) # We ignore parallelism on a per-build basis as we defer to the parent make invocation
  62. target.prepare_build(**env) # If we've got json targets, allow them to write out any extra info to .build before we kick off `make`
  63. command = target.compile_command(**env)
  64. command[0] = '+@$(MAKE)' # Override the make so that we can use jobserver to handle parallelism
  65. extra_args = '_'.join([f"{k}_{v}" for k, v in target.extra_args.items()])
  66. build_log = f"{QMK_FIRMWARE}/.build/build.log.{os.getpid()}.{keyboard_safe}.{keymap_name}"
  67. failed_log = f"{QMK_FIRMWARE}/.build/failed.log.{os.getpid()}.{keyboard_safe}.{keymap_name}"
  68. target_suffix = ''
  69. if len(extra_args) > 0:
  70. build_log += f".{extra_args}"
  71. failed_log += f".{extra_args}"
  72. target_suffix = f"_{extra_args}"
  73. # yapf: disable
  74. f.write(
  75. f"""\
  76. .PHONY: {target_filename}{target_suffix}_binary
  77. all_targets: {target_filename}{target_suffix}_binary
  78. {target_filename}{target_suffix}_binary:
  79. @rm -f "{build_log}" || true
  80. @echo "Compiling QMK Firmware for target: '{keyboard_name}:{keymap_name}'..." >>"{build_log}"
  81. {' '.join(command)} \\
  82. >>"{build_log}" 2>&1 \\
  83. || cp "{build_log}" "{failed_log}"
  84. @{{ grep '\\[ERRORS\\]' "{build_log}" >/dev/null 2>&1 && printf "Build %-64s \\e[1;31m[ERRORS]\\e[0m\\n" "{keyboard_name}:{keymap_name}" ; }} \\
  85. || {{ grep '\\[WARNINGS\\]' "{build_log}" >/dev/null 2>&1 && printf "Build %-64s \\e[1;33m[WARNINGS]\\e[0m\\n" "{keyboard_name}:{keymap_name}" ; }} \\
  86. || printf "Build %-64s \\e[1;32m[OK]\\e[0m\\n" "{keyboard_name}:{keymap_name}"
  87. @rm -f "{build_log}" || true
  88. """# noqa
  89. )
  90. # yapf: enable
  91. if no_temp:
  92. # yapf: disable
  93. f.write(
  94. f"""\
  95. @rm -rf "{QMK_FIRMWARE}/.build/{target_filename}.elf" 2>/dev/null || true
  96. @rm -rf "{QMK_FIRMWARE}/.build/{target_filename}.map" 2>/dev/null || true
  97. @rm -rf "{QMK_FIRMWARE}/.build/obj_{target_filename}" || true
  98. """# noqa
  99. )
  100. # yapf: enable
  101. f.write('\n')
  102. cli.run([find_make(), *get_make_parallel_args(parallel), '-f', makefile.as_posix(), 'all'], capture_output=False, stdin=DEVNULL)
  103. # Check for failures
  104. failures = [f for f in builddir.glob(f'failed.log.{os.getpid()}.*')]
  105. if len(failures) > 0:
  106. return False
  107. @cli.argument('builds', nargs='*', arg_only=True, help="List of builds in form <keyboard>:<keymap> to compile in parallel. Specifying this overrides all other target search options.")
  108. @cli.argument('-t', '--no-temp', arg_only=True, action='store_true', help="Remove temporary files during build.")
  109. @cli.argument('-j', '--parallel', type=int, default=1, help="Set the number of parallel make jobs; 0 means unlimited.")
  110. @cli.argument('-c', '--clean', arg_only=True, action='store_true', help="Remove object files before compiling.")
  111. @cli.argument('-n', '--dry-run', arg_only=True, action='store_true', help="Don't actually build, just show the commands to be run.")
  112. @cli.argument('-p', '--print-failures', arg_only=True, action='store_true', help="Print failed builds.")
  113. @cli.argument(
  114. '-f',
  115. '--filter',
  116. arg_only=True,
  117. action='append',
  118. default=[],
  119. help= # noqa: `format-python` and `pytest` don't agree here.
  120. "Filter the list of keyboards based on the supplied value in rules.mk. Matches info.json structure, and accepts the formats 'features.rgblight=true' or 'exists(matrix_pins.direct)'. May be passed multiple times, all filters need to match. Value may include wildcards such as '*' and '?'." # noqa: `format-python` and `pytest` don't agree here.
  121. )
  122. @cli.argument('-km', '--keymap', type=str, default='default', help="The keymap name to build. Default is 'default'.")
  123. @cli.argument('-e', '--env', arg_only=True, action='append', default=[], help="Set a variable to be passed to make. May be passed multiple times.")
  124. @cli.subcommand('Compile QMK Firmware for all keyboards.', hidden=False if cli.config.user.developer else True)
  125. def mass_compile(cli):
  126. """Compile QMK Firmware against all keyboards.
  127. """
  128. maybe_exit_config(should_exit=False, should_reraise=True)
  129. if len(cli.args.builds) > 0:
  130. json_like_targets = list([Path(p) for p in filter(lambda e: Path(e).exists() and Path(e).suffix == '.json', cli.args.builds)])
  131. make_like_targets = list(filter(lambda e: Path(e) not in json_like_targets, cli.args.builds))
  132. targets = search_make_targets(make_like_targets)
  133. targets.extend([JsonKeymapBuildTarget(e) for e in json_like_targets])
  134. else:
  135. targets = search_keymap_targets([('all', cli.config.mass_compile.keymap)], cli.args.filter)
  136. return mass_compile_targets(targets, cli.args.clean, cli.args.dry_run, cli.args.no_temp, cli.config.mass_compile.parallel, cli.args.print_failures, **build_environment(cli.args.env))