Skip to content

Commit

Permalink
Merge pull request #69 from zeralight/fix-version-sorting
Browse files Browse the repository at this point in the history
fix version comparison & sorting
  • Loading branch information
bhou authored Sep 5, 2022
2 parents 37279a9 + ba8df0e commit 0847482
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 16 deletions.
15 changes: 8 additions & 7 deletions cmd/remote/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,15 +51,16 @@ func (version defaultVersion) String() string {
}

func Less(l defaultVersion, r defaultVersion) bool {
if l.Major < r.Major {
return true
} else if l.Minor < r.Minor {
return true
} else if l.Patch < r.Patch {
return true
lseg := [3]int{l.Major, l.Minor, l.Patch}
rseg := [3]int{r.Major, r.Minor, r.Patch}
for i := 0; i < 3; i++ {
if lseg[i] != rseg[i] {
return lseg[i] < rseg[i]
}
}

return false
// If segments are equal, then compare the prerelease info
return l.Tag < r.Tag
}

func IsVersionSmaller(v1 string, v2 string) bool {
Expand Down
41 changes: 32 additions & 9 deletions cmd/remote/version_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package remote

import (
"fmt"
"sort"
"testing"

"github.com/stretchr/testify/assert"
)

func TestToString(t *testing.T) {
Expand Down Expand Up @@ -63,10 +66,13 @@ func TestParseVersions(t *testing.T) {

func TestSorter(t *testing.T) {
values := []string{
"2.0.2",
"2.0.1",
"2",
"1.2",
"1",
"1.2.3",
"1.0.9",
}

var versions []defaultVersion
Expand All @@ -77,19 +83,36 @@ func TestSorter(t *testing.T) {
}

sort.Sort(defaultVersionList(versions))
if versions[0].Major != 1 {
t.Log(versions)
}

if versions[1].Minor != 2 {
t.Log(versions)
expected_versions := []defaultVersion{
{1, 0, 0, ""},
{1, 0, 9, ""},
{1, 2, 0, ""},
{1, 2, 3, ""},
{2, 0, 0, ""},
{2, 0, 1, ""},
{2, 0, 2, ""},
}

if versions[2].Patch != 3 {
t.Log(versions)
for i := 0; i < len(expected_versions); i++ {
assert.Equal(t, expected_versions[i], versions[i], fmt.Sprintf("versions[%d] should be %v", i, expected_versions[i]))
}
}

if versions[3].Major != 2 {
t.Log(versions)
func TestLess(t *testing.T) {
test_cases := []struct {
l, r defaultVersion
compare int
}{
{defaultVersion{1, 0, 0, ""}, defaultVersion{1, 0, 1, ""}, -1},
{defaultVersion{1, 0, 0, ""}, defaultVersion{1, 0, 0, ""}, 0},
{defaultVersion{1, 0, 2, ""}, defaultVersion{1, 1, 0, ""}, -1},
{defaultVersion{1, 1, 0, ""}, defaultVersion{1, 0, 1, ""}, 1},
{defaultVersion{1, 0, 0, "rc1"}, defaultVersion{1, 0, 0, "rc2"}, -1},
{defaultVersion{1, 0, 0, "rc2"}, defaultVersion{1, 0, 0, "rc2"}, 0},
}
for _, tc := range test_cases {
assert.Equal(t, tc.compare < 0, Less(tc.l, tc.r), fmt.Sprintf("Less(%v, %v) should be %v", tc.l, tc.r, tc.compare < 0))
assert.Equal(t, tc.compare > 0, Less(tc.r, tc.l), fmt.Sprintf("Less(%v, %v) should be %v", tc.r, tc.l, tc.compare > 0))
}
}

0 comments on commit 0847482

Please sign in to comment.