-
Notifications
You must be signed in to change notification settings - Fork 0
/
semver.go
119 lines (99 loc) · 2.11 KB
/
semver.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
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
package mikku
import (
"fmt"
"regexp"
"strconv"
"strings"
)
const (
semVerPrefix = "v"
)
const (
majorIdx = iota
minorIdx
patchIdx
)
type bumpType int
const (
major bumpType = iota + 1
minor
patch
version
)
var semVerReg = regexp.MustCompile(`^v([0-9]+)\.([0-9]+)\.([0-9]+)`)
// determineNewTag bump version if the typORVer is major, minor, or patch
// otherwise, use the given version without change
func determineNewTag(currentTag string, typORVer string) (string, error) {
bt := strToBumpType(typORVer)
if bt == version {
if !validSemver(typORVer) {
return "", errInvalidSemanticVersioningTag
}
return typORVer, nil
}
if !validSemver(currentTag) {
return "", errInvalidSemanticVersioningTag
}
newTag, err := bumpVersion(currentTag, bt)
if err != nil {
return "", fmt.Errorf("bump version: %w", err)
}
return newTag, nil
}
func validSemver(ver string) bool {
return semVerReg.Match([]byte(ver))
}
func strToBumpType(str string) bumpType {
switch str {
case "major":
return major
case "minor":
return minor
case "patch":
return patch
default:
return version
}
}
func bumpVersion(tag string, typ bumpType) (string, error) {
tag = strings.TrimPrefix(tag, semVerPrefix)
splitTag := strings.Split(tag, ".")
versions, err := strsToInts(splitTag)
if err != nil {
return "", fmt.Errorf("strsToInts: %w", err)
}
switch typ {
case major:
versions[majorIdx]++
versions[minorIdx] = 0
versions[patchIdx] = 0
case minor:
versions[minorIdx]++
versions[patchIdx] = 0
case patch:
versions[patchIdx]++
default:
return "", fmt.Errorf("invalid bump type: %w", err)
}
return createSemanticVersion(versions), nil
}
func strsToInts(strs []string) ([]int, error) {
ints := make([]int, len(strs))
for idx, s := range strs {
converted, err := strconv.Atoi(s)
if err != nil {
return nil, fmt.Errorf("convert string to int: %w", err)
}
ints[idx] = converted
}
return ints, nil
}
func createSemanticVersion(versions []int) string {
sm := semVerPrefix
sm += strconv.Itoa(versions[0])
for _, v := range versions[1:] {
sm += "."
sm += strconv.Itoa(v)
}
return sm
}