File tree 2 files changed +59
-0
lines changed
2 files changed +59
-0
lines changed Original file line number Diff line number Diff line change 1
1
package version
2
2
3
3
import (
4
+ "fmt"
5
+ "os"
4
6
"strings"
5
7
6
8
"github.com/blang/semver/v4"
12
14
binaryVersion string
13
15
binarySHA string
14
16
binaryBuildDate string
17
+ customVersion string
18
+
19
+ ExitFunc = os .Exit
15
20
)
16
21
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
+
17
38
func VersionString () string {
39
+ if customVersion != "" {
40
+ return customVersion
41
+ }
42
+
18
43
// Remove the "v" prefix from the binary in case it is present
19
44
binaryVersion = strings .TrimPrefix (binaryVersion , "v" )
20
45
versionString , err := semver .Make (binaryVersion )
Original file line number Diff line number Diff line change @@ -7,11 +7,45 @@ import (
7
7
)
8
8
9
9
var _ = Describe ("Version" , func () {
10
+ BeforeEach (func () {
11
+ version .SetVersion ("" )
12
+ })
13
+
10
14
Describe ("VersionString" , func () {
11
15
When ("passed no ldflags" , func () {
12
16
It ("returns the default version" , func () {
13
17
Expect (version .VersionString ()).To (Equal ("0.0.0-unknown-version" ))
14
18
})
15
19
})
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
+ })
16
50
})
17
51
})
You can’t perform that action at this time.
0 commit comments