From d4216b0dcc13567479d81cc5ad2adedb1443ea8b Mon Sep 17 00:00:00 2001 From: Junegunn Choi Date: Thu, 23 May 2024 18:41:13 +0900 Subject: Use MSYS=enable_pcon instead of winpty on mintty 3.4.5 or later --- src/util/util.go | 32 ++++++++++++++++++++++++++++++++ src/util/util_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) (limited to 'src/util') diff --git a/src/util/util.go b/src/util/util.go index b5b27f28..9b926b8d 100644 --- a/src/util/util.go +++ b/src/util/util.go @@ -3,6 +3,7 @@ package util import ( "math" "os" + "strconv" "strings" "time" @@ -189,3 +190,34 @@ func ToKebabCase(s string) string { } return strings.ToLower(name) } + +// CompareVersions compares two version strings +func CompareVersions(v1, v2 string) int { + parts1 := strings.Split(v1, ".") + parts2 := strings.Split(v2, ".") + + atoi := func(s string) int { + n, e := strconv.Atoi(s) + if e != nil { + return 0 + } + return n + } + + for i := 0; i < Max(len(parts1), len(parts2)); i++ { + var p1, p2 int + if i < len(parts1) { + p1 = atoi(parts1[i]) + } + if i < len(parts2) { + p2 = atoi(parts2[i]) + } + + if p1 > p2 { + return 1 + } else if p1 < p2 { + return -1 + } + } + return 0 +} diff --git a/src/util/util_test.go b/src/util/util_test.go index af0762b5..013f3c23 100644 --- a/src/util/util_test.go +++ b/src/util/util_test.go @@ -203,3 +203,34 @@ func TestStringWidth(t *testing.T) { t.Errorf("Expected: %d, Actual: %d", 1, w) } } + +func TestCompareVersions(t *testing.T) { + assert := func(a, b string, expected int) { + if result := CompareVersions(a, b); result != expected { + t.Errorf("Expected: %d, Actual: %d", expected, result) + } + } + + assert("2", "1", 1) + assert("2", "2", 0) + assert("2", "10", -1) + + assert("2.1", "2.2", -1) + assert("2.1", "2.1.1", -1) + + assert("1.2.3", "1.2.2", 1) + assert("1.2.3", "1.2.3", 0) + assert("1.2.3", "1.2.3.0", 0) + assert("1.2.3", "1.2.4", -1) + + // Different number of parts + assert("1.0.0", "1", 0) + assert("1.0.0", "1.0", 0) + assert("1.0.0", "1.0.0", 0) + assert("1.0", "1.0.0", 0) + assert("1", "1.0.0", 0) + assert("1.0.0", "1.0.0.1", -1) + assert("1.0.0.1.0", "1.0.0.1", 0) + + assert("", "3.4.5", -1) +} -- cgit v1.2.3