compilation_database.py 5.6 KB

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