Bazel:为什么 lint 无法获取变量引用?

Bazel: why lint failed for variable reference?

我在 BUILD 文件中有这个 genrule,但是 bazel 构建失败,错误为:

in cmd attribute of genrule rule //example:create_version_pom: $(BUILD_TAG) not defined

genrule(
    name = "create_version_pom",
    srcs = ["pom_template.xml"],
    outs = ["version_pom.xml"],
    cmd = "sed 's/BUILD_TAG/$(BUILD_TAG)/g' $< > $@",
)

请问是什么原因,如何解决?

genrulecmd属性会在命令执行前对Bazel构建变量做变量扩展。输入文件和输出文件的 $<$@ 变量是一些预定义的变量。可以用--define定义变量,例如:

$ cat BUILD
genrule(
  name = "genfoo",
  outs = ["foo"],
  cmd = "echo $(bar) > $@",
)

$ bazel build foo --define=bar=123
INFO: Analyzed target //:foo (5 packages loaded, 8 targets configured).
INFO: Found 1 target...
Target //:foo up-to-date:
  bazel-bin/foo
INFO: Elapsed time: 0.310s, Critical Path: 0.01s
INFO: 2 processes: 1 internal, 1 linux-sandbox.
INFO: Build completed successfully, 2 total actions

$ cat bazel-bin/foo
123

所以要让 $(BUILD_TAG) 在 genrule 中工作,你需要通过
--define=BUILD_TAG=the_build_tag

除非你想把 BUILD_TAG 替换成字面上的 $(BUILD_TAG),在这种情况下 $ 需要用另一个 $ 转义:$$(BUILD_TAG) .


https://docs.bazel.build/versions/main/be/general.html#genrule.cmd
https://docs.bazel.build/versions/main/be/make-variables.html

请注意,Bazel 还具有“构建标记”机制,用于将构建时间和版本号等信息带入构建中:
https://docs.bazel.build/versions/main/user-manual.html#workspace_status
https://docs.bazel.build/versions/main/command-line-reference.html#flag--embed_label

不过使用 --workspace_status_command--embed_label 有点复杂。