-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathversion.go
74 lines (60 loc) · 1.43 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
package semver
import (
"errors"
"strconv"
"strings"
)
type VersionType string
const (
PATCH VersionType = "patch"
MINOR VersionType = "minor"
MAJOR VersionType = "major"
)
type Version interface {
Get(versionType string) (string, error)
SetNext(versionType string) (string, error)
}
type version struct {
current string
}
func NewVersion(v string) (Version, error) {
if !IsValidVersion(v) {
return nil, errors.New("version invalid - please provide version number in the following format: <major>.<minor>.<patch>")
}
return &version{v}, nil
}
func (v *version) Get(vt string) (string, error) {
versionType := VersionType(vt)
numbers := strings.Split(v.current, ".")
for i, n := range numbers {
numbers[i] = strings.TrimSuffix(n, "\n")
}
var err error
switch versionType {
case MAJOR:
major, e := strconv.Atoi(numbers[0])
err = e
numbers[0] = strconv.Itoa(major + 1)
numbers[1] = "0"
numbers[2] = "0"
case MINOR:
minor, e := strconv.Atoi(numbers[1])
err = e
numbers[1] = strconv.Itoa(minor + 1)
numbers[2] = "0"
case PATCH:
patch, e := strconv.Atoi(numbers[2])
err = e
numbers[2] = strconv.Itoa(patch + 1)
}
return strings.Join(numbers, "."), err
}
func (v *version) SetNext(vt string) (string, error) {
versionType := VersionType(vt)
if !IsValidNextVersionType(versionType) {
return "", errors.New("invalid next version type")
}
next, _ := v.Get(vt)
v.current = next
return v.current, nil
}