Skip to content

Commit

Permalink
add Base func
Browse files Browse the repository at this point in the history
Adds a Base function to Version, which returns a new Version created from only
the MAJOR.MINOR.PATCH segments of the original version, without prerelease or
metadata strings.

Consumers of go-version often want to treat prereleases of versions as equal to
non-prerelease versions, e.g. 0.15.0-dev as equal to 0.15.0. The present
functionality is intended as an easy way to opt in to this behaviour.
  • Loading branch information
kmoe committed Mar 30, 2021
1 parent 9e69307 commit cb20135
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
8 changes: 8 additions & 0 deletions version.go
Expand Up @@ -278,6 +278,14 @@ func comparePrereleases(v string, other string) int {
return 0
}

// Base returns a new version constructed from only the MAJOR.MINOR.PATCH
// segments of the version, without prerelease or metadata.
func (v *Version) Base() *Version {
segments := v.Segments64()
segmentsOnly := fmt.Sprintf("%d.%d.%d", segments[0], segments[1], segments[2])
return Must(NewVersion(segmentsOnly))
}

// Equal tests if two versions are equal.
func (v *Version) Equal(o *Version) bool {
if v == nil || o == nil {
Expand Down
32 changes: 32 additions & 0 deletions version_test.go
Expand Up @@ -87,6 +87,38 @@ func TestNewSemver(t *testing.T) {
}
}

func TestBase(t *testing.T) {
cases := []struct {
v1 string
v2 string
}{
{"1.2.3", "1.2.3"},
{"2.3.4-alpha1", "2.3.4"},
{"3.4.5alpha1", "3.4.5"},
{"1.2.3-2", "1.2.3"},
{"4.5.6-beta1+meta", "4.5.6"},
{"5.6.7.1.2.3", "5.6.7"},
}

for _, tc := range cases {
v1, err := NewVersion(tc.v1)
if err != nil {
t.Fatalf("error for version %q: %s", tc.v1, err)
}
v2, err := NewVersion(tc.v2)
if err != nil {
t.Fatalf("error for version %q: %s", tc.v2, err)
}

actual := v1.Base()
expected := v2

if !reflect.DeepEqual(actual, expected) {
t.Fatalf("expected: %s\nactual: %s", expected, actual)
}
}
}

func TestVersionCompare(t *testing.T) {
cases := []struct {
v1 string
Expand Down

0 comments on commit cb20135

Please sign in to comment.