mirror of
https://github.com/replicatedhq/troubleshoot.git
synced 2026-04-15 07:16:34 +00:00
If troubleshoot is used as a dependency in go.mod, the version information of the release would be missing at runtime. This is because the version string is injected to binaries at build time using linker flags (LD) passed to the compiler (check Makefile)
99 lines
2.1 KiB
Go
99 lines
2.1 KiB
Go
package version
|
|
|
|
import (
|
|
"fmt"
|
|
"runtime"
|
|
"runtime/debug"
|
|
"time"
|
|
)
|
|
|
|
var (
|
|
build Build
|
|
)
|
|
|
|
// Build holds details about this build of the binary
|
|
type Build struct {
|
|
Version string `json:"version,omitempty"`
|
|
GitSHA string `json:"git,omitempty"`
|
|
BuildTime time.Time `json:"buildTime,omitempty"`
|
|
TimeFallback string `json:"buildTimeFallback,omitempty"`
|
|
GoInfo GoInfo `json:"go,omitempty"`
|
|
RunAt *time.Time `json:"runAt,omitempty"`
|
|
}
|
|
|
|
type GoInfo struct {
|
|
Version string `json:"version,omitempty"`
|
|
Compiler string `json:"compiler,omitempty"`
|
|
OS string `json:"os,omitempty"`
|
|
Arch string `json:"arch,omitempty"`
|
|
}
|
|
|
|
// initBuild sets up the version info from build args or imported modules in go.mod
|
|
func initBuild() {
|
|
// TODO: Can we get the module name at runtime somehow?
|
|
tsModuleName := "github.com/replicatedhq/troubleshoot"
|
|
|
|
if version == "" {
|
|
// Lets attempt to get the version from runtime build info
|
|
// We will go through all the dependencies to find the
|
|
// troubleshoot module version. Its OK if we cannot read
|
|
// the buildinfo, we just won't have a version set
|
|
bi, ok := debug.ReadBuildInfo()
|
|
if ok {
|
|
for _, dep := range bi.Deps {
|
|
if dep.Path == tsModuleName {
|
|
version = dep.Version
|
|
break
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
build.Version = version
|
|
if len(gitSHA) >= 7 {
|
|
build.GitSHA = gitSHA[:7]
|
|
}
|
|
|
|
var err error
|
|
build.BuildTime, err = time.Parse(time.RFC3339, buildTime)
|
|
if err != nil {
|
|
build.TimeFallback = buildTime
|
|
}
|
|
|
|
build.GoInfo = getGoInfo()
|
|
build.RunAt = &RunAt
|
|
}
|
|
|
|
// GetBuild gets the build
|
|
func GetBuild() Build {
|
|
return build
|
|
}
|
|
|
|
// Version gets the version
|
|
func Version() string {
|
|
return build.Version
|
|
}
|
|
|
|
// GitSHA gets the gitsha
|
|
func GitSHA() string {
|
|
return build.GitSHA
|
|
}
|
|
|
|
// BuildTime gets the build time
|
|
func BuildTime() time.Time {
|
|
return build.BuildTime
|
|
}
|
|
|
|
func getGoInfo() GoInfo {
|
|
return GoInfo{
|
|
Version: runtime.Version(),
|
|
Compiler: runtime.Compiler,
|
|
OS: runtime.GOOS,
|
|
Arch: runtime.GOARCH,
|
|
}
|
|
}
|
|
|
|
func GetUserAgent() string {
|
|
return fmt.Sprintf("Replicated_Troubleshoot/%s", Version())
|
|
}
|