go-platform/pkg/versionutil/compare.go
2026-04-08 20:33:02 +08:00

58 lines
1016 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package versionutil
import (
"strconv"
"strings"
)
// Compare 比较语义化版本号(按段数字比较,如 1.10.0 > 1.9.0)。不支持复杂 pre-release 规则。
// 返回 -1 表示 a < b0 表示相等1 表示 a > b。
func Compare(a, b string) int {
pa := parseParts(a)
pb := parseParts(b)
maxLen := len(pa)
if len(pb) > maxLen {
maxLen = len(pb)
}
for i := 0; i < maxLen; i++ {
var xa, xb int64
if i < len(pa) {
xa = pa[i]
}
if i < len(pb) {
xb = pb[i]
}
if xa < xb {
return -1
}
if xa > xb {
return 1
}
}
return 0
}
func parseParts(s string) []int64 {
s = strings.TrimSpace(s)
if s == "" {
return []int64{0}
}
if i := strings.IndexByte(s, '-'); i >= 0 {
s = s[:i]
}
parts := strings.Split(s, ".")
out := make([]int64, 0, len(parts))
for _, p := range parts {
p = strings.TrimSpace(p)
n, err := strconv.ParseInt(p, 10, 64)
if err != nil {
n = 0
}
out = append(out, n)
}
if len(out) == 0 {
return []int64{0}
}
return out
}