File: version.go

package info (click to toggle)
golang-github-tideland-golib 4.24.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,144 kB
  • sloc: makefile: 4
file content (338 lines) | stat: -rw-r--r-- 7,550 bytes parent folder | download | duplicates (2)
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
// Tideland Go Library - Version
//
// Copyright (C) 2014-2017 Frank Mueller / Tideland / Oldenburg / Germany
//
// All rights reserved. Use of this source code is governed
// by the new BSD license.

package version

//--------------------
// IMPORTS
//--------------------

import (
	"fmt"
	"strconv"
	"strings"

	"github.com/tideland/golib/errors"
)

//--------------------
// CONST
//--------------------

// Precedence describes if a version is newer, equal, or older.
type Precedence int

// Level describes the level, on which a version differentiates
// from an other.
type Level string

// Separator, precedences, and part identifiers.
const (
	Metadata = "+"

	Newer Precedence = 1
	Equal            = 0
	Older            = -1

	Major      Level = "major"
	Minor            = "minor"
	Patch            = "patch"
	PreRelease       = "pre-release"
	All              = "all"
)

//--------------------
// VERSION
//--------------------

// Version defines the interface of a version.
type Version interface {
	fmt.Stringer

	// Major returns the major version.
	Major() int

	// Minor returns the minor version.
	Minor() int

	// Patch return the path version.
	Patch() int

	// PreRelease returns a possible pre-release of the version.
	PreRelease() string

	// Metadata returns a possible build metadata of the version.
	Metadata() string

	// Compare compares this version to the passed one. The result
	// is from the perspective of this one.
	Compare(cv Version) (Precedence, Level)

	// Less returns true if this version is less than the passed one.
	// This means this version is older.
	Less(cv Version) bool
}

// vsn implements the version interface.
type vsn struct {
	major      int
	minor      int
	patch      int
	preRelease []string
	metadata   []string
}

// New returns a simple version instance. Parts of pre-release
// and metadata are passed as optional strings separated by
// version.Metadata ("+").
func New(major, minor, patch int, prmds ...string) Version {
	if major < 0 {
		major = 0
	}
	if minor < 0 {
		minor = 0
	}
	if patch < 0 {
		patch = 0
	}
	v := &vsn{
		major: major,
		minor: minor,
		patch: patch,
	}
	isPR := true
	for _, prmd := range prmds {
		if isPR {
			if prmd == Metadata {
				isPR = false
				continue
			}
			v.preRelease = append(v.preRelease, validID(prmd, true))
		} else {
			v.metadata = append(v.metadata, validID(prmd, false))
		}
	}
	return v
}

// Parse retrieves a version out of a string.
func Parse(vsnstr string) (Version, error) {
	// Split version, pre-release, and metadata.
	npmstrs, err := splitVersionString(vsnstr)
	if err != nil {
		return nil, err
	}
	// Parse these parts.
	nums, err := parseNumberString(npmstrs[0])
	if err != nil {
		return nil, err
	}
	prmds := []string{}
	if npmstrs[1] != "" {
		prmds = strings.Split(npmstrs[1], ".")
	}
	if npmstrs[2] != "" {
		prmds = append(prmds, Metadata)
		prmds = append(prmds, strings.Split(npmstrs[2], ".")...)
	}
	// Done.
	return New(nums[0], nums[1], nums[2], prmds...), nil
}

// Major implements the Version interface.
func (v *vsn) Major() int {
	return v.major
}

// Minor implements the Version interface.
func (v *vsn) Minor() int {
	return v.minor
}

// Patch implements the Version interface.
func (v *vsn) Patch() int {
	return v.patch
}

// PreRelease implements the Version interface.
func (v *vsn) PreRelease() string {
	return strings.Join(v.preRelease, ".")
}

// Metadata implements the Version interface.
func (v *vsn) Metadata() string {
	return strings.Join(v.metadata, ".")
}

