E58B feat: get version info from go runtime (#281) · abice/go-enum@42b1ed5 · GitHub
[go: up one dir, main page]

Skip to content

Commit 42b1ed5

Browse files
authored
feat: get version info from go runtime (#281)
1 parent f44f518 commit 42b1ed5

File tree

2 files changed

+41
-9
lines changed

2 files changed

+41
-9
lines changed

main.go

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,21 @@ import (
55
"log"
66
"os"
77
"path/filepath"
8+
"runtime/debug"
89
"strings"
10+
"sync"
911

1012
"github.com/abice/go-enum/generator"
1113
"github.com/labstack/gommon/color"
1214
"github.com/urfave/cli/v2"
1315
)
1416

1517
var (
16-
version string
17-
commit string
18-
date string
19-
builtBy string
18+
versionOnce sync.Once
19+
version string
20+
commit string
21+
date string
22+
builtBy string
2023
)
2124

2225
type rootT struct {
@@ -47,11 +50,39 @@ type rootT struct {
4750
OutputSuffix string
4851
}
4952

53+
func initializeVersion() {
54+
versionOnce.Do(func() {
55+
if version != "" {
56+
return
57+
}
58+
buildInfo, ok := debug.ReadBuildInfo()
59+
if !ok {
60+
return
61+
}
62+
builtBy = "go install"
63+
version = buildInfo.Main.Version
64+
for _, setting := range buildInfo.Settings {
65+
switch setting.Key {
66+
case "vcs.revision":
67+
commit = setting.Value
68+
case "vcs.time":
69+
date = setting.Value
70+
case "vcs.modified":
71+
if setting.Value == "true" {
72+
commit += "-modified"
73+
}
74+
}
75+
}
76+
})
77+
}
78+
5079
func main() {
5180
var argv rootT
5281

82+
initializeVersion()
83+
5384
clr := color.New()
54-
out := func(format string, args ...interface{}) {
85+
out := func(format string, args ...any) {
5586
_, _ = fmt.Fprintf(clr.Output(), format, args...)
5687
}
5788

main_test.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -725,11 +725,12 @@ func TestCliFlagAliases(t *testing.T) {
725725
}
726726

727727
func TestGlobalVariables(t *testing.T) {
728+
initializeVersion()
728729
// Test that global variables are properly declared
729-
assert.Equal(t, "", version) // Should be empty by default (set during build)
730-
707D assert.Equal(t, "", commit) // Should be empty by default (set during build)
731-
assert.Equal(t, "", date) // Should be empty by default (set during build)
732-
assert.Equal(t, "", builtBy) // Should be empty by default (set during build)
730+
assert.Equal(t, "(devel)", version) // Default is "(devel)" unless set during build
731+
assert.Equal(t, "", commit) // Should be empty by default (set during build)
732+
assert.Equal(t, "", date) // Should be empty by default (set during build)
733+
assert.Equal(t, "go install", builtBy) // Default is "go install" unless set during build
733734
}
734735

735736
func TestGlobFilenamesEdgeCases(t *testing.T) {

0 commit comments

Comments
 (0)
0