Skip to content

Commit 13e0812

Browse files
baodrateXtonxtonMForstertzarc
authored andcommitted
New CLI subcommand to create clang-compatible compilation database (compile_commands.json) (qmk#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 <[email protected]> * add a usage line to docs * doc change as suggested Co-authored-by: Nick Brassel <[email protected]> * 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 <[email protected]> Co-authored-by: Christon DeWan <[email protected]> Co-authored-by: Michael Forster <[email protected]> Co-authored-by: Nick Brassel <[email protected]>
1 parent 0deb1e4 commit 13e0812

File tree

5 files changed

+166
-4
lines changed

5 files changed

+166
-4
lines changed

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,3 +86,8 @@ __pycache__
8686

8787
# Allow to exist but don't include it in the repo
8888
user_song_list.h
89+
90+
# clangd
91+
compile_commands.json
92+
.clangd/
93+
.cache/

docs/cli_commands.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,33 @@ qmk format-c
320320
qmk format-c -b branch_name
321321
```
322322

323+
## `qmk generate-compilation-database`
324+
325+
**Usage**:
326+
327+
```
328+
qmk generate-compilation-database [-kb KEYBOARD] [-km KEYMAP]
329+
```
330+
331+
Creates a `compile_commands.json` file.
332+
333+
Does your IDE/editor use a language server but doesn't _quite_ find all the necessary include files? Do you hate red squigglies? Do you wish your editor could figure out `#include QMK_KEYBOARD_H`? You might need a [compilation database](https://clang.llvm.org/docs/JSONCompilationDatabase.html)! The qmk tool can build this for you.
334+
335+
This command needs to know which keyboard and keymap to build. It uses the same configuration options as the `qmk compile` command: arguments, current directory, and config files.
336+
337+
**Example:**
338+
339+
```
340+
$ cd ~/qmk_firmware/keyboards/gh60/satan/keymaps/colemak
341+
$ qmk generate-compilation-database
342+
Ψ Making clean
343+
Ψ Gathering build instructions from make -n gh60/satan:colemak
344+
Ψ Found 50 compile commands
345+
Ψ Writing build database to /Users/you/src/qmk_firmware/compile_commands.json
346+
```
347+
348+
Now open your dev environment and live a squiggly-free life.
349+
323350
## `qmk docs`
324351

325352
This command starts a local HTTP server which you can use for browsing or improving the docs. Default port is 8936.

lib/python/qmk/cli/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
'qmk.cli.format.python',
4646
'qmk.cli.format.text',
4747
'qmk.cli.generate.api',
48+
'qmk.cli.generate.compilation_database',
4849
'qmk.cli.generate.config_h',
4950
'qmk.cli.generate.dfu_header',
5051
'qmk.cli.generate.docs',
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

lib/python/qmk/commands.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,17 @@ def _find_make():
2828
return make_cmd
2929

3030

31-
def create_make_target(target, parallel=1, **env_vars):
31+
def create_make_target(target, dry_run=False, parallel=1, **env_vars):
3232
"""Create a make command
3333
3434
Args:
3535
3636
target
3737
Usually a make rule, such as 'clean' or 'all'.
3838
39+
dry_run
40+
make -n -- don't actually build
41+
3942
parallel
4043
The number of make jobs to run in parallel
4144
@@ -52,10 +55,10 @@ def create_make_target(target, parallel=1, **env_vars):
5255
for key, value in env_vars.items():
5356
env.append(f'{key}={value}')
5457

55-
return [make_cmd, *get_make_parallel_args(parallel), *env, target]
58+
return [make_cmd, *(['-n'] if dry_run else []), *get_make_parallel_args(parallel), *env, target]
5659

5760

58-
def create_make_command(keyboard, keymap, target=None, parallel=1, **env_vars):
61+
def create_make_command(keyboard, keymap, target=None, dry_run=False, parallel=1, **env_vars):
5962
"""Create a make compile command
6063
6164
Args:
@@ -69,6 +72,9 @@ def create_make_command(keyboard, keymap, target=None, parallel=1, **env_vars):
6972
target
7073
Usually a bootloader.
7174
75+
dry_run
76+
make -n -- don't actually build
77+
7278
parallel
7379
The number of make jobs to run in parallel
7480
@@ -84,7 +90,7 @@ def create_make_command(keyboard, keymap, target=None, parallel=1, **env_vars):
8490
if target:
8591
make_args.append(target)
8692

87-
return create_make_target(':'.join(make_args), parallel, **env_vars)
93+
return create_make_target(':'.join(make_args), dry_run=dry_run, parallel=parallel, **env_vars)
8894

8995

9096
def get_git_version(current_time, repo_dir='.', check_dir='.'):

0 commit comments

Comments
 (0)