forked from git-chglog/git-chglog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tag_reader.go
127 lines (103 loc) · 2.28 KB
/
tag_reader.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
120
121
122
123
124
125
126
127
package chglog
import (
"fmt"
"regexp"
"sort"
"strings"
"time"
gitcmd "github.com/tsuyoshiwada/go-gitcmd"
)
type tagReader struct {
client gitcmd.Client
format string
separator string
reFilter *regexp.Regexp
}
func newTagReader(client gitcmd.Client, filterPattern string) *tagReader {
return &tagReader{
client: client,
separator: "@@__CHGLOG__@@",
reFilter: regexp.MustCompile(filterPattern),
}
}
func (r *tagReader) ReadAll() ([]*Tag, error) {
out, err := r.client.Exec(
"for-each-ref",
"--format",
"%(refname)"+r.separator+"%(subject)"+r.separator+"%(taggerdate)"+r.separator+"%(authordate)",
"refs/tags",
)
tags := []*Tag{}
if err != nil {
return tags, fmt.Errorf("failed to get git-tag: %s", err.Error())
}
lines := strings.Split(out, "\n")
for _, line := range lines {
tokens := strings.Split(line, r.separator)
if len(tokens) != 4 {
continue
}
name := r.parseRefname(tokens[0])
subject := r.parseSubject(tokens[1])
date, err := r.parseDate(tokens[2])
if err != nil {
t, err2 := r.parseDate(tokens[3])
if err2 != nil {
return nil, err2
}
date = t
}
if r.reFilter != nil {
if !r.reFilter.MatchString(name) {
continue
}
}
tags = append(tags, &Tag{
Name: name,
Subject: subject,
Date: date,
})
}
r.sortTags(tags)
r.assignPreviousAndNextTag(tags)
return tags, nil
}
func (*tagReader) parseRefname(input string) string {
return strings.Replace(input, "refs/tags/", "", 1)
}
func (*tagReader) parseSubject(input string) string {
return strings.TrimSpace(input)
}
func (*tagReader) parseDate(input string) (time.Time, error) {
return time.Parse("Mon Jan 2 15:04:05 2006 -0700", input)
}
func (*tagReader) assignPreviousAndNextTag(tags []*Tag) {
total := len(tags)
for i, tag := range tags {
var (
next *RelateTag
prev *RelateTag
)
if i > 0 {
next = &RelateTag{
Name: tags[i-1].Name,
Subject: tags[i-1].Subject,
Date: tags[i-1].Date,
}
}
if i+1 < total {
prev = &RelateTag{
Name: tags[i+1].Name,
Subject: tags[i+1].Subject,
Date: tags[i+1].Date,
}
}
tag.Next = next
tag.Previous = prev
}
}
func (*tagReader) sortTags(tags []*Tag) {
sort.Slice(tags, func(i, j int) bool {
return !tags[i].Date.Before(tags[j].Date)
})
}