1# A helper function to get the go platform string of the Bazel host. 2# This can be used to do cross-platform go compilations. 3# Example: 4# $ bazelisk run //bazel:go_platform 5# darwin_arm64 6py_binary( 7 name = "go_platform", 8 srcs = ["go_platform.py"], 9 data = ["@go_sdk//:bin/go"], 10 tags = ["no-remote"], # Need the platform of the host 11) 12 13_GO_PLATFORM = """ 14import os 15import subprocess 16 17# https://bazel.build/reference/be/make-variables#predefined_label_variables 18go_exe = os.path.abspath("$(execpath @go_sdk//:bin/go)") 19 20result = subprocess.run([ 21 go_exe, 22 "version", 23], capture_output=True, encoding="utf-8") 24 25# e.g. go version go1.18 darwin/arm64 26os_arch = result.stdout.strip().split(" ")[3] 27# e.g. darwin/arm64 28print(os_arch.replace("/", "_")) 29""" 30 31genrule( 32 name = "create_go_platform_script", 33 outs = ["go_platform.py"], 34 cmd = "echo '%s' > $@" % _GO_PLATFORM, 35 tools = [ 36 "@go_sdk//:bin/go", 37 ], 38) 39