From 1104363988051149ada9eb8051978de405df073d Mon Sep 17 00:00:00 2001 From: sunwei <18801147024@163.com> Date: Sun, 9 Aug 2020 02:04:38 +0800 Subject: [PATCH] =?UTF-8?q?=E3=80=90rich=20function=E3=80=91CustomVersionC?= =?UTF-8?q?ompare=20append?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/utils/version.go | 87 ++++++++++++++++++++++++++++++++++++++ core/utils/version_test.go | 30 +++++++++++++ 2 files changed, 117 insertions(+) diff --git a/core/utils/version.go b/core/utils/version.go index bb6b4b77..656ac335 100644 --- a/core/utils/version.go +++ b/core/utils/version.go @@ -35,3 +35,90 @@ func CompareVersions(a, b string) int { return 0 } + +//return 0 if they are equal,and 1 if v1>2,and 2 if v1 len(ver2) { + shorter = len(ver2) + } else { + shorter = len(ver1) + } + + for i := 0; i < shorter; i++ { + if ver1[i] == ver2[i] { + if shorter-1 == i { + if len(ver1) == len(ver2) { + return 0 + } else { + if len(ver1) > len(ver2) { + return 1 + } else { + return 2 + } + } + } + } else if ver1[i] > ver2[i] { + return 1 + } else { + return 2 + } + } + return -1 +} + +func strSlice2IntSlice(strs []string) []int64 { + if len(strs) == 0 { + return []int64{} + } + retInt := make([]int64, 0, len(strs)) + for _, str := range strs { + i, err := strconv.ParseInt(str, 10, 64) + if err == nil { + retInt = append(retInt, i) + } + } + return retInt +} + +//custom operator compare +func CustomCompareVersions(v1, v2, operator string) bool { + com := Compare(v1, v2) + switch operator { + case "==": + if com == 0 { + return true + } + case "<": + if com == 2 { + return true + } + case ">": + if com == 1 { + return true + } + case "<=": + if com == 0 || com == 2 { + return true + } + case ">=": + if com == 0 || com == 1 { + return true + } + } + return false +} diff --git a/core/utils/version_test.go b/core/utils/version_test.go index b751ced8..1cdd60f7 100644 --- a/core/utils/version_test.go +++ b/core/utils/version_test.go @@ -28,3 +28,33 @@ func TestCompareVersions(t *testing.T) { }) } } + +func TestCustomCompareVersions(t *testing.T) { + cases := []struct { + ver1 string + ver2 string + operator string + out bool + }{ + {"1", "1.0.1", ">", false}, + {"1", "0.9.9", ">", true}, + {"1", "1-0.1", "<", true}, + {"1.0.1", "1-0.1", "<", false}, + {"1.0.1", "1.0.1", "==", true}, + {"1.0.1", "1.0.2", "==", false}, + {"1.1-1", "1.0.2", "==", false}, + {"1.0.1", "1.0.2", ">=", false}, + {"1.0.2", "1.0.2", ">=", true}, + {"1.0.3", "1.0.2", ">=", true}, + {"1.0.4", "1.0.2", "<=", false}, + {"1.0.4", "1.0.6", "<=", true}, + {"1.0.4", "1.0.4", "<=", true}, + } + + for _, each := range cases { + t.Run(each.ver1, func(t *testing.T) { + actual := CustomCompareVersions(each.ver1, each.ver2, each.operator) + assert.Equal(t, each.out, actual) + }) + } +}