[英]How to use genrule output as string to expand_template substitutions in Bazel?
似乎genrule只能輸出一個Target,而expand_template替換只接受string_dict,我如何使用genrule輸出來擴展?
gen.bzl
def _expand_impl(ctx):
ctx.actions.expand_template(
template = ctx.file._template,
output = ctx.outputs.source_file,
substitutions = {
"{version}": ctx.attr.version,
}
)
expand = rule(
implementation = _expand_impl,
attrs = {
"version": attr.string(mandatory = True),
"_template": attr.label(
default = Label("//version:local.go.in"),
allow_single_file = True,
),
},
outputs = {"source_file": "local.go"},
)
建立
load("@io_bazel_rules_go//go:def.bzl", "go_library")
filegroup(
name = "templates",
srcs = ["local.go.in"],
)
genrule(
name = "inject",
outs = ["VERSION"],
local = 1,
cmd = "git rev-parse HEAD",
)
load(":gen.bzl", "expand")
expand(
name = "expand",
version = ":inject",
)
go_library(
name = "go_default_library",
srcs = [
"default.go",
":expand", # Keep
],
importpath = "go.megvii-inc.com/brain/data/version",
visibility = ["//visibility:public"],
)
和local.go.in
package version
func init() {
V = "{version}"
}
我希望local.go.in中的{version}可以被git rev-parse HEAD
輸出替換。
這里的問題是ctx.actions.expand_template()
的substitutions
參數必須在分析階段(即運行_expand_impl
時) _expand_impl
,這發生在_expand_impl
的git rev-parse HEAD
命令運行之前(即,在執行階段)。
有幾種方法可以做到這一點。 最簡單的是在genrule中做所有事情:
genrule(
name = "gen_local_go",
srcs = ["local.go.in"],
outs = ["local.go"],
local = 1,
cmd = 'sed "s/{VERSION}/$(git rev-parse HEAD)/" "$<" > "$@"',
)
這取決於主機上可用的sed
,但是任何其他類型的程序都可以輸入一個文件,修改文本並將其輸出到另一個文件。
另一種選擇是使用--workspace_status_command的組合這里有更多細節: 如何在分析時在bazel中運行shell命令? 這種方法的優點是它避免了本地規則。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.