Files
huangguo_server/common/version/version.go
T
rootandClaude Opus 5 8679200f41 Initial commit
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 13:57:10 +08:00

100 lines
1.8 KiB
Go

package version
import (
"errors"
"fmt"
"strconv"
"strings"
)
type Version struct {
Major int
Minor int
Revision int
}
var ErrVersionString = errors.New("bad version string")
func New(ver string) (*Version, error) {
vs := strings.Split(ver, ".")
if len(vs) != 3 {
return nil, ErrVersionString
}
major, err := strconv.Atoi(vs[0])
if err != nil {
return nil, ErrVersionString
}
minor, err := strconv.Atoi(vs[1])
if err != nil || minor > 999 {
return nil, ErrVersionString
}
revision, err := strconv.Atoi(vs[2])
if err != nil || revision > 999 {
return nil, ErrVersionString
}
return &Version{Major: major, Minor: minor, Revision: revision}, nil
}
func MustNew(ver string) *Version {
v, err := New(ver)
if err != nil {
panic("bad version")
}
return v
}
func (v *Version) GetCode() int64 {
return int64(v.Major*1000000) + int64(v.Minor*1000) + int64(v.Revision)
}
// for print
func (v *Version) String() string {
return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Revision)
}
// Compare 0相等, -1是 v< other, 1 v > other
func (v *Version) Compare(other *Version) float64 {
if v.String() == other.String() {
return 0
}
if v.Major > other.Major {
return 1
}
if v.Major < other.Major {
return -1
}
if v.Minor > other.Minor {
return 1
}
if v.Minor < other.Minor {
return -1
}
if v.Revision > other.Revision {
return 1
}
if v.Revision < other.Revision {
return -1
}
return 0
}
func (v *Version) GT(other *Version) bool {
return v.Compare(other) > 0
}
func (v *Version) LT(other *Version) bool {
return v.Compare(other) < 0
}
func (v *Version) EQ(other *Version) bool {
return v.Compare(other) == 0
}
func (v *Version) GTE(other *Version) bool {
return v.Compare(other) >= 0
}
func (v *Version) LTE(other *Version) bool {
return v.Compare(other) <= 0
}