Skip to content

Commit

Permalink
fix: embed troubleshoot version string from module dependency (#1371)
Browse files Browse the repository at this point in the history
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)
  • Loading branch information
banjoh authored Oct 16, 2023
1 parent 5e280d0 commit 312e467
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
3 changes: 2 additions & 1 deletion cmd/analyze/cli/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,15 @@ func runAnalyzers(v *viper.Viper, bundlePath string) error {
specContent := ""
var err error
if _, err = os.Stat(specPath); err == nil {
b, err := ioutil.ReadFile(specPath)
b, err := os.ReadFile(specPath)
if err != nil {
return err
}

specContent = string(b)
} else {
if !util.IsURL(specPath) {
// TODO: Better error message when we do not have a file/url etc
return fmt.Errorf("%s is not a URL and was not found (err %s)", specPath, err)
}

Expand Down
23 changes: 22 additions & 1 deletion pkg/version/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package version
import (
"fmt"
"runtime"
"runtime/debug"
"time"
)

Expand All @@ -27,12 +28,32 @@ type GoInfo struct {
Arch string `json:"arch,omitempty"`
}

// initBuild sets up the version info from build args
// 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 {
Expand Down

0 comments on commit 312e467

Please sign in to comment.