编译单一平台:
# BUILD
load("@io_bazel_rules_go//go:def.bzl", "go_binary")
go_binary(
name = 'example',
srcs = glob(["src/*.go"]),
)
虽然编译可以正常进行,但如果我想编译多个平台,只能用以下方法:
bazel build --platforms=@io_bazel_rules_go//go/toolchain:linux_amd64 //:example
bazel build --platforms=@io_bazel_rules_go//go/toolchain:linux_386 //:example
bazel build --platforms=@io_bazel_rules_go//go/toolchain:windows_amd64 //:example
bazel build --platforms=@io_bazel_rules_go//go/toolchain:darwin_amd64 //:example
我希望一次编译多个平台的目标,所以我尝试了这个:
# BUILD
load("//:matrix.bzl", "build_all_platform")
build_all_platform(
name = 'example',
pkg = glob(["src/*.go"]),
)
# matrix.bzl
load("@io_bazel_rules_go//go:def.bzl", "go_binary")
SUPPORTED_MATRIX = [
("windows", "amd64"),
("darwin", "amd64"),
("linux", "amd64"),
("linux", "386"),
]
def _build(ctx):
for goos, goarch in SUPPORTED_MATRIX:
target_name = 'proxy-download-' + goos + '-' + goarch
if goos == 'windows':
target_name += '.exe'
go_binary(
name = target_name,
srcs = ctx.attr.pkg,
pure = "auto",
goos = goos,
goarch = goarch,
)
build_all_platform = rule(
_build,
attrs = {
'pkg': attr.string_list(),
},
executable = True,
)
但是遇到了一个错误,我认为这可能是由于rules_go
造成的原因。
Traceback (most recent call last):
File "/source/proxy-download/BUILD", line 4
build_all_platform(name = 'proxy-download')
File "/source/proxy-download/matrix.bzl", line 16, in _build
go_binary(name = target_name, <4 more arguments>)
File "/private/var/tmp/_bazel_/071099b99a462d431baf96a3ef76cd28/external/io_bazel_rules_go/go/private/rules/wrappers.bzl", line 50, in go_binary
go_transition_wrapper(go_binary, <3 more arguments>)
File "/private/var/tmp/_bazel_/071099b99a462d431baf96a3ef76cd28/external/io_bazel_rules_go/go/private/rules/transition.bzl", line 60, in go_transition_wrapper
transition_kind(name = name, <1 more arguments>)
'rule' can only be called during the loading phase
尝试在此问题提到的多个平台上同时通过测试。
bazel build --platforms=@io_bazel_rules_go//go/toolchain:linux_386,@io_bazel_rules_go//go/toolchain:linux_amd64 //:example
> WARNING: --platforms only supports a single target platform: using the first option @io_bazel_rules_go//go/toolchain:linux_386
参考此代码,使用构建命令行实现此操作。
options = [
"go",
"build",
"-o", output_file.path,
"-compiler", "gc",
"-gcflags", '"all=-trimpath=${GOPATH}/src"',
"-asmflags", '"all=-trimpath=${GOPATH}/src"',
"-ldflags", "'%s'" % ld_flags,
"-tags", "'%s'" % ctx.attr.gotags,
pkg,
]