由网友(虚伪丶演绎这段爱)分享简介:我需要将一些文件复制到二进制目录,同时保留它们的名称。到目前为止我得到的信息:filegroup(name = "resources",srcs = glob(["resources/*.*"]),)genrule(name = "copy_resources",srcs = ["//some/package:res...我需要将一些文件复制到二进制目录,同时保留它们的名称。到目前为止我得到的信息:
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
中指定文件名,但我似乎无法确定如何解析标签以获取实际的文件名。
推荐答案
要使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
位于我的项目目录树中的不同位置,我希望这些组的所有单个文件最终并排在将使用它们的测试二进制文件的runfiles
集合中。
我尝试使用genrule
执行此操作失败。
为了从多个filegroup
复制单个文件,保留每个文件的基本名称,但平整输出目录,必须在bzl
Bazel扩展名中创建自定义规则。
它在外壳命令中使用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。
相关推荐
最新文章