diff --git a/.claude/skills/release-notes/SKILL.md b/.claude/skills/release-notes/SKILL.md new file mode 100644 index 0000000..1d9cd0d --- /dev/null +++ b/.claude/skills/release-notes/SKILL.md @@ -0,0 +1,135 @@ +--- +name: release-notes +description: Write the release note entries of a pull request, preview the notes of the next release, pick the next version and tag it. Use when opening or editing a pull request that has a feat, fix or breaking commit, when the release notes preview warns about a blockquote count, when asked what the next version is, when asked to release or tag main, or when a published release note is wrong. +--- + +# Release notes & versioning + +The repository has no changelog file. When a `vX.Y.Z` tag is pushed, `tools/releaser` builds the +GitHub release notes from the commits on `main` since the previous tag, and goreleaser publishes +them. `main` is always ready to tag, so every pull request carries its own entries. + +## Which commits get an entry + +Pull requests are rebase-merged, so each commit of a pull request lands on `main` with its own +title. A commit gets one entry when its title has: + +| Title | Section of the notes | +|---|---| +| a `!` before the colon, with any type, such as `feat!:` or `refactor(client)!:` | Breaking changes | +| `feat:` | Features | +| `fix:` | Fixes | + +A scope is allowed and has no effect: `fix(client): ...` is a fix. Every other commit, such as +`docs:`, `test:`, `ci:`, `chore:`, `build:` or `refactor:`, gets no entry. Choose the type by what a +user of the CLI, or a caller of `client/` such as the Terraform provider, notices: a change that +nobody notices is no `feat` and no `fix`. + +## Write the entries in the pull request description + +Start the pull request description with one blockquote per entry commit, in the order of the +commits. A blank line separates two blockquotes. The first line of normal text ends the entries. + + +A pull request with the commits `fix: keep the profile when a login is aborted`, +`test: cover the aborted login` and `feat(client): list building block runners` has two entry +commits, so its description starts with two blockquotes: + +```markdown +> `meshstack login`: an aborted browser login keeps the stored profile, so the previous login +> still works. + +> Go client: `Client.BuildingBlockRunner` lists the building block runners. + +## Summary + +The rest of the description is free text. +``` + + +- **The count must match.** The releaser uses the blockquotes of a pull request only when their + number equals the number of its entry commits. With any other number it uses none of them and + prints a warning. +- **Only the leading blockquotes count.** Put every other blockquote, such as a quoted error + message, below the first line of normal text. A blockquote above that line is taken as an entry. +- **A pull request written by an AI agent keeps `> 🤖 _Written by AI agent_` as its first line.** The + entries follow it as the next blockquotes, separated from it by a blank line. The releaser skips + every leading blockquote that starts with 🤖: it is no entry and does not count. +- An entry can have several lines and several paragraphs. Keep paragraphs in one blockquote with a + `>` line between them. +- Wrap the lines of an entry freely, in the pull request description and in a commit body. The + releaser joins the lines of a paragraph, because GitHub shows every newline of a release body as + a line break. Code blocks and lists stay as written. + +### Wording of an entry + +- Name what is affected first: the command in backticks, such as `` `meshstack login`: ``, or + `Go client:` for a change of `client/`. +- Describe what the user notices. For a fix, name the symptom that goes away. For a breaking change, + say what the user or the caller of `client/` must change. +- Write complete sentences in present tense. Leave out the internal diff. +- The first line of the notes, `Requires meshStack X or later.`, is written by the releaser from + `client.MinMeshStackVersion`, below which the CLI refuses a meshStack. When one feature needs a + newer meshStack than that, say so as plain text in its entry. + +## Where the releaser takes the text from + +For each entry commit the releaser takes the first text that exists: + +1. The matching leading blockquote of the pull request description. +2. The leading blockquotes of the commit message body. +3. The commit title without its `type(scope)!: ` prefix. + +The pull request description wins over the commit body. GitHub is read when the tag is pushed, so +the description of a merged pull request can still be edited until then. Each entry ends with its +pull request number and the GitHub handle of the commit author, such as `(#421 by @octocat)`. The +releaser takes the handle from the commit, so a commit by another person than the one who opened +the pull request names its own author. A commit that was pushed without a pull request shows its +short commit id. + +An entry also names the issues that GitHub linked to its pull request as closed, such as +`(#423 by @octocat, closes #389)`. Link an issue with a closing keyword, such as `Fixes #389`. The +preferred place is the body of the commit that fixes the issue, because this ties the issue to the +entry of that commit. A keyword in the pull request description also links the issue. Such an issue +is shown when the pull request has one entry commit, or when exactly one of its entry commits has no +issue of its own. + +## Preview the notes + +```bash +GOWORK=off go run ./tools/releaser "$(git describe --tags --abbrev=0 HEAD^)..HEAD" +``` + +The notes go to stdout. The warnings and the next version go to stderr. The releaser needs a token +in `GITHUB_TOKEN` or `GH_TOKEN` to read the pull requests, the authors and the issues from GitHub; +`export GH_TOKEN=$(gh auth token)` sets one. Without a token it warns, and every entry uses the +commit text. The `Release Notes Preview` workflow runs the same command on every push to `main` and +shows the notes in its run summary. + +Fix a warning about a blockquote count by editing the pull request description, then run the +preview again. The releaser reads merged pull requests only, so the commits of an open pull request +use the commit text. + +## Pick the version + +The CLI never raises the major version. Since the last tag: + +- a `feat` commit, or any commit with `!`, raises the minor version and sets the patch version to 0 + (`v0.11.2` → `v0.12.0`); +- else the patch version goes up (`v0.11.2` → `v0.11.3`). + +The preview prints the version and its reason, such as +`Next version: v0.11.3 (no feature and no breaking change since v0.11.2)`. + +## Tag and release + +1. Run the preview on an up-to-date `main` and read the notes. +2. Tag and push: + + ```bash + git tag vX.Y.Z && git push origin vX.Y.Z + ``` + +The `Release` workflow writes the notes and publishes the release. A wrong commit title on `main` +stays as it is, because the history of `main` is not rewritten. When it put an entry into the wrong +section or left one out, correct the notes by hand on the published release page. diff --git a/.github/workflows/release-notes.yml b/.github/workflows/release-notes.yml new file mode 100644 index 0000000..dfba2ef --- /dev/null +++ b/.github/workflows/release-notes.yml @@ -0,0 +1,41 @@ +name: Release Notes Preview + +on: + push: + branches: + - main + +permissions: {} + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +defaults: + run: + shell: nix develop -c bash -eo pipefail {0} # zizmor: ignore[misfeature] every step takes its tools from the dev shell + +jobs: + preview: + name: Release Notes Preview + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read # The release notes take their entries from the pull request descriptions. + issues: read # The release notes name the issues that a pull request closed. + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + - uses: cachix/install-nix-action@3dc140bfc76c49fbd4dd958429132e3746bcb086 # v31.11.5 + - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: | + ~/go/pkg/mod + ~/.cache/go-build + key: go-${{ runner.os }}-${{ github.job }}-${{ hashFiles('go.sum') }} + - name: Preview the release notes + run: go run ./tools/releaser "$(git describe --tags --abbrev=0 HEAD^)..HEAD" >> "$GITHUB_STEP_SUMMARY" + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3bcd204..760e790 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -17,15 +17,21 @@ jobs: runs-on: ubuntu-latest permissions: contents: write # goreleaser creates the release and uploads the archives + pull-requests: read # The release notes take their entries from the pull request descriptions. + issues: read # The release notes name the issues that a pull request closed. steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - # Let goreleaser read older tags, which it needs for the changelog. + # goreleaser and the release notes need the older tags. fetch-depth: 0 persist-credentials: false - uses: cachix/install-nix-action@3dc140bfc76c49fbd4dd958429132e3746bcb086 # v31.11.5 + - name: Write the release notes + run: nix develop -c go run ./tools/releaser "$(git describe --tags --abbrev=0 HEAD^)..HEAD" > "$RUNNER_TEMP/release-notes.md" + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Run GoReleaser - run: nix develop -c goreleaser release --clean + run: nix develop -c goreleaser release --clean --release-notes "$RUNNER_TEMP/release-notes.md" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # The winget section of .goreleaser.yml says how to set up this secret. diff --git a/.golangci.yml b/.golangci.yml index 2916994..1d534e3 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -124,6 +124,12 @@ linters: - path: docs/demo/ linters: - gosec + # The releaser is a front end of its own: it names itself to GitHub, and its stdout is the + # release notes. + - path: tools/releaser/ + linters: + - forbidigo + text: (user agent of the front end|stdout is a command's output) settings: # The process has one HTTP client, built in client/http. diff --git a/.goreleaser.yml b/.goreleaser.yml index ff535da..9eae957 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -48,24 +48,6 @@ checksum: name_template: '{{ .ProjectName }}_{{ .Version }}_SHA256SUMS' algorithm: sha256 -changelog: - use: github - sort: asc - groups: - # The Terraform provider imports client/, and while the CLI is at 0.x a breaking change takes no - # `!`. This group is where the provider's maintainers find what they have to adapt to. - - title: Client API - regexp: '^(feat|fix|refactor|perf)\(client\)!?:' - order: 0 - - title: Features - regexp: '^feat(\(.+\))?!?:' - order: 1 - - title: Fixes - regexp: '^fix(\(.+\))?!?:' - order: 2 - - title: Others - order: 99 - # Opens a pull request to microsoft/winget-pkgs. The pull request comes from the fork # jannymeshi/winget-pkgs, because goreleaser has to push the manifest branch somewhere, and a bot # account keeps that fork out of the meshcloud organization. One-time setup: diff --git a/AGENTS.md b/AGENTS.md index ac9f986..6524f97 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,12 +74,15 @@ the docs. parameters, which a Go method cannot have. Inline a helper of a few lines that has one caller. A string or map that several functions pass around gets a named type with methods, as `internal.KindCommand` is. -- **Conventional Commits** for messages (`feat:`, `fix:`, `docs:`, `chore:`). While the CLI is at - 0.x, a breaking change, of `client/` included, takes no `!`: every minor release may break. - goreleaser writes the release notes from these subjects, as `changelog:` in `.goreleaser.yml` - sets out, so the subject is what a user reads there. Give every change of `client/` the `client` - scope, as in `refactor(client): …`: it puts the change in the group the Terraform provider's - maintainers read before they bump the module. +- **Conventional Commits** for messages (`feat:`, `fix:`, `docs:`, `chore:`, `feat!:` for + breaking). A breaking change of `client/` takes the `!` too, because the Terraform provider's + maintainers read the breaking changes before they bump the module. Give every change of `client/` + the `client` scope, as in `refactor(client): …`. Pull requests are rebase-merged, so every commit + title lands on `main` and decides whether the commit gets a release note entry. +- **Release note entries live in the pull request description.** Every `feat` commit, every `fix` + commit and every commit with `!` gets one leading blockquote in the description of its pull + request. `tools/releaser` builds the release notes from these when a tag is pushed, and `main` is + always ready to tag. Load the **`release-notes`** skill to write them or to pick the version. - **Stress-test a plan before writing code.** For any non-trivial change, walk each branch of the decision tree and settle every open question with a recommended answer first. (*meshcloud-internal*: the `grill-me` skill of `../meshfed-release`.) @@ -129,10 +132,10 @@ go test ./cmd/internal/testacc/... -run TestAcc ## Releasing -Pushing a `vN.N.N` tag runs `.github/workflows/release.yml`: goreleaser publishes the archives and -checksums, and the image goes to GHCR only, as `ghcr.io/meshcloud/meshstack-cli`. Every other -channel the release publishes to is a job of that workflow or a publish section of `.goreleaser.yml`, -and its one-time setup is described there. +Pushing a `vN.N.N` tag runs `.github/workflows/release.yml`: `tools/releaser` writes the release +notes, goreleaser publishes them with the archives and checksums, and the image goes to GHCR only, +as `ghcr.io/meshcloud/meshstack-cli`. Every other channel the release publishes to is a job of that +workflow or a publish section of `.goreleaser.yml`, and its one-time setup is described there. The version reaches the binary through an ldflag on diff --git a/infra/github/main.tf b/infra/github/main.tf index acd22a5..f13fdc4 100644 --- a/infra/github/main.tf +++ b/infra/github/main.tf @@ -49,6 +49,12 @@ resource "github_repository_ruleset" "protect_default_branch" { } rules { + commit_message_pattern { + name = "Conventional Commits title" + operator = "regex" + pattern = "^(feat|fix|docs|test|ci|chore|refactor|build|perf|revert)(\\([^)]+\\))?!?: .+" + } + pull_request { required_approving_review_count = 1 required_review_thread_resolution = true diff --git a/tools/releaser/git.go b/tools/releaser/git.go new file mode 100644 index 0000000..61854ea --- /dev/null +++ b/tools/releaser/git.go @@ -0,0 +1,59 @@ +package main + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "regexp" + "strings" +) + +type commit struct { + SHA string + Subject string + Body string +} + +func git(args ...string) (string, error) { + out, err := exec.CommandContext(context.Background(), "git", args...).Output() //nolint:gosec // git takes the arguments that this tool builds, each as its own argument. + if exitErr, ok := errors.AsType[*exec.ExitError](err); ok { + err = errors.New(strings.TrimSpace(string(exitErr.Stderr))) + } + if err != nil { + return "", fmt.Errorf("git %s: %w", strings.Join(args, " "), err) + } + return strings.TrimSpace(string(out)), nil +} + +func listCommits(revisionRange string) ([]commit, error) { + out, err := git("log", "--reverse", "--format=%H%x1f%s%x1f%b%x1e", "--end-of-options", revisionRange) + if err != nil { + return nil, err + } + var commits []commit + for record := range strings.SplitSeq(out, "\x1e") { + if fields := strings.SplitN(strings.TrimSpace(record), "\x1f", 3); len(fields) == 3 { + commits = append(commits, commit{SHA: fields[0], Subject: fields[1], Body: fields[2]}) + } + } + return commits, nil +} + +var gitHubRemotePattern = regexp.MustCompile(`github\.com[:/]+([^/]+/[^/]+?)(\.git)?/?$`) + +func gitHubRepository() (string, error) { + if repository := os.Getenv("GITHUB_REPOSITORY"); repository != "" { + return repository, nil + } + remote, err := git("remote", "get-url", "origin") + if err != nil { + return "", err + } + match := gitHubRemotePattern.FindStringSubmatch(remote) + if match == nil { + return "", fmt.Errorf("remote %q is no GitHub repository", remote) + } + return match[1], nil +} diff --git a/tools/releaser/github.go b/tools/releaser/github.go new file mode 100644 index 0000000..fcce499 --- /dev/null +++ b/tools/releaser/github.go @@ -0,0 +1,123 @@ +package main + +import ( + "cmp" + "context" + "encoding/json/jsontext" + "errors" + "fmt" + "net/url" + "os" + "strings" + + clienthttp "github.com/meshcloud/meshstack-cli/client/http" + "github.com/meshcloud/meshstack-cli/internal/json" +) + +const commitFields = `... on Commit { + author { user { login } } + associatedPullRequests(first: 5) { nodes { number merged body + closingIssuesReferences(first: 20) { nodes { number + timelineItems(last: 1, itemTypes: [CLOSED_EVENT]) { nodes { ... on ClosedEvent { + closer { ... on Commit { oid } } + } } } + } } + } } +}` + +type commitNode struct { + Author struct { + User struct { + Login string `json:"login"` + } `json:"user"` + } `json:"author"` + AssociatedPullRequests struct { + Nodes []*pullRequest `json:"nodes"` + } `json:"associatedPullRequests"` +} + +type pullRequest struct { + Number int `json:"number"` + Merged bool `json:"merged"` + Body string `json:"body"` + ClosingIssuesReferences struct { + Nodes []issue `json:"nodes"` + } `json:"closingIssuesReferences"` +} + +type issue struct { + Number int `json:"number"` + TimelineItems struct { + Nodes []struct { + Closer struct { + OID string `json:"oid"` + } `json:"closer"` + } `json:"nodes"` + } `json:"timelineItems"` +} + +func (n commitNode) mergedPullRequest() *pullRequest { + for _, pr := range n.AssociatedPullRequests.Nodes { + if pr.Merged { + return pr + } + } + return nil +} + +func (i issue) closerCommit() string { + if events := i.TimelineItems.Nodes; len(events) > 0 { + return events[0].Closer.OID + } + return "" +} + +func lookupCommits(shas []string) (map[string]commitNode, error) { + repository, err := gitHubRepository() + if err != nil { + return nil, fmt.Errorf("cannot find the GitHub repository: %w", err) + } + token := cmp.Or(os.Getenv("GITHUB_TOKEN"), os.Getenv("GH_TOKEN")) + if token == "" { + return nil, errors.New("neither GITHUB_TOKEN nor GH_TOKEN is set, set one, for example with `export GH_TOKEN=$(gh auth token)`") + } + owner, name, _ := strings.Cut(repository, "/") + var query strings.Builder + fmt.Fprintf(&query, "{ repository(owner: %q, name: %q) {\n", owner, name) + for _, sha := range shas { + fmt.Fprintf(&query, "c%s: object(oid: %q) { %s }\n", sha, sha, commitFields) + } + query.WriteString("} }") + + type answer struct { + Data struct { + Repository map[string]commitNode `json:"repository"` + } `json:"data"` + Errors jsontext.Value `json:"errors"` + } + got, err := clienthttp.UnmarshalJsonBody[answer]( + clienthttp.NewClient(clienthttp.UserAgent{GitHubRepo: "tools/releaser", Version: "v0"}). + WithAuthorization(clienthttp.BearerToken(token)). + DoRequest(context.Background(), clienthttp.MethodPost, &url.URL{Scheme: "https", Host: "api.github.com", Path: "/graphql"}, + clienthttp.WithJsonRequest(map[string]string{"query": query.String()}, ""), + clienthttp.Retryable(clienthttp.RetryOnTransient), + )) + if httpErr, ok := errors.AsType[clienthttp.Error](err); ok { + var body struct { + Message string `json:"message"` + } + _ = json.Unmarshal(httpErr.ResponseBody, &body) + return nil, fmt.Errorf("GitHub answered HTTP %d: %s", httpErr.StatusCode, body.Message) + } + if err != nil { + return nil, err + } + if got.Data.Repository == nil { + return nil, fmt.Errorf("GitHub answered without data: %s", got.Errors) + } + nodes := make(map[string]commitNode, len(shas)) + for alias, node := range got.Data.Repository { + nodes[strings.TrimPrefix(alias, "c")] = node + } + return nodes, nil +} diff --git a/tools/releaser/main.go b/tools/releaser/main.go new file mode 100644 index 0000000..f127227 --- /dev/null +++ b/tools/releaser/main.go @@ -0,0 +1,50 @@ +package main + +import ( + "fmt" + "os" + "strings" + + "github.com/meshcloud/meshstack-cli/client" +) + +func main() { + if len(os.Args) != 2 { + fmt.Fprintln(os.Stderr, `Usage: go run ./tools/releaser "$(git describe --tags --abbrev=0 HEAD^)..HEAD"`) + os.Exit(2) + } + if err := run(os.Args[1]); err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + os.Exit(1) + } +} + +func run(revisionRange string) error { + commits, err := listCommits(revisionRange) + if err != nil { + return err + } + notes := render(client.MinMeshStackVersion.String(), collectEntries(commits)) + if _, err := os.Stdout.WriteString(notes); err != nil { + return err + } + previousTag, _, _ := strings.Cut(revisionRange, "..") + if hint := nextVersionHint(previousTag, commits); hint != "" { + annotate("notice", hint) + } + return nil +} + +func warnf(format string, args ...any) { + annotate("warning", fmt.Sprintf(format, args...)) +} + +func annotate(level, message string) { + switch { + case os.Getenv("GITHUB_ACTIONS") == "true": + message = "::" + level + "::" + strings.NewReplacer("%", "%25", "\r", "%0D", "\n", "%0A").Replace(message) + case level == "warning": + message = "Warning: " + message + } + fmt.Fprintln(os.Stderr, message) +} diff --git a/tools/releaser/notes.go b/tools/releaser/notes.go new file mode 100644 index 0000000..3f50ec3 --- /dev/null +++ b/tools/releaser/notes.go @@ -0,0 +1,256 @@ +package main + +import ( + "fmt" + "maps" + "regexp" + "slices" + "strconv" + "strings" +) + +const ( + sectionBreaking = "Breaking changes" + sectionFeatures = "Features" + sectionFixes = "Fixes" +) + +type entry struct { + Commit commit + Section string + Text string + Reference string + Author string + Issues []int +} + +var titlePattern = regexp.MustCompile(`^([A-Za-z]+)(\([^)]+\))?(!)?: (.+)$`) + +func parseTitle(subject string) (section, description string) { + match := titlePattern.FindStringSubmatch(subject) + switch { + case match == nil: + return "", "" + case match[3] == "!": + return sectionBreaking, match[4] + case match[1] == "feat": + return sectionFeatures, match[4] + case match[1] == "fix": + return sectionFixes, match[4] + } + return "", "" +} + +const aiAuthorshipMarkerPrefix = "🤖" + +func leadingQuotes(text string) []string { + var blocks []string + var current []string + flush := func() { + if block := strings.TrimSpace(strings.Join(current, "\n")); block != "" && !strings.HasPrefix(block, aiAuthorshipMarkerPrefix) { + blocks = append(blocks, block) + } + current = nil + } + for line := range strings.Lines(strings.ReplaceAll(text, "\r\n", "\n")) { + line = strings.TrimSpace(line) + quoted, isQuote := strings.CutPrefix(line, ">") + switch { + case isQuote: + current = append(current, strings.TrimPrefix(quoted, " ")) + case line == "": + flush() + default: + flush() + return blocks + } + } + flush() + return blocks +} + +func collectEntries(commits []commit) []entry { + var entries []entry + var shas []string + for _, c := range commits { + if section, description := parseTitle(c.Subject); section != "" { + entries = append(entries, entry{Commit: c, Section: section, Text: description, Reference: c.SHA[:7]}) + shas = append(shas, c.SHA) + } + } + if len(entries) == 0 { + return nil + } + + nodes, err := lookupCommits(shas) + if err != nil { + warnf("Cannot read the pull requests from GitHub: %v. Every entry uses the commit text and names no author.", err) + } + pulls := map[int]*pullRequest{} + entryCommits := map[int][]string{} + for _, sha := range shas { + if pr := nodes[sha].mergedPullRequest(); pr != nil { + if _, seen := pulls[pr.Number]; !seen { + pulls[pr.Number] = pr + } + entryCommits[pr.Number] = append(entryCommits[pr.Number], sha) + } + } + blocks := map[int][]string{} + issues := map[string][]int{} + for _, number := range slices.Sorted(maps.Keys(pulls)) { + maps.Copy(issues, assignIssues(pulls[number].ClosingIssuesReferences.Nodes, entryCommits[number])) + quotes, want := leadingQuotes(pulls[number].Body), len(entryCommits[number]) + if len(quotes) != want { + warnf("The description of #%d starts with %d blockquote(s), and the pull request has %d feat, fix or breaking commit(s) in this range. Its entries use the commit text.", number, len(quotes), want) + continue + } + blocks[number] = quotes + } + + for i := range entries { + e := &entries[i] + node := nodes[e.Commit.SHA] + e.Author, e.Issues = node.Author.User.Login, issues[e.Commit.SHA] + text := strings.Join(leadingQuotes(e.Commit.Body), "\n\n") + if pr := node.mergedPullRequest(); pr != nil { + e.Reference = "#" + strconv.Itoa(pr.Number) + if remaining := blocks[pr.Number]; len(remaining) > 0 { + text, blocks[pr.Number] = remaining[0], remaining[1:] + } + } + if text != "" { + e.Text = text + } + } + return entries +} + +func assignIssues(closed []issue, entryCommits []string) map[string][]int { + assigned := map[string][]int{} + var leftOver []int + for _, closing := range closed { + if closer := closing.closerCommit(); slices.Contains(entryCommits, closer) { + assigned[closer] = append(assigned[closer], closing.Number) + } else { + leftOver = append(leftOver, closing.Number) + } + } + var withoutIssue []string + for _, sha := range entryCommits { + if len(assigned[sha]) == 0 { + withoutIssue = append(withoutIssue, sha) + } + } + switch { + case len(leftOver) == 0: + case len(entryCommits) == 1: + assigned[entryCommits[0]] = append(assigned[entryCommits[0]], leftOver...) + case len(withoutIssue) == 1: + assigned[withoutIssue[0]] = leftOver + } + for _, numbers := range assigned { + slices.Sort(numbers) + } + return assigned +} + +func render(minMeshStackVersion string, entries []entry) string { + var out strings.Builder + fmt.Fprintf(&out, "Requires meshStack %s or later.\n", minMeshStackVersion) + for _, section := range []string{sectionBreaking, sectionFeatures, sectionFixes} { + heading := "\n## " + section + "\n" + for _, e := range entries { + if e.Section == section { + out.WriteString(heading + renderItem(e)) + heading = "" + } + } + } + return out.String() +} + +const trailingWhitespace = " \t\r" + +var ( + blockStartPattern = regexp.MustCompile("^\\s*([-*+] |\\d+[.)] |#{1,6} |```|~~~|\\||>|<)") + fencePattern = regexp.MustCompile("^\\s*(```|~~~)") + standalonePattern = regexp.MustCompile(`^\s*(#{1,6} |\|)`) +) + +func unwrap(text string) string { + var out []string + inFence, joinable := false, false + for line := range strings.SplitSeq(text, "\n") { + switch { + case fencePattern.MatchString(line): + inFence = !inFence + out = append(out, line) + joinable = false + case inFence: + out = append(out, line) + case strings.TrimSpace(line) == "": + out = append(out, "") + joinable = false + case blockStartPattern.MatchString(line) || !joinable: + out = append(out, strings.TrimRight(line, trailingWhitespace)) + joinable = !standalonePattern.MatchString(line) + default: + out[len(out)-1] += " " + strings.TrimSpace(line) + } + } + return strings.Join(out, "\n") +} + +func (e entry) suffix() string { + var out strings.Builder + out.WriteString("(" + e.Reference) + if e.Author != "" { + out.WriteString(" by @" + e.Author) + } + separator := ", closes" + for _, issue := range e.Issues { + fmt.Fprintf(&out, "%s #%d", separator, issue) + separator = "," + } + out.WriteString(")") + return out.String() +} + +func renderItem(e entry) string { + lines := strings.Split(unwrap(strings.TrimSpace(e.Text)), "\n") + if len(lines) == 1 { + lines[0] = strings.TrimRight(lines[0], trailingWhitespace) + " " + e.suffix() + } else { + lines = append(lines, "", e.suffix()) + } + var out strings.Builder + for i, line := range lines { + line = strings.TrimRight(line, trailingWhitespace) + switch { + case i == 0: + out.WriteString("- " + line) + case line != "": + out.WriteString(" " + line) + } + out.WriteString("\n") + } + return out.String() +} + +var versionTagPattern = regexp.MustCompile(`^(v\d+)\.(\d+)\.(\d+)$`) + +func nextVersionHint(previousTag string, commits []commit) string { + match := versionTagPattern.FindStringSubmatch(previousTag) + if match == nil { + return "" + } + minor, _ := strconv.Atoi(match[2]) + patch, _ := strconv.Atoi(match[3]) + for _, c := range commits { + if section, _ := parseTitle(c.Subject); section == sectionBreaking || section == sectionFeatures { + return fmt.Sprintf("Next version: %s.%d.0 (feature or breaking change since %s: %s %s)", match[1], minor+1, previousTag, c.SHA[:7], c.Subject) + } + } + return fmt.Sprintf("Next version: %s.%d.%d (no feature and no breaking change since %s)", match[1], minor, patch+1, previousTag) +}