This repository has been archived by the owner on Jul 7, 2020. It is now read-only.
/
version.go
80 lines (67 loc) · 1.8 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
package nut
import (
"fmt"
"regexp"
"strconv"
)
// Current format for nut version.
var VersionRegexp = regexp.MustCompile(`^(\d+).(\d+).(\d+)$`)
// Describes nut version. See http://gonuts.io/-/doc/versioning for explanation of version specification.
type Version struct {
Major int
Minor int
Patch int
}
// Parse and set version.
func NewVersion(version string) (v *Version, err error) {
v = new(Version)
err = v.setVersion(version)
return
}
// Return version as string in current format.
func (v Version) String() string {
res := fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
if !VersionRegexp.MatchString(res) { // sanity check
panic(fmt.Errorf("%s not matches %s", res, VersionRegexp))
}
return res
}
// Returns true if left < right, false otherwise.
func (left *Version) Less(right *Version) bool {
if left.Major < right.Major {
return true
} else if left.Major > right.Major {
return false
}
if left.Minor < right.Minor {
return true
} else if left.Minor > right.Minor {
return false
}
if left.Patch < right.Patch {
return true
} else if left.Patch > right.Patch {
return false
}
// left == right => "left < right" is false
return false
}
// Marshal to JSON.
func (v *Version) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%s"`, v)), nil
}
// Unmarshal from JSON.
func (v *Version) UnmarshalJSON(b []byte) error {
return v.setVersion(string(b[1 : len(b)-1]))
}
func (v *Version) setVersion(version string) (err error) {
parsed := VersionRegexp.FindAllStringSubmatch(version, -1)
if (parsed == nil) || (len(parsed[0]) != 4) {
err = fmt.Errorf("Bad format for version %q. See http://gonuts.io/-/doc/versioning", version)
return
}
v.Major, _ = strconv.Atoi(parsed[0][1])
v.Minor, _ = strconv.Atoi(parsed[0][2])
v.Patch, _ = strconv.Atoi(parsed[0][3])
return
}