Skip to content

Commit

Permalink
add Core func
Browse files Browse the repository at this point in the history
Adds a Core 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 31, 2021
1 parent 9e69307 commit 7da126b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
8 changes: 8 additions & 0 deletions version.go
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,14 @@ func comparePrereleases(v string, other string) int {
return 0
}

// Core returns a new version constructed from only the MAJOR.MINOR.PATCH
// segments of the version, without prerelease or metadata.
func (v *Version) Core() *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
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,38 @@ func TestNewSemver(t *testing.T) {
}
}

func TestCore(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.Core()
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 7da126b

Please sign in to comment.