Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions version/version.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package version

import (
"fmt"
"os"
"strings"

"github.com/blang/semver/v4"
Expand All @@ -12,9 +14,32 @@ var (
binaryVersion string
binarySHA string
binaryBuildDate string
customVersion string

ExitFunc = os.Exit
)

func SetVersion(version string) {
if version == "" {
customVersion = ""
return
}

_, err := semver.Parse(version)

if err != nil {
fmt.Fprintf(os.Stderr, "Invalid semantic version format: %s\n", err)
ExitFunc(1)
}

customVersion = version
}

func VersionString() string {
if customVersion != "" {
return customVersion
}

// Remove the "v" prefix from the binary in case it is present
binaryVersion = strings.TrimPrefix(binaryVersion, "v")
versionString, err := semver.Make(binaryVersion)
Expand Down
34 changes: 34 additions & 0 deletions version/version_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,45 @@ import (
)

var _ = Describe("Version", func() {
BeforeEach(func() {
version.SetVersion("")
})

Describe("VersionString", func() {
When("passed no ldflags", func() {
It("returns the default version", func() {
Expect(version.VersionString()).To(Equal("0.0.0-unknown-version"))
})
})

When("a custom version is set", func() {
It("returns the custom version", func() {
version.SetVersion("1.2.3")
Expect(version.VersionString()).To(Equal("1.2.3"))
})
})
})

Describe("SetVersion", func() {
It("sets the version for valid semver versions", func() {
version.SetVersion("1.2.3")
Expect(version.VersionString()).To(Equal("1.2.3"))
})

It("exits with status code 1 when given an invalid semver", func() {
var exitCode int
originalExitFunc := version.ExitFunc

defer func() {
version.ExitFunc = originalExitFunc
}()

version.ExitFunc = func(code int) {
exitCode = code
}

version.SetVersion("not-a-semver")
Expect(exitCode).To(Equal(1))
})
})
})
Loading