generated from layer5io/layer5-repo-template
-
Notifications
You must be signed in to change notification settings - Fork 79
/
sortversions.go
79 lines (73 loc) · 1.72 KB
/
sortversions.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
package utils
import (
"sort"
"strconv"
"strings"
)
type dottedStrings []string
func (d dottedStrings) Less(i, j int) bool {
si := cleanup(d[i])
sj := cleanup(d[j])
siarr := strings.Split(si, ".")
sjarr := strings.Split(sj, ".")
diff := len(siarr) - len(sjarr)
//Making boths strings the same length
if diff > 0 {
for diff != 0 {
sjarr = append(sjarr, "3")
diff--
}
} else {
for diff != 0 {
siarr = append(siarr, "3")
diff++
}
}
// The string will both be the same length
for i := range siarr {
//We can be sure that siarr and sjarr are numeric string array, hence Atoi can be safely used
p, _ := strconv.Atoi(siarr[i])
q, _ := strconv.Atoi(sjarr[i])
if p < q {
return true
}
if q < p {
return false
}
}
return false
}
func (d dottedStrings) Len() int {
return len(d)
}
func (d dottedStrings) Swap(i, j int) {
d[i], d[j] = d[j], d[i]
}
func cleanup(s string) string {
if strings.HasPrefix(s, "stable") {
s = strings.TrimPrefix(s, "stable")
s += "stable"
}
s = strings.Replace(s, "alpha", ".0", -1)
s = strings.Replace(s, "beta", ".1", -1)
s = strings.Replace(s, "rc", ".2", -1)
s = strings.Replace(s, "stable", ".4", -1)
s1 := ""
for _, s := range s {
if (s >= 48 && s <= 57) || s == 46 {
s1 += string(s)
}
}
return s1
}
// SortDottedStringsByDigits takes version-like dot separated digits in string format and returns them in sorted normalized form.
// Takes [v1.4.3,0.9.3,v0.0.0]=> returns [v0.0.0,0.9.3,v1.4.3]
// This function ignores all letters except for:
// - numeric digits
// - alpha, beta, rc, stable
// For the same version, stable is preferred over edge
func SortDottedStringsByDigits(s []string) []string {
s1 := dottedStrings(s)
sort.Sort(s1)
return s1
}