2021-09-16 06:59:57 +02:00
|
|
|
"""Creates a compilation database for the given keyboard build.
|
|
|
|
"""
|
|
|
|
|
|
|
|
import json
|
|
|
|
import os
|
|
|
|
import re
|
|
|
|
import shlex
|
|
|
|
import shutil
|
|
|
|
from functools import lru_cache
|
|
|
|
from pathlib import Path
|
|
|
|
from typing import Dict, Iterator, List, Union
|
|
|
|
|
|
|
|
from milc import cli, MILC
|
|
|
|
|
2023-11-15 06:24:54 +01:00
|
|
|
from qmk.commands import find_make
|
2021-09-16 06:59:57 +02:00
|
|
|
from qmk.constants import QMK_FIRMWARE
|
|
|
|
from qmk.decorators import automagic_keyboard, automagic_keymap
|
2023-04-09 18:41:30 +02:00
|
|
|
from qmk.keyboard import keyboard_completer, keyboard_folder
|
|
|
|
from qmk.keymap import keymap_completer
|
2021-09-16 06:59:57 +02:00
|
|
|
|
|
|
|
|
|
|
|
@lru_cache(maxsize=10)
|
|
|
|
def system_libs(binary: str) -> List[Path]:
|
|
|
|
"""Find the system include directory that the given build tool uses.
|
|
|
|
"""
|
|
|
|
cli.log.debug("searching for system library directory for binary: %s", binary)
|
|
|
|
bin_path = shutil.which(binary)
|
2021-09-20 06:15:07 +02:00
|
|
|
|
|
|
|
# Actually query xxxxxx-gcc to find its include paths.
|
|
|
|
if binary.endswith("gcc") or binary.endswith("g++"):
|
2021-12-29 22:35:35 +01:00
|
|
|
# (TODO): Remove 'stdin' once 'input' no longer causes issues under MSYS
|
|
|
|
result = cli.run([binary, '-E', '-Wp,-v', '-'], capture_output=True, check=True, stdin=None, input='\n')
|
2021-09-20 06:15:07 +02:00
|
|
|
paths = []
|
|
|
|
for line in result.stderr.splitlines():
|
|
|
|
if line.startswith(" "):
|
|
|
|
paths.append(Path(line.strip()).resolve())
|
|
|
|
return paths
|
|
|
|
|
2021-09-16 06:59:57 +02:00
|
|
|
return list(Path(bin_path).resolve().parent.parent.glob("*/include")) if bin_path else []
|
|
|
|
|
|
|
|
|
|
|
|
file_re = re.compile(r'printf "Compiling: ([^"]+)')
|
|
|
|
cmd_re = re.compile(r'LOG=\$\((.+?)&&')
|
|
|
|
|
|
|
|
|
|
|
|
def parse_make_n(f: Iterator[str]) -> List[Dict[str, str]]:
|
|
|
|
"""parse the output of `make -n <target>`
|
|
|
|
|
|
|
|
This function makes many assumptions about the format of your build log.
|
|
|
|
This happens to work right now for qmk.
|
|
|
|
"""
|
|
|
|
|
|
|
|
state = 'start'
|
|
|
|
this_file = None
|
|
|
|
records = []
|
|
|
|
for line in f:
|
|
|
|
if state == 'start':
|
|
|
|
m = file_re.search(line)
|
|
|
|
if m:
|
|
|
|
this_file = m.group(1)
|
|
|
|
state = 'cmd'
|
|
|
|
|
|
|
|
if state == 'cmd':
|
|
|
|
assert this_file
|
|
|
|
m = cmd_re.search(line)
|
|
|
|
if m:
|
|
|
|
# we have a hit!
|
|
|
|
this_cmd = m.group(1)
|
|
|
|
args = shlex.split(this_cmd)
|
2021-09-20 06:15:07 +02:00
|
|
|
for s in system_libs(args[0]):
|
|
|
|
args += ['-isystem', '%s' % s]
|
2021-09-16 06:59:57 +02:00
|
|
|
new_cmd = ' '.join(shlex.quote(s) for s in args if s != '-mno-thumb-interwork')
|
|
|
|
records.append({"directory": str(QMK_FIRMWARE.resolve()), "command": new_cmd, "file": this_file})
|
|
|
|
state = 'start'
|
|
|
|
|
|
|
|
return records
|
|
|
|
|
|
|
|
|
2023-11-15 06:24:54 +01:00
|
|
|
def write_compilation_database(keyboard: str = None, keymap: str = None, output_path: Path = QMK_FIRMWARE / 'compile_commands.json', skip_clean: bool = False, command: List[str] = None, **env_vars) -> bool:
|
2023-09-28 12:48:58 +02:00
|
|
|
# Generate the make command for a specific keyboard/keymap.
|
2023-11-15 06:24:54 +01:00
|
|
|
if not command:
|
|
|
|
from qmk.build_targets import KeyboardKeymapBuildTarget # Lazy load due to circular references
|
|
|
|
target = KeyboardKeymapBuildTarget(keyboard, keymap)
|
|
|
|
command = target.compile_command(dry_run=True, **env_vars)
|
2021-09-16 06:59:57 +02:00
|
|
|
|
|
|
|
if not command:
|
|
|
|
cli.log.error('You must supply both `--keyboard` and `--keymap`, or be in a directory for a keyboard or keymap.')
|
2023-04-09 18:41:30 +02:00
|
|
|
cli.echo('usage: qmk generate-compilation-database [-kb KEYBOARD] [-km KEYMAP]')
|
2021-09-16 06:59:57 +02:00
|
|
|
return False
|
|
|
|
|
|
|
|
# remove any environment variable overrides which could trip us up
|
|
|
|
env = os.environ.copy()
|
|
|
|
env.pop("MAKEFLAGS", None)
|
|
|
|
|
|
|
|
# re-use same executable as the main make invocation (might be gmake)
|
2023-11-15 06:24:54 +01:00
|
|
|
if not skip_clean:
|
|
|
|
clean_command = [find_make(), "clean"]
|
|
|
|
cli.log.info('Making clean with {fg_cyan}%s', ' '.join(clean_command))
|
|
|
|
cli.run(clean_command, capture_output=False, check=True, env=env)
|
2021-09-16 06:59:57 +02:00
|
|
|
|
|
|
|
cli.log.info('Gathering build instructions from {fg_cyan}%s', ' '.join(command))
|
|
|
|
|
|
|
|
result = cli.run(command, capture_output=True, check=True, env=env)
|
|
|
|
db = parse_make_n(result.stdout.splitlines())
|
|
|
|
if not db:
|
|
|
|
cli.log.error("Failed to parse output from make output:\n%s", result.stdout)
|
|
|
|
return False
|
|
|
|
|
|
|
|
cli.log.info("Found %s compile commands", len(db))
|
|
|
|
|
2023-09-28 12:48:58 +02:00
|
|
|
cli.log.info(f"Writing build database to {output_path}")
|
|
|
|
output_path.write_text(json.dumps(db, indent=4))
|
2021-09-16 06:59:57 +02:00
|
|
|
|
|
|
|
return True
|
2023-09-28 12:48:58 +02:00
|
|
|
|
|
|
|
|
|
|
|
@cli.argument('-kb', '--keyboard', type=keyboard_folder, completer=keyboard_completer, help='The keyboard\'s name')
|
|
|
|
@cli.argument('-km', '--keymap', completer=keymap_completer, help='The keymap\'s name')
|
|
|
|
@cli.subcommand('Create a compilation database.')
|
|
|
|
@automagic_keyboard
|
|
|
|
@automagic_keymap
|
|
|
|
def generate_compilation_database(cli: MILC) -> Union[bool, int]:
|
|
|
|
"""Creates a compilation database for the given keyboard build.
|
|
|
|
|
|
|
|
Does a make clean, then a make -n for this target and uses the dry-run output to create
|
|
|
|
a compilation database (compile_commands.json). This file can help some IDEs and
|
|
|
|
IDE-like editors work better. For more information about this:
|
|
|
|
|
|
|
|
https://clang.llvm.org/docs/JSONCompilationDatabase.html
|
|
|
|
"""
|
|
|
|
# check both config domains: the magic decorator fills in `generate_compilation_database` but the user is
|
|
|
|
# more likely to have set `compile` in their config file.
|
|
|
|
current_keyboard = cli.config.generate_compilation_database.keyboard or cli.config.user.keyboard
|
|
|
|
current_keymap = cli.config.generate_compilation_database.keymap or cli.config.user.keymap
|
|
|
|
|
|
|
|
if not current_keyboard:
|
|
|
|
cli.log.error('Could not determine keyboard!')
|
|
|
|
elif not current_keymap:
|
|
|
|
cli.log.error('Could not determine keymap!')
|
|
|
|
|
|
|
|
return write_compilation_database(current_keyboard, current_keymap, QMK_FIRMWARE / 'compile_commands.json')
|