-
Notifications
You must be signed in to change notification settings - Fork 69
/
version.go
65 lines (59 loc) · 1.35 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
package openapi
import (
"fmt"
"strconv"
"strings"
"github.com/go-faster/errors"
)
// Version represents OpenAPI version.
type Version struct {
// Major is the major version number.
Major int
// Minor is the minor version number.
Minor int
// Patch is the patch version number.
Patch int
}
// MarshalText implements encoding.TextMarshaler.
func (v *Version) MarshalText() ([]byte, error) {
return []byte(v.String()), nil
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (v *Version) UnmarshalText(text []byte) error {
var (
r = string(text)
err error
target Version
)
switch n := strings.Split(r, "."); len(n) {
case 3:
target.Patch, err = strconv.Atoi(n[2])
if err != nil {
return errors.Wrap(err, "invalid patch version")
}
fallthrough
case 2:
target.Minor, err = strconv.Atoi(n[1])
if err != nil {
return errors.Wrap(err, "invalid minor version")
}
fallthrough
case 1:
major := n[0]
if len(n) == 1 {
major = r
}
target.Major, err = strconv.Atoi(major)
if err != nil {
return errors.Wrap(err, "invalid major version")
}
default:
return errors.New("version must have format <major>.<minor>[.<patch>]")
}
*v = target
return nil
}
// String returns the string representation of the version.
func (v Version) String() string {
return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
}