-
-
Notifications
You must be signed in to change notification settings - Fork 910
/
changelog.go
383 lines (334 loc) · 9.31 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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
// Package changelog provides the release changelog to goreleaser.
package changelog
import (
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"github.com/apex/log"
"github.com/goreleaser/goreleaser/internal/client"
"github.com/goreleaser/goreleaser/internal/git"
"github.com/goreleaser/goreleaser/internal/tmpl"
"github.com/goreleaser/goreleaser/pkg/context"
)
// ErrInvalidSortDirection happens when the sort order is invalid.
var ErrInvalidSortDirection = errors.New("invalid sort direction")
const li = "* "
type useChangelog string
func (u useChangelog) formatable() bool {
return u != "github-native"
}
const (
useGit = "git"
useGitHub = "github"
useGitLab = "gitlab"
useGitHubNative = "github-native"
)
// Pipe for checksums.
type Pipe struct{}
func (Pipe) String() string { return "generating changelog" }
func (Pipe) Skip(ctx *context.Context) bool { return ctx.Config.Changelog.Skip || ctx.Snapshot }
// Run the pipe.
func (Pipe) Run(ctx *context.Context) error {
notes, err := loadContent(ctx, ctx.ReleaseNotesFile, ctx.ReleaseNotesTmpl)
if err != nil {
return err
}
ctx.ReleaseNotes = notes
if ctx.ReleaseNotesFile != "" || ctx.ReleaseNotesTmpl != "" {
return nil
}
footer, err := loadContent(ctx, ctx.ReleaseFooterFile, ctx.ReleaseFooterTmpl)
if err != nil {
return err
}
header, err := loadContent(ctx, ctx.ReleaseHeaderFile, ctx.ReleaseHeaderTmpl)
if err != nil {
return err
}
if err := checkSortDirection(ctx.Config.Changelog.Sort); err != nil {
return err
}
entries, err := buildChangelog(ctx)
if err != nil {
return err
}
changes, err := formatChangelog(ctx, entries)
if err != nil {
return err
}
changelogElements := []string{changes}
if header != "" {
changelogElements = append([]string{header}, changelogElements...)
}
if footer != "" {
changelogElements = append(changelogElements, footer)
}
ctx.ReleaseNotes = strings.Join(changelogElements, "\n\n")
if !strings.HasSuffix(ctx.ReleaseNotes, "\n") {
ctx.ReleaseNotes += "\n"
}
path := filepath.Join(ctx.Config.Dist, "CHANGELOG.md")
log.WithField("changelog", path).Info("writing")
return os.WriteFile(path, []byte(ctx.ReleaseNotes), 0o644) //nolint: gosec
}
func formatChangelog(ctx *context.Context, entries []string) (string, error) {
newLine := "\n"
if ctx.TokenType == context.TokenTypeGitLab || ctx.TokenType == context.TokenTypeGitea {
// We need two or more whitespace to let markdown interpret
// it as newline. See https://docs.gitlab.com/ee/user/markdown.html#newlines for details
log.Debug("is gitlab or gitea changelog")
newLine = " \n"
}
if !useChangelog(ctx.Config.Changelog.Use).formatable() {
return strings.Join(entries, newLine), nil
}
result := []string{"## Changelog"}
if len(ctx.Config.Changelog.Groups) == 0 {
log.Debug("not grouping entries")
return strings.Join(append(result, filterAndPrefixItems(entries)...), newLine), nil
}
log.Debug("grouping entries")
groups := ctx.Config.Changelog.Groups
sort.Slice(groups, func(i, j int) bool { return groups[i].Order < groups[j].Order })
for _, group := range groups {
items := make([]string, 0)
if group.Regexp == "" {
// If no regexp is provided, we purge all strikethrough entries and add remaining entries to the list
items = filterAndPrefixItems(entries)
// clear array
entries = nil
} else {
regex, err := regexp.Compile(group.Regexp)
if err != nil {
return "", fmt.Errorf("failed to group into %q: %w", group.Title, err)
}
for i, entry := range entries {
match := regex.MatchString(entry)
if match {
items = append(items, li+entry)
// Striking out the matched entry
entries[i] = ""
}
}
}
if len(items) > 0 {
result = append(result, fmt.Sprintf("### %s", group.Title))
result = append(result, items...)
}
}
return strings.Join(result, newLine), nil
}
func filterAndPrefixItems(ss []string) []string {
var r []string
for _, s := range ss {
if s != "" {
r = append(r, li+s)
}
}
return r
}
func loadFromFile(file string) (string, error) {
bts, err := os.ReadFile(file)
if err != nil {
return "", err
}
log.WithField("file", file).Debugf("read %d bytes", len(bts))
return string(bts), nil
}
func checkSortDirection(mode string) error {
switch mode {
case "":
fallthrough
case "asc":
fallthrough
case "desc":
return nil
}
return ErrInvalidSortDirection
}
func buildChangelog(ctx *context.Context) ([]string, error) {
log, err := getChangelog(ctx, ctx.Git.CurrentTag)
if err != nil {
return nil, err
}
entries := strings.Split(log, "\n")
if lastLine := entries[len(entries)-1]; strings.TrimSpace(lastLine) == "" {
entries = entries[0 : len(entries)-1]
}
if !useChangelog(ctx.Config.Changelog.Use).formatable() {
return entries, nil
}
entries, err = filterEntries(ctx, entries)
if err != nil {
return entries, err
}
return sortEntries(ctx, entries), nil
}
func filterEntries(ctx *context.Context, entries []string) ([]string, error) {
for _, filter := range ctx.Config.Changelog.Filters.Exclude {
r, err := regexp.Compile(filter)
if err != nil {
return entries, err
}
entries = remove(r, entries)
}
return entries, nil
}
func sortEntries(ctx *context.Context, entries []string) []string {
direction := ctx.Config.Changelog.Sort
if direction == "" {
return entries
}
result := make([]string, len(entries))
copy(result, entries)
sort.Slice(result, func(i, j int) bool {
imsg := extractCommitInfo(result[i])
jmsg := extractCommitInfo(result[j])
if direction == "asc" {
return strings.Compare(imsg, jmsg) < 0
}
return strings.Compare(imsg, jmsg) > 0
})
return result
}
func remove(filter *regexp.Regexp, entries []string) (result []string) {
for _, entry := range entries {
if !filter.MatchString(extractCommitInfo(entry)) {
result = append(result, entry)
}
}
return result
}
func extractCommitInfo(line string) string {
return strings.Join(strings.Split(line, " ")[1:], " ")
}
func getChangelog(ctx *context.Context, tag string) (string, error) {
prev := ctx.Git.PreviousTag
if prev == "" {
// get first commit
result, err := git.Clean(git.Run(ctx, "rev-list", "--max-parents=0", "HEAD"))
if err != nil {
return "", err
}
prev = result
}
return doGetChangelog(ctx, prev, tag)
}
func doGetChangelog(ctx *context.Context, prev, tag string) (string, error) {
l, err := getChangeloger(ctx)
if err != nil {
return "", err
}
return l.Log(ctx, prev, tag)
}
func getChangeloger(ctx *context.Context) (changeloger, error) {
switch ctx.Config.Changelog.Use {
case useGit:
fallthrough
case "":
return gitChangeloger{}, nil
case useGitHub:
fallthrough
case useGitLab:
return newSCMChangeloger(ctx)
case useGitHubNative:
return newGithubChangeloger(ctx)
default:
return nil, fmt.Errorf("invalid changelog.use: %q", ctx.Config.Changelog.Use)
}
}
func newGithubChangeloger(ctx *context.Context) (changeloger, error) {
cli, err := client.NewGitHub(ctx, ctx.Token)
if err != nil {
return nil, err
}
repo, err := git.ExtractRepoFromConfig(ctx)
if err != nil {
return nil, err
}
if err := repo.CheckSCM(); err != nil {
return nil, err
}
return &githubNativeChangeloger{
client: cli,
repo: client.Repo{
Owner: repo.Owner,
Name: repo.Name,
},
}, nil
}
func newSCMChangeloger(ctx *context.Context) (changeloger, error) {
cli, err := client.New(ctx)
if err != nil {
return nil, err
}
repo, err := git.ExtractRepoFromConfig(ctx)
if err != nil {
return nil, err
}
if err := repo.CheckSCM(); err != nil {
return nil, err
}
return &scmChangeloger{
client: cli,
repo: client.Repo{
Owner: repo.Owner,
Name: repo.Name,
},
}, nil
}
func loadContent(ctx *context.Context, fileName, tmplName string) (string, error) {
if tmplName != "" {
log.Debugf("loading template %q", tmplName)
content, err := loadFromFile(tmplName)
if err != nil {
return "", err
}
content, err = tmpl.New(ctx).Apply(content)
if strings.TrimSpace(content) == "" && err == nil {
log.Warnf("loaded %q, but it evaluates to an empty string", tmplName)
}
return content, err
}
if fileName != "" {
log.Debugf("loading file %q", fileName)
content, err := loadFromFile(fileName)
if strings.TrimSpace(content) == "" && err == nil {
log.Warnf("loaded %q, but it is empty", fileName)
}
return content, err
}
return "", nil
}
type changeloger interface {
Log(ctx *context.Context, prev, current string) (string, error)
}
type gitChangeloger struct{}
var validSHA1 = regexp.MustCompile(`^[a-fA-F0-9]{40}$`)
func (g gitChangeloger) Log(ctx *context.Context, prev, current string) (string, error) {
args := []string{"log", "--pretty=oneline", "--abbrev-commit", "--no-decorate", "--no-color"}
if validSHA1.MatchString(prev) {
args = append(args, prev, current)
} else {
args = append(args, fmt.Sprintf("tags/%s..tags/%s", prev, current))
}
return git.Run(ctx, args...)
}
type scmChangeloger struct {
client client.Client
repo client.Repo
}
func (c *scmChangeloger) Log(ctx *context.Context, prev, current string) (string, error) {
return c.client.Changelog(ctx, c.repo, prev, current)
}
type githubNativeChangeloger struct {
client client.GitHubClient
repo client.Repo
}
func (c *githubNativeChangeloger) Log(ctx *context.Context, prev, current string) (string, error) {
return c.client.GenerateReleaseNotes(ctx, c.repo, prev, current)
}