Skip to content

Commit 312e467

Browse files
authored
fix: embed troubleshoot version string from module dependency (#1371)
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)
1 parent 5e280d0 commit 312e467

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

cmd/analyze/cli/run.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,15 @@ func runAnalyzers(v *viper.Viper, bundlePath string) error {
1818
specContent := ""
1919
var err error
2020
if _, err = os.Stat(specPath); err == nil {
21-
b, err := ioutil.ReadFile(specPath)
21+
b, err := os.ReadFile(specPath)
2222
if err != nil {
2323
return err
2424
}
2525

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

pkg/version/version.go

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package version
33
import (
44
"fmt"
55
"runtime"
6+
"runtime/debug"
67
"time"
78
)
89

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

30-
// initBuild sets up the version info from build args
31+
// initBuild sets up the version info from build args or imported modules in go.mod
3132
func initBuild() {
33+
// TODO: Can we get the module name at runtime somehow?
34+
tsModuleName := "github.com/replicatedhq/troubleshoot"
35+
36+
if version == "" {
37+
// Lets attempt to get the version from runtime build info
38+
// We will go through all the dependencies to find the
39+
// troubleshoot module version. Its OK if we cannot read
40+
// the buildinfo, we just won't have a version set
41+
bi, ok := debug.ReadBuildInfo()
42+
if ok {
43+
for _, dep := range bi.Deps {
44+
if dep.Path == tsModuleName {
45+
version = dep.Version
46+
break
47+
}
48+
}
49+
}
50+
}
51+
3252
build.Version = version
3353
if len(gitSHA) >= 7 {
3454
build.GitSHA = gitSHA[:7]
3555
}
56+
3657
var err error
3758
build.BuildTime, err = time.Parse(time.RFC3339, buildTime)
3859
if err != nil {

0 commit comments

Comments
 (0)