build: get binary build info from debug/buildinfo

Since `go1.18` the runtime has a package that provides information about module
versions, version control information, and build flags embedded in executable
files built by the go command.

The new packages allows us to get information needed by the `version` command
without having to rely on `ldflags` set at build time.

This can be really helpful while debugging errors from people using custom
binaries. For example a build from master.
This commit is contained in:
positiveblue
2022-10-01 15:09:34 -07:00
parent 27fdd0a5b0
commit 5924964a9b
2 changed files with 32 additions and 27 deletions

View File

@@ -7,6 +7,7 @@ package build
import (
"fmt"
"runtime/debug"
"strings"
)
@@ -17,16 +18,14 @@ var (
// -ldflags during compilation.
Commit string
// CommitHash stores the current commit hash of this build, this should
// be set using the -ldflags during compilation.
// CommitHash stores the current commit hash of this build.
CommitHash string
// RawTags contains the raw set of build tags, separated by commas. This
// should be set using -ldflags during compilation.
// RawTags contains the raw set of build tags, separated by commas.
RawTags string
// GoVersion stores the go version that the executable was compiled
// with. This should be set using -ldflags during compilation.
// with.
GoVersion string
)
@@ -62,6 +61,20 @@ func init() {
"alphabet", r))
}
}
// Get build information from the runtime.
if info, ok := debug.ReadBuildInfo(); ok {
GoVersion = info.GoVersion
for _, setting := range info.Settings {
switch setting.Key {
case "vcs.revision":
CommitHash = setting.Value
case "-tags":
RawTags = setting.Value
}
}
}
}
// Version returns the application version as a properly formed string per the