File tree Expand file tree Collapse file tree 2 files changed +59
-0
lines changed
Expand file tree Collapse file tree 2 files changed +59
-0
lines changed Original file line number Diff line number Diff line change 11package version
22
33import (
4+ "fmt"
5+ "os"
46 "strings"
57
68 "github.com/blang/semver/v4"
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+
1738func 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 )
Original file line number Diff line number Diff line change @@ -7,11 +7,45 @@ import (
77)
88
99var _ = 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})
You can’t perform that action at this time.
0 commit comments