Skip to content

Commit 070c506

Browse files
authored
Set custom version (#3491)
1 parent dd2557f commit 070c506

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

version/version.go

+25
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package version
22

33
import (
4+
"fmt"
5+
"os"
46
"strings"
57

68
"github.com/blang/semver/v4"
@@ -12,9 +14,32 @@ var (
1214
binaryVersion string
1315
binarySHA string
1416
binaryBuildDate string
17+
customVersion string
18+
19+
ExitFunc = os.Exit
1520
)
1621

22+
func SetVersion(version string) {
23+
if version == "" {
24+
customVersion = ""
25+
return
26+
}
27+
28+
_, err := semver.Parse(version)
29+
30+
if err != nil {
31+
fmt.Fprintf(os.Stderr, "Invalid semantic version format: %s\n", err)
32+
ExitFunc(1)
33+
}
34+
35+
customVersion = version
36+
}
37+
1738
func VersionString() string {
39+
if customVersion != "" {
40+
return customVersion
41+
}
42+
1843
// Remove the "v" prefix from the binary in case it is present
1944
binaryVersion = strings.TrimPrefix(binaryVersion, "v")
2045
versionString, err := semver.Make(binaryVersion)

version/version_test.go

+34
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,45 @@ import (
77
)
88

99
var _ = Describe("Version", func() {
10+
BeforeEach(func() {
11+
version.SetVersion("")
12+
})
13+
1014
Describe("VersionString", func() {
1115
When("passed no ldflags", func() {
1216
It("returns the default version", func() {
1317
Expect(version.VersionString()).To(Equal("0.0.0-unknown-version"))
1418
})
1519
})
20+
21+
When("a custom version is set", func() {
22+
It("returns the custom version", func() {
23+
version.SetVersion("1.2.3")
24+
Expect(version.VersionString()).To(Equal("1.2.3"))
25+
})
26+
})
27+
})
28+
29+
Describe("SetVersion", func() {
30+
It("sets the version for valid semver versions", func() {
31+
version.SetVersion("1.2.3")
32+
Expect(version.VersionString()).To(Equal("1.2.3"))
33+
})
34+
35+
It("exits with status code 1 when given an invalid semver", func() {
36+
var exitCode int
37+
originalExitFunc := version.ExitFunc
38+
39+
defer func() {
40+
version.ExitFunc = originalExitFunc
41+
}()
42+
43+
version.ExitFunc = func(code int) {
44+
exitCode = code
45+
}
46+
47+
version.SetVersion("not-a-semver")
48+
Expect(exitCode).To(Equal(1))
49+
})
1650
})
1751
})

0 commit comments

Comments
 (0)