blob: 76cf4852c769e9782e6130516686e8c792cd8202 [file] [log] [blame]
khenaidooab1f7bd2019-11-14 14:00:27 -05001// Copyright 2013-2015 CoreOS, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// Semantic Versions http://semver.org
16package semver
17
18import (
19 "bytes"
20 "errors"
21 "fmt"
khenaidood948f772021-08-11 17:49:24 -040022 "regexp"
khenaidooab1f7bd2019-11-14 14:00:27 -050023 "strconv"
24 "strings"
25)
26
27type Version struct {
28 Major int64
29 Minor int64
30 Patch int64
31 PreRelease PreRelease
32 Metadata string
33}
34
35type PreRelease string
36
37func splitOff(input *string, delim string) (val string) {
38 parts := strings.SplitN(*input, delim, 2)
39
40 if len(parts) == 2 {
41 *input = parts[0]
42 val = parts[1]
43 }
44
45 return val
46}
47
48func New(version string) *Version {
49 return Must(NewVersion(version))
50}
51
52func NewVersion(version string) (*Version, error) {
53 v := Version{}
54
55 if err := v.Set(version); err != nil {
56 return nil, err
57 }
58
59 return &v, nil
60}
61
62// Must is a helper for wrapping NewVersion and will panic if err is not nil.
63func Must(v *Version, err error) *Version {
64 if err != nil {
65 panic(err)
66 }
67 return v
68}
69
70// Set parses and updates v from the given version string. Implements flag.Value
71func (v *Version) Set(version string) error {
72 metadata := splitOff(&version, "+")
73 preRelease := PreRelease(splitOff(&version, "-"))
74 dotParts := strings.SplitN(version, ".", 3)
75
76 if len(dotParts) != 3 {
77 return fmt.Errorf("%s is not in dotted-tri format", version)
78 }
79
khenaidood948f772021-08-11 17:49:24 -040080 if err := validateIdentifier(string(preRelease)); err != nil {
81 return fmt.Errorf("failed to validate pre-release: %v", err)
82 }
83
84 if err := validateIdentifier(metadata); err != nil {
85 return fmt.Errorf("failed to validate metadata: %v", err)
86 }
87
khenaidooab1f7bd2019-11-14 14:00:27 -050088 parsed := make([]int64, 3, 3)
89
90 for i, v := range dotParts[:3] {
91 val, err := strconv.ParseInt(v, 10, 64)
92 parsed[i] = val
93 if err != nil {
94 return err
95 }
96 }
97
98 v.Metadata = metadata
99 v.PreRelease = preRelease
100 v.Major = parsed[0]
101 v.Minor = parsed[1]
102 v.Patch = parsed[2]
103 return nil
104}
105
106func (v Version) String() string {
107 var buffer bytes.Buffer
108
109 fmt.Fprintf(&buffer, "%d.%d.%d", v.Major, v.Minor, v.Patch)
110
111 if v.PreRelease != "" {
112 fmt.Fprintf(&buffer, "-%s", v.PreRelease)
113 }
114
115 if v.Metadata != "" {
116 fmt.Fprintf(&buffer, "+%s", v.Metadata)
117 }
118
119 return buffer.String()
120}
121
122func (v *Version) UnmarshalYAML(unmarshal func(interface{}) error) error {
123 var data string
124 if err := unmarshal(&data); err != nil {
125 return err
126 }
127 return v.Set(data)
128}
129
130func (v Version) MarshalJSON() ([]byte, error) {
131 return []byte(`"` + v.String() + `"`), nil
132}
133
134func (v *Version) UnmarshalJSON(data []byte) error {
135 l := len(data)
136 if l == 0 || string(data) == `""` {
137 return nil
138 }
139 if l < 2 || data[0] != '"' || data[l-1] != '"' {
140 return errors.New("invalid semver string")
141 }
142 return v.Set(string(data[1 : l-1]))
143}
144
145// Compare tests if v is less than, equal to, or greater than versionB,
146// returning -1, 0, or +1 respectively.
147func (v Version) Compare(versionB Version) int {
148 if cmp := recursiveCompare(v.Slice(), versionB.Slice()); cmp != 0 {
149 return cmp
150 }
151 return preReleaseCompare(v, versionB)
152}
153
154// Equal tests if v is equal to versionB.
155func (v Version) Equal(versionB Version) bool {
156 return v.Compare(versionB) == 0
157}
158
159// LessThan tests if v is less than versionB.
160func (v Version) LessThan(versionB Version) bool {
161 return v.Compare(versionB) < 0
162}
163
164// Slice converts the comparable parts of the semver into a slice of integers.
165func (v Version) Slice() []int64 {
166 return []int64{v.Major, v.Minor, v.Patch}
167}
168
169func (p PreRelease) Slice() []string {
170 preRelease := string(p)
171 return strings.Split(preRelease, ".")
172}
173
174func preReleaseCompare(versionA Version, versionB Version) int {
175 a := versionA.PreRelease
176 b := versionB.PreRelease
177
178 /* Handle the case where if two versions are otherwise equal it is the
179 * one without a PreRelease that is greater */
180 if len(a) == 0 && (len(b) > 0) {
181 return 1
182 } else if len(b) == 0 && (len(a) > 0) {
183 return -1
184 }
185
186 // If there is a prerelease, check and compare each part.
187 return recursivePreReleaseCompare(a.Slice(), b.Slice())
188}
189
190func recursiveCompare(versionA []int64, versionB []int64) int {
191 if len(versionA) == 0 {
192 return 0
193 }
194
195 a := versionA[0]
196 b := versionB[0]
197
198 if a > b {
199 return 1
200 } else if a < b {
201 return -1
202 }
203
204 return recursiveCompare(versionA[1:], versionB[1:])
205}
206
207func recursivePreReleaseCompare(versionA []string, versionB []string) int {
208 // A larger set of pre-release fields has a higher precedence than a smaller set,
209 // if all of the preceding identifiers are equal.
210 if len(versionA) == 0 {
211 if len(versionB) > 0 {
212 return -1
213 }
214 return 0
215 } else if len(versionB) == 0 {
216 // We're longer than versionB so return 1.
217 return 1
218 }
219
220 a := versionA[0]
221 b := versionB[0]
222
223 aInt := false
224 bInt := false
225
226 aI, err := strconv.Atoi(versionA[0])
227 if err == nil {
228 aInt = true
229 }
230
231 bI, err := strconv.Atoi(versionB[0])
232 if err == nil {
233 bInt = true
234 }
235
khenaidood948f772021-08-11 17:49:24 -0400236 // Numeric identifiers always have lower precedence than non-numeric identifiers.
237 if aInt && !bInt {
238 return -1
239 } else if !aInt && bInt {
240 return 1
241 }
242
khenaidooab1f7bd2019-11-14 14:00:27 -0500243 // Handle Integer Comparison
244 if aInt && bInt {
245 if aI > bI {
246 return 1
247 } else if aI < bI {
248 return -1
249 }
250 }
251
252 // Handle String Comparison
253 if a > b {
254 return 1
255 } else if a < b {
256 return -1
257 }
258
259 return recursivePreReleaseCompare(versionA[1:], versionB[1:])
260}
261
262// BumpMajor increments the Major field by 1 and resets all other fields to their default values
263func (v *Version) BumpMajor() {
264 v.Major += 1
265 v.Minor = 0
266 v.Patch = 0
267 v.PreRelease = PreRelease("")
268 v.Metadata = ""
269}
270
271// BumpMinor increments the Minor field by 1 and resets all other fields to their default values
272func (v *Version) BumpMinor() {
273 v.Minor += 1
274 v.Patch = 0
275 v.PreRelease = PreRelease("")
276 v.Metadata = ""
277}
278
279// BumpPatch increments the Patch field by 1 and resets all other fields to their default values
280func (v *Version) BumpPatch() {
281 v.Patch += 1
282 v.PreRelease = PreRelease("")
283 v.Metadata = ""
284}
khenaidood948f772021-08-11 17:49:24 -0400285
286// validateIdentifier makes sure the provided identifier satisfies semver spec
287func validateIdentifier(id string) error {
288 if id != "" && !reIdentifier.MatchString(id) {
289 return fmt.Errorf("%s is not a valid semver identifier", id)
290 }
291 return nil
292}
293
294// reIdentifier is a regular expression used to check that pre-release and metadata
295// identifiers satisfy the spec requirements
296var reIdentifier = regexp.MustCompile(`^[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*$`)