compilation_database.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. """Creates a compilation database for the given keyboard build.
  2. """
  3. import json
  4. import os
  5. import re
  6. import shlex
  7. import shutil
  8. from functools import lru_cache
  9. from pathlib import Path
  10. from typing import Dict, Iterator, List, Union
  11. from milc import cli, MILC
  12. from qmk.commands import create_make_command
  13. from qmk.constants import QMK_FIRMWARE
  14. from qmk.decorators import automagic_keyboard, automagic_keymap
  15. @lru_cache(maxsize=10)
  16. def system_libs(binary: str) -> List[Path]:
  17. """Find the system include directory that the given build tool uses.
  18. """
  19. cli.log.debug("searching for system library directory for binary: %s", binary)
  20. bin_path = shutil.which(binary)
  21. # Actually query xxxxxx-gcc to find its include paths.
  22. if binary.endswith("gcc") or binary.endswith("g++"):
  23. # (TODO): Remove 'stdin' once 'input' no longer causes issues under MSYS
  24. result = cli.run([binary, '-E', '-Wp,-v', '-'], capture_output=True, check=True, stdin=None, input='\n')
  25. paths = []
  26. for line in result.stderr.splitlines():
  27. if line.startswith(" "):
  28. paths.append(Path(line.strip()).resolve())
  29. return paths
  30. return list(Path(bin_path).resolve().parent.parent.glob("*/include")) if bin_path else []
  31. file_re = re.compile(r'printf "Compiling: ([^"]+)')
  32. cmd_re = re.compile(r'LOG=\$\((.+?)&&')
  33. def parse_make_n(f: Iterator[str]) -> List[Dict[str, str]]:
  34. """parse the output of `make -n <target>`
  35. This function makes many assumptions about the format of your build log.
  36. This happens to work right now for qmk.
  37. """
  38. state = 'start'
  39. this_file = None
  40. records = []
  41. for line in f:
  42. if state == 'start':
  43. m = file_re.search(line)
  44. if m:
  45. this_file = m.group(1)
  46. state = 'cmd'
  47. if state == 'cmd':
  48. assert this_file
  49. m = cmd_re.search(line)
  50. if m:
  51. # we have a hit!
  52. this_cmd = m.group(1)
  53. args = shlex.split(this_cmd)
  54. for s in system_libs(args[0]):
  55. args += ['-isystem', '%s' % s]
  56. new_cmd = ' '.join(shlex.quote(s) for s in args if s != '-mno-thumb-interwork')
  57. records.append({"directory": str(QMK_FIRMWARE.resolve()), "command": new_cmd, "file": this_file})
  58. state = 'start'
  59. return records
  60. @cli.argument('-kb', '--keyboard', help='The keyboard to build a firmware for. Ignored when a configurator export is supplied.')
  61. @cli.argument('-km', '--keymap', help='The keymap to build a firmware for. Ignored when a configurator export is supplied.')
  62. @cli.subcommand('Create a compilation database.')
  63. @automagic_keyboard
  64. @automagic_keymap
  65. def generate_compilation_database(cli: MILC) -> Union[bool, int]:
  66. """Creates a compilation database for the given keyboard build.
  67. Does a make clean, then a make -n for this target and uses the dry-run output to create
  68. a compilation database (compile_commands.json). This file can help some IDEs and
  69. IDE-like editors work better. For more information about this:
  70. https://clang.llvm.org/docs/JSONCompilationDatabase.html
  71. """
  72. command = None
  73. # check both config domains: the magic decorator fills in `generate_compilation_database` but the user is
  74. # more likely to have set `compile` in their config file.
  75. current_keyboard = cli.config.generate_compilation_database.keyboard or cli.config.user.keyboard
  76. current_keymap = cli.config.generate_compilation_database.keymap or cli.config.user.keymap
  77. if current_keyboard and current_keymap:
  78. # Generate the make command for a specific keyboard/keymap.
  79. command = create_make_command(current_keyboard, current_keymap, dry_run=True)
  80. elif not current_keyboard:
  81. cli.log.error('Could not determine keyboard!')
  82. elif not current_keymap:
  83. cli.log.error('Could not determine keymap!')
  84. if not command:
  85. cli.log.error('You must supply both `--keyboard` and `--keymap`, or be in a directory for a keyboard or keymap.')
  86. cli.echo('usage: qmk compiledb [-kb KEYBOARD] [-km KEYMAP]')
  87. return False
  88. # remove any environment variable overrides which could trip us up
  89. env = os.environ.copy()
  90. env.pop("MAKEFLAGS", None)
  91. # re-use same executable as the main make invocation (might be gmake)
  92. clean_command = [command[0], 'clean']
  93. cli.log.info('Making clean with {fg_cyan}%s', ' '.join(clean_command))
  94. cli.run(clean_command, capture_output=False, check=True, env=env)
  95. cli.log.info('Gathering build instructions from {fg_cyan}%s', ' '.join(command))
  96. result = cli.run(command, capture_output=True, check=True, env=env)
  97. db = parse_make_n(result.stdout.splitlines())
  98. if not db:
  99. cli.log.error("Failed to parse output from make output:\n%s", result.stdout)
  100. return False
  101. cli.log.info("Found %s compile commands", len(db))
  102. dbpath = QMK_FIRMWARE / 'compile_commands.json'
  103. cli.log.info(f"Writing build database to {dbpath}")
  104. dbpath.write_text(json.dumps(db, indent=4))
  105. return True