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