Skip to content

Commit

Permalink
Normalize version when using go install (#266)
Browse files Browse the repository at this point in the history
  • Loading branch information
jmdacruz authored May 27, 2022
1 parent e35fdec commit 93517cd
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
21 changes: 20 additions & 1 deletion buildversion/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ package buildversion
import (
"fmt"
"runtime/debug"

"github.com/blang/semver"
)

const DefaultVersion = "0.0.0-dev"
Expand All @@ -39,13 +41,30 @@ func PackageManager() string {
return packageManager
}

func NormalizeVersion(version string) (string, error) {
if version[0] == 'v' {
// Normalize version tags in the form v1.1.1 to 1.1.1
version = version[1:]
}
// Ensure that version tag can be parsed correctly
_, err := semver.Parse(version)
if err != nil {
return version, err
}
return version, nil
}

func init() {
// Use build info from debug package if available, and if no build info is
// provided via build CLI.
info, available := debug.ReadBuildInfo()
// info.Main.Version will be "" when debugging, and "(devel)" when building with no arguments
if available && info.Main.Version != "" && info.Main.Version != "(devel)" && BuildTime == "" && BuildCommit == "" && BuildVersion == DefaultVersion {
BuildVersion = info.Main.Version
version, err := NormalizeVersion(info.Main.Version)
if err != nil {
return
}
BuildVersion = version
BuildCommit = fmt.Sprintf("(unknown, mod sum: %q)", info.Main.Sum)
BuildTime = "(unknown)"
}
Expand Down
42 changes: 42 additions & 0 deletions buildversion/version_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,45 @@ func TestDefaultBuildTime(t *testing.T) {
func TestDefaultBuildCommit(t *testing.T) {
assert.Equal(t, "", BuildCommit)
}

func TestNormalizeVersion(t *testing.T) {
tests := []struct {
expected string
input string
shouldFail bool
}{
{
input: "1.1.1",
expected: "1.1.1",
},
{
input: "v1.1.1",
expected: "1.1.1",
},
{
input: "x1.1.1",
shouldFail: true,
},
{
input: "vv1.1.1",
shouldFail: true,
},
{
input: "1.1",
shouldFail: true,
},
{
input: "foobar",
shouldFail: true,
},
}
for _, test := range tests {
actual, err := NormalizeVersion(test.input)
if test.shouldFail {
assert.Error(t, err)
continue
}
assert.NoError(t, err)
assert.Equal(t, test.expected, actual)
}
}

0 comments on commit 93517cd

Please sign in to comment.