forked from desbo/merge-pr-action
-
Notifications
You must be signed in to change notification settings - Fork 0
/
semver.go
89 lines (69 loc) · 1.67 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
package main
import (
"fmt"
"regexp"
"strings"
"github.com/blang/semver/v4"
)
type versionUpgrade struct {
From semver.Version
To semver.Version
}
type upgradeType int
const (
noChange = iota
patch
minor
major
)
func (u upgradeType) String() string {
return map[upgradeType]string{
noChange: "no change",
patch: "patch",
minor: "minor",
major: "major",
}[u]
}
func (vu versionUpgrade) String() string {
return fmt.Sprintf("upgrade from %v to %v (%v)", vu.From, vu.To, vu.UpgradeType())
}
func (vu *versionUpgrade) UpgradeType() upgradeType {
if vu.To.Major > vu.From.Major {
return major
}
if vu.To.Minor > vu.From.Minor {
return minor
}
if vu.To.Patch > vu.From.Patch {
return patch
}
return noChange
}
func parseUpgradeType(s string) (upgradeType, error) {
parsed, ok := map[string]upgradeType{
"major": major,
"minor": minor,
"patch": patch,
}[strings.TrimSpace(strings.ToLower(s))]
if !ok {
return noChange, fmt.Errorf("unrecognised allowed update value %v", s)
}
return parsed, nil
}
// extract two versions from a string, order them and return a VersionUpgrade
func parseVersionUpgrade(s string) (*versionUpgrade, error) {
semVerRegex := regexp.MustCompile(`([0-9]+)\.([0-9]+)\.([0-9]+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+)?`)
matches := semVerRegex.FindAllString(s, 2)
if len(matches) != 2 {
return nil, fmt.Errorf("unable to parse 2 versions from %v", s)
}
a := semver.MustParse(matches[0])
b := semver.MustParse(matches[1])
if a.LTE(b) {
return &versionUpgrade{a, b}, nil
}
return &versionUpgrade{b, a}, nil
}
func allowed(allowed, proposed upgradeType) bool {
return proposed <= allowed
}