Bazel:将多个文件复制到二进制目录

时间:2016-08-11 20:09:50

标签: bazel

我需要将一些文件复制到二进制目录,同时保留它们的名称。到目前为止我得到了什么:

filegroup(
    name = "resources",
    srcs = glob(["resources/*.*"]),
)

genrule(
    name = "copy_resources",
    srcs = ["//some/package:resources"],
    outs = [ ],
    cmd = "cp $(SRCS) $(@D)",
    local = 1,
    output_to_bindir = 1,
)

现在我必须在outs中指定文件名,但我似乎无法弄清楚如何解析标签以获取实际的文件名。

1 个答案:

答案 0 :(得分:3)

要使filegroup可用于二进制文件(使用bazel run执行)或测试(使用bazel test执行时)通常将filegroup列为一部分二进制文件data的格式,如下所示:

cc_binary(
    name = "hello-world",
    srcs = ["hello-world.cc"],
    data = [
        "//your_project/other/deeply/nested/resources:other_test_files",
    ],
)
# known to work at least as of bazel version 0.22.0

通常以上条件就足够了。

但是,可执行文件随后必须遍历目录结构"other/deeply/nested/resources/",以便从指示的filegroup中查找文件。

换句话说,当填充可执行文件的runfiles时,bazel保留从WORKSPACE根到所有包含给定filegroup的包的目录嵌套。

有时候,这种保留的目录嵌套是不可取的。


挑战:

就我而言,我在项目目录树的各个位置上有多个filegroup,我希望这些组中的所有单个文件都以 byside-by-side 将使用它们的测试二进制文件的runfiles集合中。


我尝试使用genrule进行此操作失败。

为了从多个filegroup复制单个文件,保留每个文件的基本名称,但变平输出目录,有必要在{{1中创建自定义规则 }}

值得庆幸的是,自定义规则非常简单。

它在shell命令中使用bzl,就像原始问题中列出的未完成的cp一样。

扩展文件:

genrule

使用它:

# contents of a file you create named: copy_filegroups.bzl
# known to work in bazel version 0.22.0
def _copy_filegroup_impl(ctx):
    all_input_files = [
        f for t in ctx.attr.targeted_filegroups for f in t.files
    ]

    all_outputs = []
    for f in all_input_files:
        out = ctx.actions.declare_file(f.basename)
        all_outputs += [out]
        ctx.actions.run_shell(
            outputs=[out],
            inputs=depset([f]),
            arguments=[f.path, out.path],
            # This is what we're all about here. Just a simple 'cp' command.
            # Copy the input to CWD/f.basename, where CWD is the package where
            # the copy_filegroups_to_this_package rule is invoked.
            # (To be clear, the files aren't copied right to where your BUILD
            # file sits in source control. They are copied to the 'shadow tree'
            # parallel location under `bazel info bazel-bin`)
            command="cp $1 $2")

    # Small sanity check
    if len(all_input_files) != len(all_outputs):
        fail("Output count should be 1-to-1 with input count.")

    return [
        DefaultInfo(
            files=depset(all_outputs),
            runfiles=ctx.runfiles(files=all_outputs))
    ]


copy_filegroups_to_this_package = rule(
    implementation=_copy_filegroup_impl,
    attrs={
        "targeted_filegroups": attr.label_list(),
    },
)

您可以克隆complete working example here