Skip to content

Commit

Permalink
VersionLessThan(): fix comparison for multi-digit version parts
Browse files Browse the repository at this point in the history
The function was previously using lexicographical comparison of strings,
which works as expected only for single-digit version parts. Fix the
function to actually first convert version parts to integers before
comparing them. This will ensure the correct numerical order.

Signed-off-by: Tomáš Hozza <[email protected]>
  • Loading branch information
thozza committed Oct 9, 2023
1 parent 76f5eed commit 18a3031
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 2 deletions.
13 changes: 11 additions & 2 deletions internal/common/distro.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"io"
"os"
"strconv"
"strings"
)

Expand Down Expand Up @@ -71,9 +72,17 @@ func VersionLessThan(a, b string) bool {
}

for idx := 0; idx < len(aParts); idx++ {
if aParts[idx] < bParts[idx] {
aInt, err := strconv.Atoi(aParts[idx])
if err != nil {
panic(err)
}
bInt, err := strconv.Atoi(bParts[idx])
if err != nil {
panic(err)
}
if aInt < bInt {
return true
} else if aParts[idx] > bParts[idx] {
} else if aInt > bInt {
return false
}
}
Expand Down
74 changes: 74 additions & 0 deletions internal/common/distro_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,77 @@ VARIANT_ID=workstation`,
}
}
}

func TestVersionLessThan(t *testing.T) {
type testCases struct {
Name string
VersionA string
VersionB string
Expected bool
}

cases := []testCases{
{
Name: "8 < 8.1",
VersionA: "8",
VersionB: "8.1",
Expected: true,
},
{
Name: "8.1 < 8.2",
VersionA: "8.1",
VersionB: "8.2",
Expected: true,
},
{
Name: "8 < 9",
VersionA: "8",
VersionB: "9",
Expected: true,
},
{
Name: "8.1 < 9",
VersionA: "8.1",
VersionB: "9",
Expected: true,
},
{
Name: "8.1 < 9.1",
VersionA: "8.1",
VersionB: "9.1",
Expected: true,
},
{
Name: "8 < 8.10",
VersionA: "8",
VersionB: "8.10",
Expected: true,
},
{
Name: "8.1 < 8.10",
VersionA: "8.1",
VersionB: "8.10",
Expected: true,
},
{
Name: "8.10 < 8.11",
VersionA: "8.10",
VersionB: "8.11",
Expected: true,
},
{
Name: "8.10 > 8.6",
VersionA: "8.10",
VersionB: "8.6",
Expected: false,
},
}

for _, c := range cases {
t.Run(c.Name, func(t *testing.T) {
if VersionLessThan(c.VersionA, c.VersionB) != c.Expected {
t.Fatalf("VersionLessThan(%s, %s) returned unexpected result", c.VersionA, c.VersionB)
}
})
}
}

0 comments on commit 18a3031

Please sign in to comment.