gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:41:56 28 4
gpt4 key购买 nike

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

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 中指定文件名,但我似乎不知道如何解析标签以获取实际的文件名。

最佳答案

要使文件组可用于二进制文件(使用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/”,以便从指定的文件组中查找文件。

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

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

<小时/>

挑战:

就我而言,我有几个文件组位于项目目录树的不同位置,并且我希望这些组的所有单独文件最终并排 在将使用它们的测试二进制文件的 runfiles 集合中。

<小时/>

我尝试使用 genrule 执行此操作但没有成功。

为了从多个文件组复制单个文件,保留每个文件的基本名称但展平输出目录,有必要在bzl bazel 扩展

值得庆幸的是,自定义规则相当简单。

它在 shell 命令中使用 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(),
},
)

使用它:

# inside the BUILD file of your exe
load(
"//your_project:copy_filegroups.bzl",
"copy_filegroups_to_this_package",
)

copy_filegroups_to_this_package(
name = "other_files_unnested",
# you can list more than one filegroup:
targeted_filegroups = ["//your_project/other/deeply/nested/library:other_test_files"],
)

cc_binary(
name = "hello-world",
srcs = ["hello-world.cc"],
data = [
":other_files_unnested",
],
)

您可以克隆 complete working example here .

关于Bazel:将多个文件复制到二进制目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38905256/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com