1
0
mirror of https://github.com/goreleaser/goreleaser.git synced 2025-03-19 20:57:53 +02:00

483 lines
11 KiB
Go
Raw Normal View History

// Package changelog provides the release changelog to goreleaser.
package changelog
import (
"cmp"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"github.com/caarlos0/log"
"github.com/goreleaser/goreleaser/v2/internal/client"
"github.com/goreleaser/goreleaser/v2/internal/git"
"github.com/goreleaser/goreleaser/v2/internal/tmpl"
"github.com/goreleaser/goreleaser/v2/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"
useGitea = "gitea"
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, error) {
if ctx.Snapshot {
return true, nil
}
return tmpl.New(ctx).Bool(ctx.Config.Changelog.Disable)
}
func (Pipe) Default(ctx *context.Context) error {
if ctx.Config.Changelog.Format == "" {
ctx.Config.Changelog.Format = "{{ .SHA }}: {{ .Message }} ({{ with .AuthorUsername }}@{{ . }}{{ else }}{{ .AuthorName }} <{{ .AuthorEmail }}>{{ end }})"
}
return nil
}
// 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
}
feat: add gitlab for releases (#1038) * outlines gitlab client integration * makes client parameter more explicit * adds gitlab url to config * changes releaseID to string to adapt to gitlab * updates to latest gitlab client lib 0.18 * fixes copy paster in gitlab upload func * fixes gitlab typo in config * adds gitlab token to env and context * release now uses the client factory method * skips brew pipe if it is not a github release * add github tokentype to publish tests * skips scoop pipe if it is not a github release * corrects brew skip msg * adds gitlab token to main test * adds gitlab to release docs * validates config and errors accordingly * adapt release pipe name to include gitlab * fixes gitlab client after testing * moves not-configured brew and scoop pipe checks as first check * adds more debug to gitlab client * adapts changelog generation for gitlab markdown * adds debug log for gitlab changelog * env needs to run before changelog pipe * moves gitlab default download url to default pipe * moves multiple releases check to from config to release pipe * release differs now for github and gitlab * adds debug gitlab release update msgs * moves env pipe as second after before because it determines the token type other pipes depend on * adaptes error check on gitlab release creation * Revert "adaptes error check on gitlab release creation" This reverts commit 032024571c76140f8e2207ee01cc08088f37594b. * simplifies gitlab client logic. removes comments * skips tls verification for gitlab client if specified in config * updates the docs * adds clarification that brew and scoop are not supported if it is a gitlab release * fixes copy paster in release.md * adds missing blob pipe in defaults and publish due to missing in merge * updates comment in gitlab client
2019-06-29 16:02:40 +02:00
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")
2024-06-22 22:43:57 -03:00
log.WithField("path", path).Debug("writing changelog")
return os.WriteFile(path, []byte(ctx.ReleaseNotes), 0o644) //nolint: gosec
}
type changelogGroup struct {
title string
entries []string
order int
}
func title(s string, level int) string {
if s == "" {
return ""
}
return fmt.Sprintf("%s %s", strings.Repeat("#", level), s)
}
func newLineFor(ctx *context.Context) string {
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")
return " \n"
}
return "\n"
}
func abbrevEntry(s string, abbr int) string {
switch abbr {
case 0:
return s
case -1:
_, rest, _ := strings.Cut(s, " ")
return rest
default:
commit, rest, _ := strings.Cut(s, " ")
if abbr > len(commit) {
return s
}
return fmt.Sprintf("%s %s", commit[:abbr], rest)
}
}
func abbrev(entries []string, abbr int) []string {
result := make([]string, 0, len(entries))
for _, entry := range entries {
result = append(result, abbrevEntry(entry, abbr))
}
return result
}
func formatChangelog(ctx *context.Context, entries []string) (string, error) {
if !useChangelog(ctx.Config.Changelog.Use).formatable() {
return strings.Join(entries, newLineFor(ctx)), nil
}
entries = abbrev(entries, ctx.Config.Changelog.Abbrev)
result := []string{title("Changelog", 2)}
if len(ctx.Config.Changelog.Groups) == 0 {
log.Debug("not grouping entries")
return strings.Join(append(result, filterAndPrefixItems(entries)...), newLineFor(ctx)), nil
}
log.Debug("grouping entries")
var groups []changelogGroup
for _, group := range ctx.Config.Changelog.Groups {
item := changelogGroup{
title: title(group.Title, 3),
order: group.Order,
}
if group.Regexp == "" {
// If no regexp is provided, we purge all strikethrough entries and add remaining entries to the list
item.entries = filterAndPrefixItems(entries)
// clear array
entries = nil
} else {
re, err := regexp.Compile(group.Regexp)
if err != nil {
return "", fmt.Errorf("failed to group into %q: %w", group.Title, err)
}
log.Debugf("group: %#v", group)
i := 0
for _, entry := range entries {
match := re.MatchString(entry)
log.Debugf("entry: %s match: %b\n", entry, match)
if match {
item.entries = append(item.entries, li+entry)
} else {
// Keep unmatched entry.
entries[i] = entry
i++
}
}
entries = entries[:i]
}
groups = append(groups, item)
if len(entries) == 0 {
break // No more entries to process.
}
}
slices.SortFunc(groups, groupSort)
for _, group := range groups {
if len(group.entries) > 0 {
result = append(result, group.title)
result = append(result, group.entries...)
}
}
return strings.Join(result, newLineFor(ctx)), nil
}
func groupSort(i, j changelogGroup) int {
return cmp.Compare(i.order, j.order)
}
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 {
2022-12-30 22:57:24 -03:00
case "", "asc", "desc":
return nil
2022-12-30 22:57:24 -03:00
default:
return ErrInvalidSortDirection
}
}
func buildChangelog(ctx *context.Context) ([]string, error) {
l, err := getChangeloger(ctx)
if err != nil {
return nil, err
}
log, err := l.Log(ctx)
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) {
filters := ctx.Config.Changelog.Filters
if len(filters.Include) > 0 {
var newEntries []string
for _, filter := range filters.Include {
r, err := regexp.Compile(filter)
if err != nil {
return entries, err
}
newEntries = append(newEntries, keep(r, entries)...)
}
return newEntries, nil
}
for _, filter := range 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
}
slices.SortFunc(entries, func(i, j string) int {
imsg := extractCommitInfo(i)
jmsg := extractCommitInfo(j)
compareRes := strings.Compare(imsg, jmsg)
if direction == "asc" {
return compareRes
}
return -compareRes
})
return entries
}
func keep(filter *regexp.Regexp, entries []string) (result []string) {
for _, entry := range entries {
if filter.MatchString(extractCommitInfo(entry)) {
result = append(result, entry)
}
}
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 getChangeloger(ctx *context.Context) (changeloger, error) {
switch ctx.Config.Changelog.Use {
2024-04-23 09:11:49 -03:00
case useGit, "":
return gitChangeloger{}, nil
case useGitLab, useGitea, useGitHub:
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.NewGitHubReleaseNotesGenerator(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
}
2021-11-06 16:58:07 -03:00
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) (string, error)
}
type gitChangeloger struct{}
func (g gitChangeloger) Log(ctx *context.Context) (string, error) {
args := []string{"log", "--pretty=oneline", "--no-decorate", "--no-color"}
prev, current := comparePair(ctx)
fix(changelog): fix random order of first commit in first release (#5173) ## Background This is a bug that occurs randomly under a very specific condition. Not sure how long this bug has been around. I first noticed it in the failed Dagger test job in https://github.com/goreleaser/goreleaser/pull/5161 after the `TestGroup` unit test was updated to use regex matching https://github.com/goreleaser/goreleaser/pull/5161#discussion_r1781302054. Log: https://github.com/goreleaser/goreleaser/actions/runs/11108665571/job/30862144417#step:4:680 ``` --- FAIL: TestGroup (0.23s) changelog_test.go:843: Error Trace: /src/internal/pipe/changelog/changelog_test.go:843 Error: Expect "## Changelog ### Features * a77c0b89a457ee6a78447f6c9113b79cf4dce8ce feat: added that thing ### Bug Fixes * 3e2908a87e5fdfdbd5efaad013c0b2d196c64c40 bug: Merge pull request #999 from goreleaser/some-branch ### Bots * e2b7fbaaf1387cd4af575f5e329d9441ce1a917b feat(deps): update foobar [bot] ### Others * 3643389d7150dc191eca4ac8428274fb31213a12 this is not a Merge pull request * 3e1421263cd99fbd9a1a6c0196a355efe96e631d chore: something about cArs we dont need * c094f150bc948d76f920219ef9729fd63747324b docs: whatever * 242178ede64b3ff570dfbde6416f2c4718dd5b68 fix: whatever * 02b7e77076dfed7475d42d728d69d13d19a10a39 ignored: whatever * c3b78e347e5c38acc6b78e5a963b28221ac0cfee fixed bug 2 * fc5f56a9d915d19bc3630dc40aabd99a3eede02b added feature 1 * dc67ddaae25db36fe70d3b96311243621c176169 first " to match "## Changelog ### Features \* \w+ feat: added that thing ### Bug Fixes \* \w+ bug: Merge pull request #999 from goreleaser\/some-branch ### Bots \* \w+ feat\(deps\): update foobar \[bot\] ### Others \* \w+ first \* \w+ this is not a Merge pull request \* \w+ chore: something about cArs we dont need \* \w+ docs: whatever \* \w+ fix: whatever \* \w+ ignored: whatever \* \w+ fixed bug 2 \* \w+ added feature 1 " Test: TestGroup ``` Then it also failed in: 1. 71e7a63ca111d184ac9ab3f68187b12c63b2c13e Log: https://github.com/goreleaser/goreleaser/actions/runs/11166871425/job/31041794426#step:4:667 ``` --- FAIL: TestGroup (0.13s) changelog_test.go:843: Error Trace: /src/internal/pipe/changelog/changelog_test.go:843 Error: Expect "## Changelog ### Features * 7a9c58e3f299b347754c02a149f77d4450768aba feat: added that thing ### Bug Fixes * 9d5982da0fa36817c9c907271ece0a238bc24918 bug: Merge pull request #999 from goreleaser/some-branch ### Bots * 6890859be3907f8f1b60b1a82cb4af277a0bc425 feat(deps): update foobar [bot] ### Others * 6acc3600c5fe17d0330b566e6d5703e48725f300 this is not a Merge pull request * 31abf613e4c3a5fcaebb0a1a23bcd418d61d2c4d first * 14a53e66c59c532a81e729b6717aa4137cc292fb chore: something about cArs we dont need * df77c2f0d8b1bbdc697e843e1dd2764a716a2aa5 docs: whatever * a4802f6fc858cbc12ceca360a89894a61a0a097f fix: whatever * 7a2645a1262516ca24443a65c137680e2e3857fc ignored: whatever * b66e319579a7eeb319d1d2a95cb938d6316d3edb fixed bug 2 * 377012fb77758238b46a20c8bbd348e55d011168 added feature 1 " to match "## Changelog ### Features \* \w+ feat: added that thing ### Bug Fixes \* \w+ bug: Merge pull request #999 from goreleaser\/some-branch ### Bots \* \w+ feat\(deps\): update foobar \[bot\] ### Others \* \w+ first \* \w+ this is not a Merge pull request \* \w+ chore: something about cArs we dont need \* \w+ docs: whatever \* \w+ fix: whatever \* \w+ ignored: whatever \* \w+ fixed bug 2 \* \w+ added feature 1 " Test: TestGroup ``` 2. 747c11d83301405c40df3a5b56adf976c8382b0f Log: https://github.com/goreleaser/goreleaser/actions/runs/11166873534/job/31041800714#step:4:677 ``` --- FAIL: TestGroup (0.09s) changelog_test.go:843: Error Trace: /src/internal/pipe/changelog/changelog_test.go:843 Error: Expect "## Changelog ### Features * 49f56e2d8ca352d4641828efd167dbfe91f5769a feat: added that thing ### Bug Fixes * 11c8dafa67d5973c359ed3bcf859b81d571396ed bug: Merge pull request #999 from goreleaser/some-branch ### Bots * df888fe601a92afe5d8d4fcae5a551b0eaa57684 feat(deps): update foobar [bot] ### Others * 03f397c28cd4f5484afee71f7edd99977f85deec this is not a Merge pull request * 16333c2d178e4911a049ba63b0b8783bbc7e497b chore: something about cArs we dont need * e7b30e58579bdaaeea184d78ddb5017a2bdc3459 docs: whatever * ab9abbc7aa88208f2b3dc44dc9f7b0e55771b826 fix: whatever * 87fc355911ca94f0a1e5a6c332e36b1f73654fbe ignored: whatever * 189fa3fb4ceb246084404247ad1b521747f30991 fixed bug 2 * 49fdca4fd96ec600d79722f3453c1b84e82dd6e5 added feature 1 * ea1e16eb97b432d9c111df934ea4b6ce3691438a first " to match "## Changelog ### Features \* \w+ feat: added that thing ### Bug Fixes \* \w+ bug: Merge pull request #999 from goreleaser\/some-branch ### Bots \* \w+ feat\(deps\): update foobar \[bot\] ### Others \* \w+ first \* \w+ this is not a Merge pull request \* \w+ chore: something about cArs we dont need \* \w+ docs: whatever \* \w+ fix: whatever \* \w+ ignored: whatever \* \w+ fixed bug 2 \* \w+ added feature 1 " Test: TestGroup ``` 3. 10980311a53bf90e3d5d469a9c3e916d67c0050d Log: https://github.com/goreleaser/goreleaser/actions/runs/11183904433/job/31093519567#step:14:41 ``` --- FAIL: TestGroup (0.14s) changelog_test.go:843: Error Trace: /home/runner/work/goreleaser/goreleaser/internal/pipe/changelog/changelog_test.go:843 Error: Expect "## Changelog ### Features * ec216fc3537667e300da4181c6b51520367afd28 feat: added that thing ### Bug Fixes * 5132e678d5f69a366415474cefce012c640a7de9 bug: Merge pull request #999 from goreleaser/some-branch ### Bots * dd9571e27c5a4f19882b8062a790636376b677bc feat(deps): update foobar [bot] ### Others * c9b95e3b52ad6a82bacabae63decd45b1038d137 this is not a Merge pull request * 260f70d5c2b6e31a35058b727818a78a7d589a22 chore: something about cArs we dont need * 0969cba5b1363473e05eb251ffefbccd46fa6fc8 first * c504cb0173a1f312ab39d17852f86b95504ff767 docs: whatever * d57cab9360470d0e0a03d1ecb4763e89fe182f8f fix: whatever * 2e659ceef3f2231ed107c80954833d9073091dd3 ignored: whatever * 72658b11fd2789a03e83496d723a9196f7b14467 fixed bug 2 * 883d4fab813e6849520463b5325077a9ef45131d added feature 1 " to match "## Changelog ### Features \* \w+ feat: added that thing ### Bug Fixes \* \w+ bug: Merge pull request #999 from goreleaser\/some-branch ### Bots \* \w+ feat\(deps\): update foobar \[bot\] ### Others \* \w+ first \* \w+ this is not a Merge pull request \* \w+ chore: something about cArs we dont need \* \w+ docs: whatever \* \w+ fix: whatever \* \w+ ignored: whatever \* \w+ fixed bug 2 \* \w+ added feature 1 " Test: TestGroup ``` As we can see from the log, the first commit with the `first` message can appear in a random order in the changelog. --- ## Solution In the `TestGroup` unit test, we are making 11 git commits, all within a second. There seems to be a bug with `git log` where it is unable to order the commits in reverse chronological order if all commits have the same authored and committed date, as shown below. > [!note] > `/tmp/TestGroup4125952855/001` is the temporary directory created by `testlib.Mktmp` in `TestGroup` test. `git log` without revision range: ``` /tmp/TestGroup4125952855/001 main ❯ git log --oneline 85f005f (HEAD -> main, tag: v0.0.2) this is not a Merge pull request 27dbd0e bug: Merge pull request #999 from goreleaser/some-branch 3495034 feat: added that thing 9f0db77 chore: something about cArs we dont need 634e043 docs: whatever ef52fef fix: whatever ff49bea feat(deps): update foobar [bot] e0f4e4b ignored: whatever ce7fbfa fixed bug 2 940a684 added feature 1 2750980 (tag: v0.0.1) first ``` `git log` with multiple revision ranges, the "first" commit appears at the top: ``` /tmp/TestGroup4125952855/001 main ❯ git log --oneline 2750980 v0.0.2 2750980 (tag: v0.0.1) first 85f005f (HEAD -> main, tag: v0.0.2) this is not a Merge pull request 27dbd0e bug: Merge pull request #999 from goreleaser/some-branch 3495034 feat: added that thing 9f0db77 chore: something about cArs we dont need 634e043 docs: whatever ef52fef fix: whatever ff49bea feat(deps): update foobar [bot] e0f4e4b ignored: whatever ce7fbfa fixed bug 2 940a684 added feature 1 ``` If we specify only one revision, then the commits are ordered correctly in reverse chronological order: ``` /tmp/TestGroup4125952855/001 main ❯ git log --oneline v0.0.2 85f005f (HEAD -> main, tag: v0.0.2) this is not a Merge pull request 27dbd0e bug: Merge pull request #999 from goreleaser/some-branch 3495034 feat: added that thing 9f0db77 chore: something about cArs we dont need 634e043 docs: whatever ef52fef fix: whatever ff49bea feat(deps): update foobar [bot] e0f4e4b ignored: whatever ce7fbfa fixed bug 2 940a684 added feature 1 2750980 (tag: v0.0.1) first ``` Based on my observations, this bug can only happen when all commits are created at the same time, and the user is creating their first release note. This commit fixes the bug by excluding the first commit SHA-1 hash from `git log` in `gitChangeLogger`. Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
2024-10-08 08:45:32 +08:00
if prev == "" {
// log all commits since the first commit
args = append(args, current)
} else {
args = append(args, fmt.Sprintf("tags/%s..tags/%s", ctx.Git.PreviousTag, ctx.Git.CurrentTag))
}
return git.Run(ctx, args...)
}
type scmChangeloger struct {
client client.Client
repo client.Repo
}
func (c *scmChangeloger) Log(ctx *context.Context) (string, error) {
prev, current := comparePair(ctx)
items, err := c.client.Changelog(ctx, c.repo, prev, current)
if err != nil {
return "", err
}
var lines []string
for _, item := range items {
line, err := tmpl.New(ctx).WithExtraFields(tmpl.Fields{
"SHA": item.SHA,
"Message": item.Message,
"AuthorUsername": item.AuthorUsername,
"AuthorName": item.AuthorName,
"AuthorEmail": item.AuthorEmail,
}).Apply(ctx.Config.Changelog.Format)
if err != nil {
return "", err
}
lines = append(lines, line)
}
return strings.Join(lines, "\n"), nil
}
type githubNativeChangeloger struct {
client client.ReleaseNotesGenerator
repo client.Repo
}
func (c *githubNativeChangeloger) Log(ctx *context.Context) (string, error) {
return c.client.GenerateReleaseNotes(ctx, c.repo, ctx.Git.PreviousTag, ctx.Git.CurrentTag)
}
func comparePair(ctx *context.Context) (prev string, current string) {
prev = ctx.Git.PreviousTag
current = ctx.Git.CurrentTag
return
}