-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchangelog.go
244 lines (213 loc) · 5.86 KB
/
changelog.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
package changelog
import (
"context"
"fmt"
"io"
"io/ioutil"
"net/url"
"os"
"path"
"sort"
"strings"
"sync"
"text/template"
"github.com/google/go-github/v29/github"
log "github.com/sirupsen/logrus"
"golang.org/x/oauth2"
"github.com/jimschubert/changelog/model"
"github.com/jimschubert/changelog/service"
)
const emptyTree = "master~1"
const defaultEnd = "master"
const defaultTemplate = `{{define "PullTemplate"}} ({{if .IsPull -}}
{{if .PullURL}}[contributed]({{.PullURL}}){{else}}contributed{{end}} by {{end}}{{if .AuthorURL -}}
[{{.Author}}]({{.AuthorURL}}){{else}}{{.Author}}{{end -}})
{{- end -}}
{{define "CommitTemplate" -}}
{{if .CommitURL}}[{{.CommitHashShort}}]({{.CommitURL}}){{else}}{{.CommitHashShort}}{{end -}}
{{- end -}}
{{define "GroupTemplate" -}}
{{- range .Grouped}}
### {{ .Name }}
{{range .Items -}}
* {{template "CommitTemplate" . }} {{.Title}}{{template "PullTemplate" . }}
{{end -}}
{{end -}}
{{end -}}
{{define "FlatTemplate" -}}
{{range .Items -}}
* {{template "CommitTemplate" . }} {{.Title}}{{template "PullTemplate" . }}
{{end -}}
{{end -}}
{{define "DefaultTemplate" -}}
## {{.Version}}
{{if len .Grouped -}}
{{template "GroupTemplate" . -}}
{{- else}}
{{template "FlatTemplate" . -}}
{{end}}
<em>For more details, see <a href="{{.CompareURL}}">{{.PreviousVersion}}..{{.Version}}</a></em>
{{end -}}
{{template "DefaultTemplate" . -}}
`
// Changelog holds the information required to define the bounds for the changelog
type Changelog struct {
*model.Config
From string
To string
}
// Generate will format a changelog, writing to the supplied writer
func (c *Changelog) Generate(writer io.Writer) error {
ctx := context.Background()
token, found := os.LookupEnv("GITHUB_TOKEN")
if !found {
log.Fatal("Environment variable GITHUB_TOKEN not found.")
os.Exit(1)
}
if len(c.From) == 0 {
c.From = emptyTree
}
if len(c.To) == 0 {
c.To = defaultEnd
}
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
tc := oauth2.NewClient(ctx, ts)
var client *github.Client
if c.Config.Enterprise != nil && len(*c.Config.Enterprise) > 0 {
cl, e := github.NewEnterpriseClient(*c.Config.Enterprise, *c.Config.Enterprise, tc)
if e != nil {
return e
}
client = cl
} else {
client = github.NewClient(tc)
}
doneChan := make(chan struct{})
errorChan := make(chan error)
ciChan := make(chan *model.ChangeItem)
wg := sync.WaitGroup{}
var target service.Store
if c.Config.GetPreferLocal() {
target = service.NewLocalGitService().WithClient(client).WithConfig(c.Config)
} else {
target = service.NewGitHubService().WithClient(client).WithConfig(c.Config)
}
err := target.Process(&ctx, &wg, ciChan, c.From, c.To)
if err != nil {
return err
}
go wait(doneChan, &wg)
all := make([]model.ChangeItem, 0)
for {
select {
case e := <-errorChan:
return e
case ci := <-ciChan:
if ci != nil {
all = append(all, *ci)
}
case <-doneChan:
return c.writeChangelog(all, writer)
}
}
}
func (c *Changelog) GetGitURLs() (*model.GitURLs, error) {
gh := "https://github.com"
if c.Enterprise != nil {
gh = strings.TrimRight(*c.Enterprise, "/api")
}
u, err := url.Parse(gh)
if err != nil {
return nil, err
}
create := func(op string) string {
end := fmt.Sprintf("%s...%s%s", c.From, c.To, op)
u.Path = path.Join(u.Path, c.Owner, c.Repo, "compare", end)
return u.String()
}
return &model.GitURLs{
CompareURL: create(""),
DiffURL: create(".diff"),
PatchURL: create(".patch"),
}, nil
}
func wait(ch chan struct{}, wg *sync.WaitGroup) {
wg.Wait()
ch <- struct{}{}
}
func (c *Changelog) writeChangelog(all []model.ChangeItem, writer io.Writer) error {
var compareURL = ""
var diffURL = ""
var patchURL = ""
u, err := c.GetGitURLs()
if err != nil {
log.Warn("Unable to determine urls for compare, diff, and patch.")
} else {
compareURL = u.CompareURL
diffURL = u.DiffURL
patchURL = u.PatchURL
}
switch *c.Config.SortDirection {
case model.Ascending:
sort.Sort(CommitAscendingSorter(all))
case model.Descending:
sort.Sort(CommitDescendingSorter(all))
}
grouped := make(map[string][]model.ChangeItem)
for _, item := range all {
g := item.Group()
if len(g) > 0 {
grouped[g] = append(grouped[g], item)
}
}
templateGroups := make([]model.TemplateGroup, 0)
if c.Groupings != nil {
for _, grouping := range *c.Groupings {
if grouping.Name != "" {
if items, ok := grouped[grouping.Name]; ok && len(items) > 0 {
log.WithFields(log.Fields{
"name": grouping.Name,
"count": len(items),
}).Debug("found template grouping data")
templateGroups = append(templateGroups, model.TemplateGroup{
Name: grouping.Name,
Items: items,
})
}
}
}
}
d := &model.TemplateData{
PreviousVersion: c.From,
Version: c.To,
Items: all,
CompareURL: compareURL,
DiffURL: diffURL,
PatchURL: patchURL,
Grouped: templateGroups,
}
var tpl = defaultTemplate
if c.Config.Template != nil {
b, templateErr := ioutil.ReadFile(*c.Config.Template)
if templateErr != nil {
log.Warn("Unable to load template. Using default.")
} else {
log.Debug("Using default template.")
tpl = string(b)
}
}
tmpl, err := template.New("changelog").Parse(tpl)
if err != nil {
return err
}
_ = tmpl.Execute(writer, d)
return nil
}
type CommitDescendingSorter []model.ChangeItem
func (a CommitDescendingSorter) Len() int { return len(a) }
func (a CommitDescendingSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a CommitDescendingSorter) Less(i, j int) bool { return a[i].Date().Unix() > a[j].Date().Unix() }
type CommitAscendingSorter []model.ChangeItem
func (a CommitAscendingSorter) Len() int { return len(a) }
func (a CommitAscendingSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a CommitAscendingSorter) Less(i, j int) bool { return a[i].Date().Unix() < a[j].Date().Unix() }