diff options
| author | Bao <qubidt@gmail.com> | 2021-09-15 23:59:57 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-09-16 14:59:57 +1000 |
| commit | 590b405468fec906a51767a5cda4aa30ada5d52f (patch) | |
| tree | 0c907b8836440475e7b2800737800f4d50d81649 /lib/python/qmk/cli/generate | |
| parent | f7054522106644a5fd9ee58b5117a44b3209b7b2 (diff) | |
| download | qmk_firmware-590b405468fec906a51767a5cda4aa30ada5d52f.tar.gz qmk_firmware-590b405468fec906a51767a5cda4aa30ada5d52f.zip | |
New CLI subcommand to create clang-compatible compilation database (`compile_commands.json`) (#14370)
* pulled source from dev branch
* missed a file from origin
* formatting
* revised argument names. relaxed matching rules to work for avr too
* add docstrings
* added docs. tightened up regex
* remove unused imports
* cleaning up command file. use existing qmk dir constant
* rename parser library file
* move lib functions into command file. there are only 2 and they aren't large
* currently debugging...
* more robustly find config
* updated docs
* remove unused imports
* reuse make executable from the main make command
* pulled source from dev branch
* missed a file from origin
* formatting
* revised argument names. relaxed matching rules to work for avr too
* add docstrings
* added docs. tightened up regex
* remove unused imports
* cleaning up command file. use existing qmk dir constant
* rename parser library file
* move lib functions into command file. there are only 2 and they aren't large
* currently debugging...
* more robustly find config
* updated docs
* remove unused imports
* reuse make executable from the main make command
* remove MAKEFLAGS from environment for better control over process management
* Update .gitignore
Co-authored-by: Michael Forster <forster@google.com>
* add a usage line to docs
* doc change as suggested
Co-authored-by: Nick Brassel <nick@tzarc.org>
* rename command
* remove debug print statements
* generate-compilation-database: fix arg handling
* generate-comilation-db: improve error handling
* use cli.run() instead of Popen()
Co-authored-by: Xton <cdewan@apple.com>
Co-authored-by: Christon DeWan <cmdpix@mac.com>
Co-authored-by: Michael Forster <forster@google.com>
Co-authored-by: Nick Brassel <nick@tzarc.org>
Diffstat (limited to 'lib/python/qmk/cli/generate')
| -rwxr-xr-x | lib/python/qmk/cli/generate/compilation_database.py | 123 |
1 files changed, 123 insertions, 0 deletions
diff --git a/lib/python/qmk/cli/generate/compilation_database.py b/lib/python/qmk/cli/generate/compilation_database.py new file mode 100755 index 000000000..2748d96e7 --- /dev/null +++ b/lib/python/qmk/cli/generate/compilation_database.py | |||
| @@ -0,0 +1,123 @@ | |||
| 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 | ||
