From 23d223508bfa6c12739669dc91d1b0df4a9c7b37 Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Wed, 29 Nov 2023 20:01:35 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20super=20=E5=8C=85=E6=96=B0=E5=A2=9E=20O?= =?UTF-8?q?ldVersion=20=E5=92=8C=20CompareVersion=20=E5=87=BD=E6=95=B0?= =?UTF-8?q?=E7=94=A8=E4=BA=8E=E7=89=88=E6=9C=AC=E6=AF=94=E8=BE=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/super/version.go | 57 +++++++++++++++++++++++++++++++++++++ utils/super/version_test.go | 13 +++++++++ 2 files changed, 70 insertions(+) create mode 100644 utils/super/version.go create mode 100644 utils/super/version_test.go diff --git a/utils/super/version.go b/utils/super/version.go new file mode 100644 index 0000000..4a15b34 --- /dev/null +++ b/utils/super/version.go @@ -0,0 +1,57 @@ +package super + +import ( + "regexp" + "strings" +) + +// OldVersion 检查 version2 对于 version1 来说是不是旧版本 +func OldVersion(version1, version2 string) bool { + return CompareVersion(version1, version2) == 1 +} + +// CompareVersion 返回一个整数,用于表示两个版本号的比较结果: +// - 如果 version1 大于 version2,它将返回 1 +// - 如果 version1 小于 version2,它将返回 -1 +// - 如果 version1 和 version2 相等,它将返回 0 +func CompareVersion(version1, version2 string) int { + reg, _ := regexp.Compile("[^0-9.]+") + processedVersion1 := processVersion(reg.ReplaceAllString(version1, "")) + processedVersion2 := processVersion(reg.ReplaceAllString(version2, "")) + + n, m := len(processedVersion1), len(processedVersion2) + i, j := 0, 0 + for i < n || j < m { + x := 0 + for ; i < n && processedVersion1[i] != '.'; i++ { + x = x*10 + int(processedVersion1[i]-'0') + } + i++ // skip the dot + y := 0 + for ; j < m && processedVersion2[j] != '.'; j++ { + y = y*10 + int(processedVersion2[j]-'0') + } + j++ // skip the dot + if x > y { + return 1 + } + if x < y { + return -1 + } + } + return 0 +} + +func processVersion(version string) string { + // 移除首尾可能存在的非数字字符 + reg, _ := regexp.Compile("^[^.0-9]+|[^.0-9]+$") + version = reg.ReplaceAllString(version, "") + // 确保不出现连续的点 + version = strings.ReplaceAll(version, "..", ".") + // 移除每一部分起始的 0 + versionParts := strings.Split(version, ".") + for idx, part := range versionParts { + versionParts[idx] = strings.TrimLeft(part, "0") + } + return strings.Join(versionParts, ".") +} diff --git a/utils/super/version_test.go b/utils/super/version_test.go new file mode 100644 index 0000000..326acf1 --- /dev/null +++ b/utils/super/version_test.go @@ -0,0 +1,13 @@ +package super_test + +import ( + "github.com/kercylan98/minotaur/utils/super" + "testing" +) + +func TestCompareVersion(t *testing.T) { + t.Log(super.CompareVersion("1", "2"), -1) + t.Log(super.CompareVersion("1", "vv2"), -1) + t.Log(super.CompareVersion("1", "vv2.3.1"), -1) + t.Log(super.CompareVersion("11", "vv2.3.1"), 1) +}