packages feed

cabal-buck2-0.6.0.0: buck2/prelude/cxx/tools/compilation_database.bxl

# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is dual-licensed under either the MIT license found in the
# LICENSE-MIT file in the root directory of this source tree or the Apache
# License, Version 2.0 found in the LICENSE-APACHE file in the root directory
# of this source tree. You may select, at your option, one of the
# above-listed licenses.

load("@prelude//cxx:comp_db.bzl", "CxxCompilationDbInfo")
load("@prelude//cxx:compile_types.bzl", "CxxSrcCompileCommand")
load("@prelude//utils:utils.bzl", "flatten")

def _make_entry(ctx: bxl.Context, target: Label, compile_command: CxxSrcCompileCommand, add_target_name: bool) -> dict:
    args = compile_command.cxx_compile_cmd.base_compile_cmd.copy()
    args.add(compile_command.cxx_compile_cmd.argsfile.cmd_form)
    args.add(compile_command.args)
    ctx.output.ensure_multiple(args)

    result = {
        "arguments": args,
        "directory": ctx.fs.abs_path_unsafe(ctx.root()),
        "file": compile_command.src,
    }

    if add_target_name:
        result["target"] = target.configured_target().raw_target()

    return result

def _impl(ctx: bxl.Context):
    targets = ctx.configured_targets(flatten(ctx.cli_args.targets), modifiers = ctx.modifiers)
    if ctx.cli_args.recursive:
        targets = ctx.cquery().deps(targets)

    actions = ctx.bxl_actions().actions

    db = []
    for name, target in ctx.analysis(targets).items():
        comp_db_info = target.providers().get(CxxCompilationDbInfo)
        if comp_db_info:
            for cc in comp_db_info.info.values():
                if ctx.cli_args.include_headers or (not cc.is_header):
                    db.append(_make_entry(ctx, name, cc, ctx.cli_args.add_target_name))

    db_file = actions.declare_output("compile_commands.json", has_content_based_path = False)
    actions.write_json(db_file.as_output(), db, with_inputs = True, pretty = True)
    ctx.output.print(ctx.output.ensure(db_file))

generate = bxl_main(
    doc = "Generate a compilation database for a set of targets and print its path to stdout",
    impl = _impl,
    cli_args = {
        "add-target-name": cli_args.bool(
            default = False,
            doc = "Include the name of the target in the compilation database entries (non-standard)",
        ),
        "include-headers": cli_args.bool(
            default = True,
            doc = "Include header file compilation db actions",
        ),
        "recursive": cli_args.bool(
            default = False,
            doc = "Automatically include all dependent targets in the generated compilation db",
        ),
        "targets": cli_args.list(
            cli_args.configured_target_expr(),
            doc = "Targets to generate the database for",
        ),
    },
)