-
Notifications
You must be signed in to change notification settings - Fork 0
/
version.go
130 lines (107 loc) · 2.28 KB
/
version.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package migo
import (
"errors"
"fmt"
"sort"
"strconv"
"strings"
version "github.com/blang/semver"
)
type Version struct {
v *version.Version
timestamp int64
Name string
}
func (v Version) String() string {
skipSegs := true
if v.v.Patch != 0 || v.v.Minor != 0 || v.timestamp != 0 {
skipSegs = false
}
ver := ""
if skipSegs {
ver = fmt.Sprintf("%v", v.v.Major)
} else {
ver = v.v.String()
if v.timestamp > 0 {
ver += fmt.Sprintf(".%d", v.timestamp)
}
}
return fmt.Sprintf("%s-%s", ver, v.Name)
}
func (v Version) StringWithoutName() string {
skipSegs := true
if v.v.Patch != 0 || v.v.Minor != 0 || v.timestamp != 0 {
skipSegs = false
}
ver := ""
if skipSegs {
ver = fmt.Sprintf("%v", v.v.Major)
} else {
ver = v.v.String()
if v.timestamp > 0 {
ver += fmt.Sprintf(".%d", v.timestamp)
}
}
return ver
}
func VersionFromString(s string) (*Version, error) {
strs := strings.Split(s, "-")
if len(strs) < 2 {
return nil, errors.New("bad version format")
}
semver := strs[0]
var timestamp int64
versions := strings.Split(strs[0], ".")
if len(versions) == 4 {
semver = fmt.Sprintf("%s.%s.%s", versions[0], versions[1], versions[2])
var err error
timestamp, err = strconv.ParseInt(versions[3], 10, 64)
if err != nil {
return nil, err
}
}
v, err := version.ParseTolerant(semver)
if err != nil {
return nil, err
}
strAsByte := []byte(s)
name := string(strAsByte[len(strs[0])+1:])
return &Version{
v: &v,
Name: name,
timestamp: timestamp,
}, nil
}
func (v Version) GreaterThan(o *Version) bool {
r := v.v.Compare(*o.v)
if r == 0 {
return v.timestamp > o.timestamp
}
return r == 1
}
func (v Version) GreaterThanOrEqual(o *Version) bool {
r := v.v.Compare(*o.v)
if r == 0 {
return v.timestamp >= o.timestamp
}
return r >= 0
}
func StringsToVersions(strs []string) ([]Version, error) {
result := make([]Version, len(strs), len(strs))
for i, str := range strs {
ver, err := VersionFromString(str)
if err != nil {
return nil, err
}
result[i] = *ver
}
return result, nil
}
func GreatestVersion(versions []Version) *Version {
sort.SliceStable(versions, func(i, j int) bool {
left := versions[i]
right := versions[j]
return right.GreaterThan(&left)
})
return &versions[len(versions)-1]
}