github.com/shuguocloud/go-zero@v1.3.0/core/utils/version.go (about) 1 package utils 2 3 import ( 4 "strconv" 5 "strings" 6 7 "github.com/shuguocloud/go-zero/core/mathx" 8 "github.com/shuguocloud/go-zero/core/stringx" 9 ) 10 11 var replacer = stringx.NewReplacer(map[string]string{ 12 "V": "", 13 "v": "", 14 "-": ".", 15 }) 16 17 // CompareVersions returns true if the first field and the third field are equal, otherwise false. 18 func CompareVersions(v1, op, v2 string) bool { 19 result := compare(v1, v2) 20 switch op { 21 case "=", "==": 22 return result == 0 23 case "<": 24 return result == -1 25 case ">": 26 return result == 1 27 case "<=": 28 return result == -1 || result == 0 29 case ">=": 30 return result == 0 || result == 1 31 } 32 33 return false 34 } 35 36 // return -1 if v1<v2, 0 if they are equal, and 1 if v1>v2 37 func compare(v1, v2 string) int { 38 v1 = replacer.Replace(v1) 39 v2 = replacer.Replace(v2) 40 fields1 := strings.Split(v1, ".") 41 fields2 := strings.Split(v2, ".") 42 ver1 := strsToInts(fields1) 43 ver2 := strsToInts(fields2) 44 shorter := mathx.MinInt(len(ver1), len(ver2)) 45 46 for i := 0; i < shorter; i++ { 47 if ver1[i] == ver2[i] { 48 continue 49 } else if ver1[i] < ver2[i] { 50 return -1 51 } else { 52 return 1 53 } 54 } 55 56 if len(ver1) < len(ver2) { 57 return -1 58 } else if len(ver1) == len(ver2) { 59 return 0 60 } else { 61 return 1 62 } 63 } 64 65 func strsToInts(strs []string) []int64 { 66 if len(strs) == 0 { 67 return nil 68 } 69 70 ret := make([]int64, 0, len(strs)) 71 for _, str := range strs { 72 i, _ := strconv.ParseInt(str, 10, 64) 73 ret = append(ret, i) 74 } 75 76 return ret 77 }