Skip to content

Commit 10e7aa0

Browse files
committed
cmd: refactor -version so it works with go install
The previous method of setting version assumed that values would be set through ldflags. Still supporting this method, but this PR adds a fallback to read from debug.BuildInfo if they aren't set. This covers the case where users are `go install`ing the tool.
1 parent 6363006 commit 10e7aa0

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

cmd/yamlfmt/main.go

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import (
1919
"fmt"
2020
"log"
2121
"os"
22+
"runtime/debug"
2223

2324
"github.com/google/yamlfmt"
2425
"github.com/google/yamlfmt/command"
@@ -27,8 +28,8 @@ import (
2728
)
2829

2930
var (
30-
version = "dev"
31-
commit = "none"
31+
version = ""
32+
commit = ""
3233
)
3334

3435
func main() {
@@ -44,7 +45,12 @@ func run() error {
4445
flag.Parse()
4546

4647
if *flagVersion {
47-
fmt.Printf("yamlfmt %s (%s)\n", version, commit)
48+
currentVersion, currentCommit := getVersion()
49+
versionMessage := fmt.Sprintf("yamlfmt %s", currentVersion)
50+
if currentCommit != "" {
51+
versionMessage += fmt.Sprintf(" (%s)", currentCommit)
52+
}
53+
fmt.Println(versionMessage)
4854
return nil
4955
}
5056

@@ -89,3 +95,20 @@ func run() error {
8995
func getFullRegistry() *yamlfmt.Registry {
9096
return yamlfmt.NewFormatterRegistry(&basic.BasicFormatterFactory{})
9197
}
98+
99+
func getVersion() (string, string) {
100+
// If version was set via ldflags, return that.
101+
if version != "" {
102+
return version, commit
103+
}
104+
105+
buildInfo, ok := debug.ReadBuildInfo()
106+
// If buildinfo can't be read, return default values.
107+
if !ok {
108+
return "dev", ""
109+
}
110+
111+
// Otherwise read the version from buildInfo (this is to cover
112+
// the go install usecase).
113+
return buildInfo.Main.Version, ""
114+
}

0 commit comments

Comments
 (0)