Bazel not allowing Go debug.ReadBuildInfo() passthrough?

43 views Asked by At

I'm new to Bazel and cannot understand why Go debug.ReadBuildInfo() is not usable for me.

I have a debug.ReadBuildInfo() wrapper function internal/version/info.go in codebase which outputs a marshalled JSON output via an exported BuildInfoJSON() function, so it looks like this:

// Basic wrapper around stdlib debug.ReadBuildInfo()
func BuildInfo() (*debug.BuildInfo, error) {
    info, ok := debug.ReadBuildInfo()
    if !ok {
        return nil, errors.New("failed to retrieve build info")
    }
    return info, nil
}

// Marshals output from debug.ReadBuildInfo() into JSON format
func BuildInfoJSON() ([]byte, error) {
    info, err := BuildInfo()
    if err != nil {
        return nil, err
    }
    json, err := json.MarshalIndent(info, "", " ")
    if err != nil {
        return nil, fmt.Errorf("failed to retrieve build info: %v", err)
    }
    return json, nil
}

I then have a command under cmd/foo/main.go which imports version (i.e. import (info codebase/internal/version)) and displays it if a version flag is set (code below is simplified pseudo-code):

    if *version {
        info.BuildInfoJSON()
    }

But when I compile with Bazel and call info.BuildInfoJSON() in main(), I get the following, I get an error failed to retrieve build info (which is bubbled up from debug.ReadBuildInfo() in my version function).

I am using Bzlmod with Gazelle to auto-generate BUILD.bazel files.

The auto-generated BUILD.bazel for internal/version is :

load("@rules_go//go:def.bzl", "go_library")

go_library(
    name = "version",
    srcs = ["info.go"],
    importpath = "codebase/internal/version",
    visibility = ["//:__subpackages__"],
)

The auto-generated BUILD.bazel for cmd/foo is :

load("@rules_go//go:def.bzl", "go_library")
load("//rules/go:rules_go.bzl", "go_binary")

go_library(
    name = "foo_lib",
    srcs = ["main.go"],
    importpath = "codebase/cmd/foo",
    visibility = ["//visibility:private"],
    deps = [
        "//internal/version",
    ],
)

go_binary(
    name = "foo",
    embed = [":foo_lib"],
    visibility = ["//visibility:public"],
)

Of course everything works perfectly if you directly call debug.ReadBuildInfo() within main() but that's not what I want, because I am keen to avoid code duplication.

0

There are 0 answers