compilation_database.py 5.5 KB

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