From c873c18a42680d05e0fe9ddb732efcb2c03655e7 Mon Sep 17 00:00:00 2001 From: zhengkunwang <31820853+zhengkunwang223@users.noreply.github.com> Date: Thu, 14 Dec 2023 11:20:11 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E8=A7=A3=E5=86=B3=E9=83=A8=E5=88=86?= =?UTF-8?q?=E8=BD=AF=E4=BB=B6=E9=94=99=E8=AF=AF=E5=88=A4=E6=96=AD=E5=8D=87?= =?UTF-8?q?=E7=BA=A7=E7=9A=84=E9=97=AE=E9=A2=98=20(#3314)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/utils/common/common.go | 78 ++++++++++++++++++++-------------- 1 file changed, 47 insertions(+), 31 deletions(-) diff --git a/backend/utils/common/common.go b/backend/utils/common/common.go index 09b682d1f..853245eb8 100644 --- a/backend/utils/common/common.go +++ b/backend/utils/common/common.go @@ -17,44 +17,60 @@ import ( "github.com/mozillazg/go-pinyin" ) -func CompareVersion(version1 string, version2 string) bool { - if version1 == version2 { - return false - } - version1s := strings.Split(version1, ".") - version2s := strings.Split(version2, ".") - - if len(version2s) > len(version1s) { - for i := 0; i < len(version2s)-len(version1s); i++ { - version1s = append(version1s, "0") +func CompareVersion(version1, version2 string) bool { + v1s := extractNumbers(version1) + v2s := extractNumbers(version2) + + maxLen := max(len(v1s), len(v2s)) + v1s = append(v1s, make([]string, maxLen-len(v1s))...) + v2s = append(v2s, make([]string, maxLen-len(v2s))...) + + for i := 0; i < maxLen; i++ { + v1, err1 := strconv.Atoi(v1s[i]) + v2, err2 := strconv.Atoi(v2s[i]) + if err1 != nil { + v1 = 0 } - } - if len(version1s) > len(version2s) { - for i := 0; i < len(version1s)-len(version2s); i++ { - version2s = append(version2s, "0") + if err2 != nil { + v2 = 0 + } + if v1 != v2 { + return v1 > v2 } } + return false +} - n := min(len(version1s), len(version2s)) - re := regexp.MustCompile("[0-9]+") - for i := 0; i < n; i++ { - sVersion1s := re.FindAllString(version1s[i], -1) - sVersion2s := re.FindAllString(version2s[i], -1) - if len(sVersion1s) == 0 { - return false - } - if len(sVersion2s) == 0 { - return false - } - v1num, _ := strconv.Atoi(sVersion1s[0]) - v2num, _ := strconv.Atoi(sVersion2s[0]) - if v1num == v2num { - continue +func extractNumbers(version string) []string { + var numbers []string + start := -1 + for i, r := range version { + if isDigit(r) { + if start == -1 { + start = i + } } else { - return v1num > v2num + if start != -1 { + numbers = append(numbers, version[start:i]) + start = -1 + } } } - return true + if start != -1 { + numbers = append(numbers, version[start:]) + } + return numbers +} + +func isDigit(r rune) bool { + return r >= '0' && r <= '9' +} + +func max(x, y int) int { + if x > y { + return x + } + return y } func GetSortedVersions(versions []string) []string {