将 Bazel 输出提供给另一个 Bazel 规则

Feed Bazel output to another Bazel rule

我是 Bazel 的新手,很难找到解决方案:

假设我有这个 nodejs_binary 规则:

nodejs_binary(
    name = "js_scirpt",
    data = [
        "@npm//some_lib",
    ],
    entry_point = ":some_js_script.js",
)

现在我需要将 :js_script 的输出提供给执行其他操作的 go_test 规则。顺序很重要:nodejs 规则应该首先完成,然后 go_test 使用输出。

我认为这应该可以通过将 json 文件从 nodejs_binary 写入磁盘并从 some_js_script.js 读取它来实现,尽管我无法控制执行顺序并且我不知道如何将其传递给 go_test 规则。知道这是如何实现的(或者可能有更好的方法)吗?

我不太了解 nodejs_binarygo_test,但您可能想要的是通过 data 属性依赖于 nodejs 二进制文件的测试:
https://github.com/bazelbuild/rules_go/blob/master/go/core.rst#go-test
https://docs.bazel.build/versions/main/build-ref.html#data

go_test(
    name = "go_default_test",
    srcs = ["some_test.go"],
    data = [":js_script"],
)

js_scirpt会在go test构建之前构建,在测试执行时提供给测试

https://github.com/bazelbuild/rules_go#how-do-i-access-testdata

A dependency is the way to make one thing happen before another with Bazel. genrule 是 运行 命令并使输出可用的最简单方法。

将它们放在一起看起来像这样:

genrule(
    name = "run_js_script",
    tools = [
        ":js_script",
    ],
    outs = [
        "something.json",
    ],
    cmd = "$(location :js_script) --output $(location something.json)",
)

go_test(
    data = [
        ":something.json",
    ],
    [name, srcs, deps, etc]
)

Go 代码应使用 runfiles.go 查找文件路径。

此外,Node 代码应该使用命令行标志让目标写入其输出。如果它不能这样做,那么使用 shell 命令将输出移动到 $(location something.json).