-
Notifications
You must be signed in to change notification settings - Fork 0
/
prev.go
93 lines (89 loc) · 1.91 KB
/
prev.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
package main
import (
"context"
"sort"
"strings"
"github.com/Masterminds/semver/v3"
)
type getPrevTagOpts struct {
Head string
RepoDir string
Prefixes []string
Fallback string
Constraints *semver.Constraints
}
func getPrevTag(ctx context.Context, options *getPrevTagOpts) (string, error) {
if options == nil {
options = &getPrevTagOpts{}
}
head := options.Head
if head == "" {
head = "HEAD"
}
prefixes := options.Prefixes
if len(prefixes) == 0 {
prefixes = []string{""}
}
cmdLine := []string{"git", "rev-list", "--pretty=%D", head}
type prefixedVersion struct {
prefix string
ver *semver.Version
}
var versions []prefixedVersion
done := false
err := runCmdHandleLines(ctx, options.RepoDir, cmdLine, func(line string, cancel context.CancelFunc) {
if done {
return
}
refs := strings.Split(line, ", ")
for _, r := range refs {
var ok bool
r, ok = strings.CutPrefix(r, "tag: ")
if !ok {
continue
}
for _, prefix := range options.Prefixes {
r, ok = strings.CutPrefix(r, prefix)
if !ok {
continue
}
ver, err := semver.StrictNewVersion(r)
if err != nil {
continue
}
if options.Constraints != nil && !options.Constraints.Check(ver) {
continue
}
versions = append(versions, prefixedVersion{prefix, ver})
}
}
if len(versions) > 0 {
cancel()
done = true
}
})
if err != nil {
return "", err
}
// order first by version then by index of prefix in prefixes
sort.Slice(versions, func(i, j int) bool {
a, b := versions[i], versions[j]
if !a.ver.Equal(b.ver) {
return a.ver.GreaterThan(b.ver)
}
for _, prefix := range prefixes {
if a.prefix == prefix {
return b.prefix != prefix
}
if b.prefix == prefix {
return false
}
}
return false
})
if len(versions) == 0 {
return options.Fallback, nil
}
winner := versions[0]
return winner.prefix + winner.ver.Original(), nil
}