如何从bazel sh_binary调用bash函数?



我想从sh_binary调用bash函数,但不知道如何调用。

我有bash脚本与函数调用:

mybashfunction.sh

function a () {
echo a
}
function b () {
echo b
}

BUILD.bazel

sh_binary(
name = "a",
srcs = ["mybashfunction.sh"],
args = [
"a",
],
visibility = ["//visibility:public"],
)

下面的命令不调用bash函数:

bazel run //test:a

的回报:

INFO: Analyzed target //test:a (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
Target //test:a up-to-date:
bazel-bin/test/a
INFO: Elapsed time: 0.148s, Critical Path: 0.00s
INFO: 1 process: 1 internal.
INFO: Build completed successfully, 1 total action
INFO: Build completed successfully, 1 total action

我能使它工作的唯一方法是从另一个脚本调用函数:

a.sh

source ./test/mybashfunction.sh
a

BUILD.bazel

sh_binary(
name = "a",
srcs = ["a.sh"],
data = [
"mybashfunction.sh",
],
visibility = ["//visibility:public"],
)

输出:

bazel run //test:a
INFO: Analyzed target //test:a (1 packages loaded, 3 targets configured).
INFO: Found 1 target...
Target //test:a up-to-date:
bazel-bin/test/a
INFO: Elapsed time: 0.192s, Critical Path: 0.02s
INFO: 4 processes: 4 internal.
INFO: Build completed successfully, 4 total actions
INFO: Build completed successfully, 4 total actions
a

不是最干净的方法,但一个可能的解决方案是扩展脚本以接受作为参数运行的函数,例如

function a () {
echo a
}
function b () {
echo b
}
if [ ! -z "$1" ]; then
$1
fi

由于您将参数传递给BUILD文件中的脚本,因此这应该触发对函数的调用:

sh_binary(
name = "a",
srcs = ["mybashfunction.sh"],
args = [
"a",
],
visibility = ["//visibility:public"],
)
sh_binary(
name = "b",
srcs = ["mybashfunction.sh"],
args = [
"b",
],
visibility = ["//visibility:public"],
)
$> bazel run :a
...
INFO: Build completed successfully, 1 total action
a
$> bazel run :b
...
INFO: Build completed successfully, 1 total action
b