// Compare implements the Version interface.
func (v *vsn) Compare(cv Version) (Precedence, Level) {
	// Standard version parts.
	switch {
	case v.major < cv.Major():
		return Older, Major
	case v.major > cv.Major():
		return Newer, Major
	case v.minor < cv.Minor():
		return Older, Minor
	case v.minor > cv.Minor():
		return Newer, Minor
	case v.patch < cv.Patch():
		return Older, Patch
	case v.patch > cv.Patch():
		return Newer, Patch
	}
	// Now the parts of the pre-release.
	cvpr := []string{}
	for _, cvprPart := range strings.Split(cv.PreRelease(), ".") {
		if cvprPart != "" {
			cvpr = append(cvpr, cvprPart)
		}
	}
	vlen := len(v.preRelease)
	cvlen := len(cvpr)
	count := vlen
	if cvlen < vlen {
		count = cvlen
	}
	for i := 0; i < count; i++ {
		vn, verr := strconv.Atoi(v.preRelease[i])
		cvn, cverr := strconv.Atoi(cvpr[i])
		if verr == nil && cverr == nil {
			// Numerical comparison.
			switch {
			case vn < cvn:
				return Older, PreRelease
			case vn > cvn:
				return Newer, PreRelease
			}
			continue
		}
		// Alphanumerical comparison.
		switch {
		case v.preRelease[i] < cvpr[i]:
			return Older, PreRelease
		case v.preRelease[i] > cvpr[i]:
			return Newer, PreRelease
		}
	}
	// Still no clean result, so the shorter
	// pre-relese is older.
	switch {
	case vlen < cvlen:
		return Newer, PreRelease
	case vlen > cvlen:
		return Older, PreRelease
	}
	// Last but not least: we are equal.
	return Equal, All
}

// Less implements the Version interface.
func (v *vsn) Less(cv Version) bool {
	precedence, _ := v.Compare(cv)
	return precedence == Older
}

// String implements the fmt.Stringer interface.
func (v *vsn) String() string {
	vs := fmt.Sprintf("%d.%d.%d", v.major, v.minor, v.patch)
	if len(v.preRelease) > 0 {
		vs += "-" + v.PreRelease()
	}
	if len(v.metadata) > 0 {
		vs += Metadata + v.Metadata()
	}
	return vs
}

//--------------------
// TOOLS
//--------------------

// validID reduces the passed identifier to a valid one. If we care
// for numeric identifiers leading zeros will be removed.
func validID(id string, numeric bool) string {
	out := []rune{}
	letter := false
	digit := false
	hyphen := false
	for _, r := range id {
		switch {
		case r >= 'a' && r <= 'z':
			letter = true
			out = append(out, r)
		case r >= 'A' && r <= 'Z':
			letter = true
			out = append(out, r)
		case r >= '0' && r <= '9':
			digit = true
			out = append(out, r)
		case r == '-':
			hyphen = true
			out = append(out, r)
		}
	}
	if numeric && digit && !letter && !hyphen {
		// Digits only, and we care for it.
		// Remove leading zeros.
		for len(out) > 0 && out[0] == '0' {
			out = out[1:]
		}
		if len(out) == 0 {
			out = []rune{'0'}
		}
	}
	return string(out)
}

// splitVersionString separates the version string into numbers,
// pre-release, and metadata strings.
func splitVersionString(vsnstr string) ([]string, error) {
	npXm := strings.SplitN(vsnstr, Metadata, 2)
	switch len(npXm) {
	case 1:
		nXp := strings.SplitN(npXm[0], "-", 2)
		switch len(nXp) {
		case 1:
			return []string{nXp[0], "", ""}, nil
		case 2:
			return []string{nXp[0], nXp[1], ""}, nil
		}
	case 2:
		nXp := strings.SplitN(npXm[0], "-", 2)
		switch len(nXp) {
		case 1:
			return []string{nXp[0], "", npXm[1]}, nil
		case 2:
			return []string{nXp[0], nXp[1], npXm[1]}, nil
		}
	}
	return nil, errors.New(ErrIllegalVersionFormat, errorMessages, "wrong parts")
}

// parseNumberString retrieves major, minor, and patch number
// of the passed string.
func parseNumberString(nstr string) ([]int, error) {
	nstrs := strings.Split(nstr, ".")
	if len(nstrs) < 1 || len(nstrs) > 3 {
		return nil, errors.New(ErrIllegalVersionFormat, errorMessages, "wrong number parts")
	}
	vsn := []int{1, 0, 0}
	for i, nstr := range nstrs {
		num, err := strconv.Atoi(nstr)
		if err != nil {
			return nil, errors.New(ErrIllegalVersionFormat, errorMessages, err.Error())
		}
		if num < 0 {
			return nil, errors.New(ErrIllegalVersionFormat, errorMessages, "negative version number")
		}
		vsn[i] = num
	}
	return vsn, nil
}

// EOF