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