compilation_database.py 4.9 KB

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