github.com/coreservice-io/utils@v0.3.0/version_util/version.go (about) 1 package version_util 2 3 import ( 4 "errors" 5 "strconv" 6 "strings" 7 ) 8 9 type Version struct { 10 head int64 11 middle int64 12 tail int64 13 } 14 15 func NewVersion(head int64, middle int64, tail int64) *Version { 16 return &Version{ 17 head: head, 18 middle: middle, 19 tail: tail, 20 } 21 } 22 23 func (v *Version) ToString() string { 24 return "v" + strconv.FormatInt(v.head, 10) + "." + strconv.FormatInt(v.middle, 10) + "." + strconv.FormatInt(v.tail, 10) 25 } 26 27 func StrToVersion(vstr string) (*Version, error) { 28 vstr = strings.TrimSpace(vstr) 29 vstr = strings.ToLower(vstr) 30 vstr = strings.TrimPrefix(vstr, "v") 31 32 v_array := strings.Split(vstr, ".") 33 34 if len(v_array) != 3 { 35 return nil, errors.New("version format error,vstr:" + vstr) 36 } 37 38 head_, err := strconv.ParseInt(v_array[0], 10, 64) 39 if err != nil { 40 return nil, errors.New("version head format error,vstr:" + vstr) 41 } 42 43 mid_, err := strconv.ParseInt(v_array[1], 10, 64) 44 if err != nil { 45 return nil, errors.New("version middle format error,vstr:" + vstr) 46 } 47 48 tail_, err := strconv.ParseInt(v_array[2], 10, 64) 49 if err != nil { 50 return nil, errors.New("version tail format error,vstr:" + vstr) 51 } 52 53 return &Version{ 54 head: head_, 55 middle: mid_, 56 tail: tail_, 57 }, nil 58 59 } 60 61 // a>b return 1 , a==b return 0 , a<b return -1 62 func VersionCompare(a *Version, b *Version) int { 63 64 //head 65 if a.head < b.head { 66 return -1 67 } else if a.head > b.head { 68 return 1 69 } else { 70 71 //middle 72 if a.middle < b.middle { 73 return -1 74 } else if a.middle > b.middle { 75 return 1 76 } else { 77 78 //tail 79 if a.tail < b.tail { 80 return -1 81 } else if a.tail > b.tail { 82 return 1 83 } else { 84 return 0 85 } 86 87 } 88 } 89 }