diff --git a/.github/workflows/release-pr.yml b/.github/workflows/release-pr.yml new file mode 100644 index 0000000..b96e062 --- /dev/null +++ b/.github/workflows/release-pr.yml @@ -0,0 +1,125 @@ +# Keeps one pull request, from release/plugins, that releases every plugin whose image changed since its last release +# (tools/release), and tags the versions it leaves on main once merged. Each run, for a push to main: +# +# 1. tags each version at the top of a plugin's CHANGELOG.md that has no tag yet, on the commit of the push: the merge +# of the release pull request. Each tag starts the release workflow, which publishes that plugin's image. +# 2. writes the next version of each plugin with a change since its last tag to its CHANGELOG.md, and force-pushes +# that, on the commit of the push, to release/plugins; then opens the pull request, or updates it. With nothing to +# release, it closes the pull request. +# +# It acts as the release App, whose key is in the environment `release`, which only main may use. A tag created or a +# branch pushed with GITHUB_TOKEN starts no workflow: the tags would publish nothing, and CI would not run on the pull +# request. The App may also create the tags plugins/*/v*, which the repository's tag ruleset forbids to others. +name: Release pull request + +on: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: release-pr + cancel-in-progress: false + +env: + # Use exactly the Go version of .tool-versions; never download another toolchain. + GOTOOLCHAIN: local + GOWORK: "off" + BRANCH: release/plugins + +defaults: + run: + # Named, so that a step runs with -o pipefail. + shell: bash + +jobs: + release-pr: + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + environment: release + steps: + - name: A token of the release App + id: app + uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 + with: + app-id: ${{ vars.RELEASE_APP_ID }} + private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} + permission-contents: write + permission-pull-requests: write + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + # The whole history with the tags: the last release of a plugin is its highest tag. + fetch-depth: 0 + fetch-tags: true + persist-credentials: false + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version-file: .tool-versions + cache-dependency-path: | + go.sum + tools/go.sum + plugins/*/go.sum + - name: Tag the versions of the changelogs + env: + GH_TOKEN: ${{ steps.app.outputs.token }} + REPOSITORY: ${{ github.repository }} + run: | + tags="$(go run -C tools ./cmd/release tags -root ..)" + for tag in $tags; do + gh api "repos/$REPOSITORY/git/refs" -f "ref=refs/tags/$tag" -f "sha=$GITHUB_SHA" > /dev/null + # And here, so that the next step counts it as released. + git tag "$tag" "$GITHUB_SHA" + echo "Tagged \`$tag\` on $GITHUB_SHA." >> "$GITHUB_STEP_SUMMARY" + done + - name: Write the next versions to the changelogs + id: prepare + env: + REPO_URL: ${{ github.server_url }}/${{ github.repository }} + run: go run -C tools ./cmd/release prepare -root .. -repo-url "$REPO_URL" -body "$RUNNER_TEMP/body.md" -github-output + - name: Open or update the pull request + if: steps.prepare.outputs.count != '0' + env: + GH_TOKEN: ${{ steps.app.outputs.token }} + REPOSITORY: ${{ github.repository }} + OWNER: ${{ github.repository_owner }} + SLUG: ${{ steps.app.outputs.app-slug }} + TITLE: ${{ steps.prepare.outputs.title }} + run: | + id="$(gh api "users/$SLUG%5Bbot%5D" --jq .id)" + git config user.name "${SLUG}[bot]" + git config user.email "${id}+${SLUG}[bot]@users.noreply.github.com" + git switch --quiet -c "$BRANCH" + git add plugins/*/CHANGELOG.md + git commit --quiet -m "$TITLE" + + # The App's token for this push only; the checkout keeps no credentials. + auth="$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 -w0)" + echo "::add-mask::$auth" + git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic $auth" \ + push --force --quiet origin "HEAD:refs/heads/$BRANCH" + + number="$(gh api "repos/$REPOSITORY/pulls?head=$OWNER:$BRANCH&state=open" --jq '.[0].number // empty')" + if [ -z "$number" ]; then + url="$(gh api "repos/$REPOSITORY/pulls" -f title="$TITLE" -f head="$BRANCH" -f base=main \ + -F body=@"$RUNNER_TEMP/body.md" --jq .html_url)" + else + url="$(gh api -X PATCH "repos/$REPOSITORY/pulls/$number" -f title="$TITLE" \ + -F body=@"$RUNNER_TEMP/body.md" --jq .html_url)" + fi + echo "[$TITLE]($url)" >> "$GITHUB_STEP_SUMMARY" + - name: Close the pull request, with nothing to release + if: steps.prepare.outputs.count == '0' + env: + GH_TOKEN: ${{ steps.app.outputs.token }} + REPOSITORY: ${{ github.repository }} + OWNER: ${{ github.repository_owner }} + run: | + number="$(gh api "repos/$REPOSITORY/pulls?head=$OWNER:$BRANCH&state=open" --jq '.[0].number // empty')" + if [ -n "$number" ]; then + gh api -X PATCH "repos/$REPOSITORY/pulls/$number" -f state=closed > /dev/null + gh api -X DELETE "repos/$REPOSITORY/git/refs/heads/$BRANCH" > /dev/null || true + echo "Nothing to release: closed #$number." >> "$GITHUB_STEP_SUMMARY" + fi diff --git a/README.md b/README.md index aae4e3c..e0283cd 100644 --- a/README.md +++ b/README.md @@ -117,13 +117,33 @@ Each plugin is released on its own, as its container image, `ghcr.io/mycroblog/< linux/arm64. Its `go.mod` replaces the root module with `../..`, so it builds from a checkout of this repository, not with `go install …@version`. There are no GitHub releases: the images are the release. -To release a plugin, tag a commit of main with `plugins//v` and push the tag: +Releases go through one pull request, from `release/plugins`, that the [release pull request +workflow](.github/workflows/release-pr.yml) keeps up to date with main. It lists each plugin whose image changed since +its last release, with its next version, and writes that version to the plugin's `CHANGELOG.md`, with the commits that +reach its image. Merging it tags each version on main, `plugins//v`, as the release App. + +- **What needs a release**: a change to the plugin's image. That is its own files, but its tests, its Markdown and + `plugin.yaml`; the code of the root module it builds; the modules of its build; `.dockerignore`; and `.tool-versions`. + A change to tests, to CI, or to `tools/` and `scripts/` releases nothing. A plugin never released is released at + `0.1.0`. +- **The next version**, from the [Conventional Commits](https://www.conventionalcommits.org/) that reach the image: a + breaking change (`feat!:`, or a `BREAKING CHANGE:` footer) moves the major version, a `feat` the minor version, and + anything else the patch version. Before 1.0.0, a breaking change moves the minor version, as a `feat` does. After a + pre-release, the next version is its release: a fix after `0.2.0-rc.1` is `0.2.0`. +- **Another version**, such as a pre-release or 1.0.0: edit the first heading of the plugin's `CHANGELOG.md` in the + pull request, such as `## 0.2.0-rc.1 (2026-11-27)`. To leave a plugin out, revert its `CHANGELOG.md` there. Each push + to main makes the pull request again, which drops such edits, so make them just before merging. + +The last release of a plugin is its highest tag, and a version at the top of a `CHANGELOG.md` with no tag yet is tagged +on the next push to main, whoever wrote it there. To see what the pull request would hold: ```sh -git tag plugins/my-media-ffmpeg/v0.1.0 origin/main -git push origin plugins/my-media-ffmpeg/v0.1.0 +GOWORK=off go run -C tools ./cmd/release plan -root .. ``` +The tags `plugins/*/v*` are protected by a ruleset: only the release App, and administrators, may create them. An +administrator may still tag a commit of main by hand, as the workflow does. + The [release workflow](.github/workflows/release.yml) runs the plugin's integration tests on each architecture, pushes the images, joins them into one index, and attests its provenance. It refuses a tag on a commit that is not on main, and a version that is already published: a published version never changes. @@ -137,14 +157,6 @@ a version that is already published: a published version never changes. There is no `latest`: a plugin speaks the protocol of the version of mycroblog/my that `buf.gen.yaml` pins, so a deployment names the version it runs. Each image carries that version in its label `dev.mycroblog.plugin.protocol`. -A plugin needs a new version when its build changed since its last release: its own files, the code of the root module -it imports, its Go version, or the packages of its image. affected tells which, though a change to the harness (CI, -`tools/`, `scripts/`) lists every plugin: - -```sh -GOWORK=off go run -C tools ./cmd/affected -root .. -base plugins/my-media-ffmpeg/v0.1.0 -``` - Check an image before you run it: ```sh diff --git a/tools/affected/affected.go b/tools/affected/affected.go index 5a98ffb..2ccfc0a 100644 --- a/tools/affected/affected.go +++ b/tools/affected/affected.go @@ -71,20 +71,10 @@ func Compute(ctx context.Context, root, base string) (Result, error) { if err != nil { return Result{}, err } - mergeBase, err := git(ctx, root, "merge-base", base, "HEAD") - if err != nil { - return Result{}, err - } - mergeBase = strings.TrimSpace(mergeBase) - out, err := git(ctx, root, "diff", "--name-only", "--no-renames", mergeBase) - if err != nil { - return Result{}, err - } - untracked, err := git(ctx, root, "ls-files", "--others", "--exclude-standard") + mergeBase, changed, err := changedSince(ctx, root, base) if err != nil { return Result{}, err } - changed := slices.Compact(slices.Sorted(slices.Values(append(lines(out), lines(untracked)...)))) plugins, err := pluginNames(root) if err != nil { @@ -130,6 +120,24 @@ func Compute(ctx context.Context, root, base string) (Result, error) { return res, nil } +// changedSince returns the merge base of base and HEAD, and the files changed since it, working tree included. +func changedSince(ctx context.Context, root, base string) (string, []string, error) { + mergeBase, err := git(ctx, root, "merge-base", base, "HEAD") + if err != nil { + return "", nil, err + } + mergeBase = strings.TrimSpace(mergeBase) + out, err := git(ctx, root, "diff", "--name-only", "--no-renames", mergeBase) + if err != nil { + return "", nil, err + } + untracked, err := git(ctx, root, "ls-files", "--others", "--exclude-standard") + if err != nil { + return "", nil, err + } + return mergeBase, slices.Compact(slices.Sorted(slices.Values(append(lines(out), lines(untracked)...)))), nil +} + func isHarness(f string) bool { return slices.ContainsFunc(harness, func(h string) bool { return f == h || strings.HasSuffix(h, "/") && strings.HasPrefix(f, h) @@ -299,17 +307,42 @@ func (b build) modules(ctx context.Context, root string) (map[string]string, err // affected returns the affected packages of the main module of the build, given the files changed since the checkout // of the merge base at baseDir. func (b build) affected(ctx context.Context, baseDir string, changed []string) ([]string, error) { - nodes, err := b.list(ctx) + nodes, code, err := b.code(ctx, baseDir, changed) if err != nil { return nil, err } + mainPath := moduleOf(b.dir) + var out []string + for ip, n := range nodes { + // Only the packages of the build's own module: the root module's are tested in its own build, and a change of + // their code reaches the plugin's packages through their imports. + if n.module == nil || n.module.Path != mainPath { + continue + } + if code[ip] || changedFiles(b.root, n, changed, n.testFiles, false, true) || + slices.ContainsFunc(n.testImports, func(imp string) bool { return code[imp] }) { + out = append(out, ip) + } + } + slices.Sort(out) + return out, nil +} + +// code returns the packages of the build, and those whose code changed since the checkout of the merge base at +// baseDir: one of their code files changed, a package their code imports changed code, or the module they belong to +// changed version in this build. +func (b build) code(ctx context.Context, baseDir string, changed []string) (map[string]*node, map[string]bool, error) { + nodes, err := b.list(ctx) + if err != nil { + return nil, nil, err + } headMods, err := b.modules(ctx, b.root) if err != nil { - return nil, err + return nil, nil, err } baseMods, err := b.modules(ctx, baseDir) if err != nil { - return nil, fmt.Errorf("at the merge base: %w", err) + return nil, nil, fmt.Errorf("at the merge base: %w", err) } // The modules of the build whose version changed, and the main modules whose directives changed. moved := map[string]bool{} @@ -319,33 +352,9 @@ func (b build) affected(ctx context.Context, baseDir string, changed []string) ( } } - // changedFiles reports whether a file of files in the package's directory, or of its testdata/ with testdata, - // changed; or, with goFiles, a Go file of the directory that no longer exists. - changedFiles := func(n *node, files []string, goFiles, testdata bool) bool { - if n.dir == "" { - return false - } - rel, err := filepath.Rel(b.root, n.dir) - if err != nil || strings.HasPrefix(rel, "..") { - return false // outside the repository - } - rel = filepath.ToSlash(rel) - for _, f := range changed { - switch { - case path.Dir(f) == rel && slices.Contains(files, path.Base(f)): - return true - case goFiles && path.Dir(f) == rel && path.Ext(f) == ".go" && !strings.HasSuffix(f, "_test.go"): - return true // a deleted file of the package's code - case testdata && (strings.HasPrefix(f, rel+"/testdata/") || path.Dir(f) == rel && strings.HasSuffix(f, "_test.go")): - return true // a file of its testdata, or a deleted test file - } - } - return false - } - code := map[string]bool{} for ip, n := range nodes { - if n.module != nil && moved[n.module.Path] || changedFiles(n, n.codeFiles, true, false) { + if n.module != nil && moved[n.module.Path] || changedFiles(b.root, n, changed, n.codeFiles, true, false) { code[ip] = true } } @@ -358,22 +367,40 @@ func (b build) affected(ctx context.Context, baseDir string, changed []string) ( } } } + return nodes, code, nil +} - mainPath := moduleOf(b.dir) - var out []string - for ip, n := range nodes { - // Only the packages of the build's own module: the root module's are tested in its own build, and a change of - // their code reaches the plugin's packages through their imports. - if n.module == nil || n.module.Path != mainPath { - continue - } - if code[ip] || changedFiles(n, n.testFiles, false, true) || - slices.ContainsFunc(n.testImports, func(imp string) bool { return code[imp] }) { - out = append(out, ip) +// changedFiles reports whether a file of files in the directory of the package, in the repository at root, or of its +// testdata/ with testdata, is among changed; or, with goFiles, a Go file of the directory that no longer exists. +func changedFiles(root string, n *node, changed, files []string, goFiles, testdata bool) bool { + rel, ok := repoDir(root, n) + if !ok { + return false + } + for _, f := range changed { + switch { + case path.Dir(f) == rel && slices.Contains(files, path.Base(f)): + return true + case goFiles && path.Dir(f) == rel && path.Ext(f) == ".go" && !strings.HasSuffix(f, "_test.go"): + return true // a deleted file of the package's code + case testdata && (strings.HasPrefix(f, rel+"/testdata/") || path.Dir(f) == rel && strings.HasSuffix(f, "_test.go")): + return true // a file of its testdata, or a deleted test file } } - slices.Sort(out) - return out, nil + return false +} + +// repoDir returns the directory of the package relative to the repository at root, with slashes, and whether it is in +// the repository at all. +func repoDir(root string, n *node) (string, bool) { + if n.dir == "" { + return "", false + } + rel, err := filepath.Rel(root, n.dir) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return "", false // outside the repository + } + return filepath.ToSlash(rel), true } func moduleOf(dir string) string { diff --git a/tools/affected/release.go b/tools/affected/release.go new file mode 100644 index 0000000..e133a6e --- /dev/null +++ b/tools/affected/release.go @@ -0,0 +1,147 @@ +package affected + +import ( + "context" + "path" + "path/filepath" + "slices" + "strings" +) + +// What changes the image of a plugin, for its releases, is narrower than what CI tests for a change: +// +// - the tests: a test file or a file of testdata/ changes no image; +// - the harness: the CI, tools/ and scripts/ change no image, but .dockerignore and .tool-versions (see imageInputs) do; +// - plugin.yaml, which says what the contract tests check, is not in the image. +// +// The code a plugin builds counts as for CI: its own, that of the root module it imports, and the modules of its build. + +// imageInputs are the files outside plugins/ and the Go code that the images are built with: what the Dockerfiles may +// copy, and the Go version they build with. +var imageInputs = []string{".dockerignore", ".tool-versions"} + +// Release reports whether the image of the plugin changed since base, a revision (its last release), compared from its +// merge base with HEAD, working tree included. +func Release(ctx context.Context, root, base, plugin string) (bool, error) { + root, err := filepath.Abs(root) + if err != nil { + return false, err + } + mergeBase, changed, err := changedSince(ctx, root, base) + if err != nil { + return false, err + } + if slices.ContainsFunc(changed, func(f string) bool { return slices.Contains(imageInputs, f) || ownImageFile(plugin, f) }) { + return true, nil + } + if len(changed) == 0 { + return false, nil + } + + baseDir, cleanup, err := worktree(ctx, root, mergeBase) + if err != nil { + return false, err + } + defer cleanup() + b := build{root: root, dir: filepath.Join(root, "plugins", plugin), plugin: plugin} + nodes, code, err := b.code(ctx, baseDir, changed) + if err != nil { + return false, err + } + mainPath := moduleOf(b.dir) + for ip, n := range nodes { + if n.module != nil && n.module.Path == mainPath && code[ip] { + return true, nil + } + } + return false, nil +} + +// Scope returns which files reach the image of the plugin, as the repository at root stands: the files of the plugin +// but its tests, its Markdown and plugin.yaml; the code files of the packages of the repository its code builds; the +// go.mod and go.sum of the modules of the repository in its build; and imageInputs. +// +// It tells which commits since a release went into the next one. Whether there is a next one is Release's to say, which +// compares the builds themselves: a commit can touch a go.sum without changing the build. +func Scope(ctx context.Context, root, plugin string) (func(file string) bool, error) { + root, err := filepath.Abs(root) + if err != nil { + return nil, err + } + b := build{root: root, dir: filepath.Join(root, "plugins", plugin), plugin: plugin} + nodes, err := b.list(ctx) + if err != nil { + return nil, err + } + + // The packages the plugin's code builds: those of its module, and what their code imports. + reach := map[string]bool{} + var visit func(ip string) + visit = func(ip string) { + n, ok := nodes[ip] + if !ok || reach[ip] { + return + } + reach[ip] = true + for _, imp := range n.codeImports { + visit(imp) + } + } + mainPath := moduleOf(b.dir) + for ip, n := range nodes { + if n.module != nil && n.module.Path == mainPath { + visit(ip) + } + } + + dirs, modFiles := map[string]bool{}, map[string]bool{} + for ip := range reach { + n := nodes[ip] + if rel, ok := repoDir(root, n); ok { + dirs[rel] = true + } + if n.module == nil { + continue + } + dir := n.module.Dir + if n.module.Replace != nil && n.module.Replace.Dir != "" { + dir = n.module.Replace.Dir + } + if rel, ok := repoDir(root, &node{dir: dir}); ok { + modFiles[path.Join(rel, "go.mod")], modFiles[path.Join(rel, "go.sum")] = true, true + } + } + + return func(f string) bool { + switch { + case slices.Contains(imageInputs, f), ownImageFile(plugin, f), modFiles[f]: + return true + case strings.HasPrefix(f, "plugins/"+plugin+"/"), path.Ext(f) == ".md", strings.HasSuffix(f, "_test.go"): + // The plugin's own files are ownImageFile's to say. + return false + default: + return dirs[path.Dir(f)] + } + }, nil +} + +// Plugins returns the names of the plugins of the repository at root: the directories of plugins/ with a go.mod. +func Plugins(root string) ([]string, error) { + return pluginNames(root) +} + +// ownImageFile reports whether f is a file of the plugin that its image is made of: any file under plugins// +// but its Markdown, its tests and testdata/, and plugin.yaml. +func ownImageFile(plugin, f string) bool { + rest, ok := strings.CutPrefix(f, "plugins/"+plugin+"/") + if !ok { + return false + } + switch { + case path.Ext(rest) == ".md", strings.HasSuffix(rest, "_test.go"), rest == "plugin.yaml": + return false + case strings.HasPrefix(rest, "testdata/"), strings.Contains(rest, "/testdata/"): + return false + } + return true +} diff --git a/tools/affected/release_test.go b/tools/affected/release_test.go new file mode 100644 index 0000000..600ef1e --- /dev/null +++ b/tools/affected/release_test.go @@ -0,0 +1,146 @@ +package affected + +import ( + "context" + "os/exec" + "testing" +) + +func TestRelease(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git is not installed") + } + t.Setenv("GOPROXY", "off") + t.Setenv("GOFLAGS", "") + + for _, tt := range []struct { + name string + change map[string]string + want map[string]bool // plugin → whether its image changed + }{ + { + name: "code of a package: the plugins that build it", + change: map[string]string{"internal/a/a.go": "package a\n\nfunc A() int { return 2 }\n"}, + want: map[string]bool{"p1": true, "p2": false}, + }, + { + name: "code that only a test imports: the plugins that build it, not those whose tests do", + change: map[string]string{"internal/c/c.go": "package c\n\nfunc C() int { return 4 }\n"}, + want: map[string]bool{"p1": false, "p2": true}, + }, + { + name: "a test of a plugin: no image", + change: map[string]string{"plugins/p1/main_test.go": "package main\n\nimport \"testing\"\n\nfunc TestMain(t *testing.T) {}\n"}, + want: map[string]bool{"p1": false, "p2": false}, + }, + { + name: "testdata of a plugin: no image", + change: map[string]string{"plugins/p1/testdata/in.txt": "in\n"}, + want: map[string]bool{"p1": false, "p2": false}, + }, + { + name: "plugin.yaml: no image", + change: map[string]string{"plugins/p1/plugin.yaml": "kinds: [media_image]\n"}, + want: map[string]bool{"p1": false, "p2": false}, + }, + { + name: "a plugin's Dockerfile: that plugin", + change: map[string]string{"plugins/p1/Dockerfile": "FROM busybox\n"}, + want: map[string]bool{"p1": true, "p2": false}, + }, + { + name: "a dependency of one plugin: that plugin", + change: map[string]string{"plugins/p1/go.mod": p1GoMod("ext2")}, + want: map[string]bool{"p1": true, "p2": false}, + }, + { + name: "the CI: no image", + change: map[string]string{".github/workflows/ci.yml": "on: push\n", "tools/x.go": "package tools\n"}, + want: map[string]bool{"p1": false, "p2": false}, + }, + { + name: "what the images may copy: every image", + change: map[string]string{".dockerignore": "*.md\n"}, + want: map[string]bool{"p1": true, "p2": true}, + }, + { + name: "Markdown: no image", + change: map[string]string{"README.md": "# changed\n", "plugins/p1/CHANGELOG.md": "# p1\n"}, + want: map[string]bool{"p1": false, "p2": false}, + }, + } { + t.Run(tt.name, func(t *testing.T) { + dir := repo(t) + for f, content := range tt.change { + write(t, dir, f, content) + } + gitRun(t, dir, "add", "-A") + gitRun(t, dir, "commit", "-q", "-m", "change") + for plugin, want := range tt.want { + got, err := Release(context.Background(), dir, "base", plugin) + if err != nil { + t.Fatal(err) + } + if got != want { + t.Errorf("Release(%s) = %v, want %v", plugin, got, want) + } + } + }) + } +} + +func TestReleaseNoChange(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git is not installed") + } + t.Setenv("GOPROXY", "off") + dir := repo(t) + got, err := Release(context.Background(), dir, "base", "p1") + if err != nil { + t.Fatal(err) + } + if got { + t.Error("Release = true for no change") + } +} + +func TestScope(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git is not installed") + } + t.Setenv("GOPROXY", "off") + dir := repo(t) + in, err := Scope(context.Background(), dir, "p1") + if err != nil { + t.Fatal(err) + } + for f, want := range map[string]bool{ + "plugins/p1/main.go": true, + "plugins/p1/Dockerfile": true, + "plugins/p1/go.mod": true, + "plugins/p1/gone.go": true, // a deleted file of the plugin + "internal/a/a.go": true, + "internal/a/gone.go": true, // a deleted file of a package it builds + "third_party/ext1/ext.go": true, + "third_party/ext1/go.mod": true, + "go.mod": true, + ".dockerignore": true, + ".tool-versions": true, + "plugins/p1/README.md": false, + "plugins/p1/plugin.yaml": false, + "plugins/p1/main_test.go": false, + "plugins/p1/testdata/in.txt": false, + "internal/a/a_test.go": false, + "internal/a/testdata/in.txt": false, + "internal/b/b.go": false, + "internal/c/c.go": false, // imported by a test of internal/a only + "third_party/ext2/ext.go": false, + "plugins/p2/main.go": false, + ".github/workflows/ci.yml": false, + "README.md": false, + } { + if got := in(f); got != want { + t.Errorf("Scope(p1)(%s) = %v, want %v", f, got, want) + } + } +} diff --git a/tools/cmd/release/main.go b/tools/cmd/release/main.go new file mode 100644 index 0000000..6ce83d3 --- /dev/null +++ b/tools/cmd/release/main.go @@ -0,0 +1,95 @@ +// Command release prepares the releases of the plugins (see package release): +// +// release plan print the plugins with a change since their last release, and their next versions +// release prepare write those versions to their CHANGELOG.md, and the release pull request's title and body +// release tags print the tags of the versions at the top of the changelogs that are not tagged yet +// +// Every command takes -root, the repository, checked out with its tags. +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "os" + "time" + + "github.com/mycroblog/plugin/tools/release" +) + +func main() { + if len(os.Args) < 2 { + usage() + } + cmd, args := os.Args[1], os.Args[2:] + fs := flag.NewFlagSet("release "+cmd, flag.ExitOnError) + root := fs.String("root", ".", "the repository, checked out with its tags") + repoURL := fs.String("repo-url", "https://github.com/mycroblog/plugin", "the repository's URL, for the links to commits") + date := fs.String("date", time.Now().UTC().Format(time.DateOnly), "the date of the releases, YYYY-MM-DD") + body := fs.String("body", "", "prepare: write the pull request's body to this file") + githubOutput := fs.Bool("github-output", false, "prepare: also write count and title to $GITHUB_OUTPUT") + _ = fs.Parse(args) + ctx := context.Background() + + switch cmd { + case "plan", "prepare": + d, err := time.Parse(time.DateOnly, *date) + check(err) + plans, err := release.Pending(ctx, *root) + check(err) + if cmd == "plan" { + type row struct { + Plugin string `json:"plugin"` + Last string `json:"last,omitempty"` + Next string `json:"next"` + Commits int `json:"commits"` + } + rows := []row{} + for _, p := range plans { + r := row{Plugin: p.Plugin, Next: p.Next.String(), Commits: len(p.Commits)} + if p.Last != nil { + r.Last = p.Last.String() + } + rows = append(rows, r) + } + out, _ := json.MarshalIndent(rows, "", " ") + fmt.Println(string(out)) + return + } + check(release.Write(*root, plans, *repoURL, d)) + for _, p := range plans { + fmt.Printf("%s %s\n", p.Plugin, p.Next) + } + if *body != "" { + check(os.WriteFile(*body, []byte(release.Body(plans, *repoURL, d)), 0o644)) + } + if *githubOutput { + f, err := os.OpenFile(os.Getenv("GITHUB_OUTPUT"), os.O_APPEND|os.O_WRONLY, 0) + check(err) + defer f.Close() + _, err = fmt.Fprintf(f, "count=%d\ntitle=%s\n", len(plans), release.Title(plans)) + check(err) + } + case "tags": + tags, err := release.Tags(ctx, *root) + check(err) + for _, t := range tags { + fmt.Println(t) + } + default: + usage() + } +} + +func usage() { + fmt.Fprintln(os.Stderr, "usage: release plan|prepare|tags [-root dir] [-repo-url url] [-date YYYY-MM-DD] [-body file] [-github-output]") + os.Exit(2) +} + +func check(err error) { + if err != nil { + fmt.Fprintln(os.Stderr, "release:", err) + os.Exit(1) + } +} diff --git a/tools/release/changelog.go b/tools/release/changelog.go new file mode 100644 index 0000000..c776cf7 --- /dev/null +++ b/tools/release/changelog.go @@ -0,0 +1,128 @@ +package release + +import ( + "fmt" + "os" + "strings" + "time" +) + +// Section returns the section of the changelog for the plan: its heading, then its commits by kind, each with a link +// to the commit at repoURL. +func Section(p Plan, repoURL string, date time.Time) string { + var b strings.Builder + fmt.Fprintf(&b, "## %s (%s)\n\n", p.Next, date.Format(time.DateOnly)) + if p.Last == nil { + b.WriteString("First release.\n") + return b.String() + } + if len(p.Commits) == 0 { + // Release found a change of the build that no commit's files show, such as a module that moved. + fmt.Fprintf(&b, "Built again, with the repository's changes since %s.\n", p.Last) + return b.String() + } + var parts []string + for _, s := range sections { + var lines []string + for _, c := range p.Commits { + if c.section() == s { + lines = append(lines, "- "+entry(p.Plugin, c, repoURL)) + } + } + if len(lines) > 0 { + parts = append(parts, fmt.Sprintf("### %s\n\n%s\n", s, strings.Join(lines, "\n"))) + } + } + b.WriteString(strings.Join(parts, "\n")) + return b.String() +} + +// entry is the line of a commit: its description, its scope unless the scope names the plugin, and its link. +func entry(plugin string, c Commit, repoURL string) string { + s := c.Description + if c.Scope != "" && c.Scope != plugin && !strings.HasSuffix(plugin, "-"+c.Scope) { + s = "**" + c.Scope + ":** " + s + } + short := c.Hash + if len(short) > 7 { + short = short[:7] + } + return fmt.Sprintf("%s ([%s](%s/commit/%s))", s, short, repoURL, c.Hash) +} + +// Write puts the section of each plan at the top of its plugin's CHANGELOG.md, under its title, creating the file for +// a first release. +func Write(root string, plans []Plan, repoURL string, date time.Time) error { + for _, p := range plans { + path := changelogPath(root, p.Plugin) + old, err := os.ReadFile(path) + if err != nil && !os.IsNotExist(err) { + return err + } + content := string(old) + if content == "" { + content = "# Changelog of " + p.Plugin + "\n" + } + section := Section(p, repoURL, date) + // Before the first section, or at the end when there is none. + var out string + if i := strings.Index(content, "\n## "); i >= 0 { + out = content[:i+1] + "\n" + section + "\n" + content[i+1:] + } else { + out = strings.TrimRight(content, "\n") + "\n\n" + section + } + out = collapseBlankLines(out) + if err := os.WriteFile(path, []byte(out), 0o644); err != nil { + return err + } + } + return nil +} + +// collapseBlankLines leaves at most one blank line between two lines. +func collapseBlankLines(s string) string { + for strings.Contains(s, "\n\n\n") { + s = strings.ReplaceAll(s, "\n\n\n", "\n\n") + } + return s +} + +// Title is the title of the release pull request. +func Title(plans []Plan) string { + var parts []string + for _, p := range plans { + parts = append(parts, p.Plugin+" "+p.Next.String()) + } + return "chore: release " + strings.Join(parts, ", ") +} + +// Body is the description of the release pull request. +func Body(plans []Plan, repoURL string, date time.Time) string { + var b strings.Builder + b.WriteString("Releases the plugins below. Merging this pull request tags each version on main, " + + "`plugins//v`, and each tag releases the plugin's image.\n\n") + b.WriteString("| Plugin | Last release | Next |\n|---|---|---|\n") + for _, p := range plans { + last := "none" + if p.Last != nil { + last = p.Last.String() + } + fmt.Fprintf(&b, "| %s | %s | %s |\n", p.Plugin, last, p.Next) + } + b.WriteString("\n- To release another version, edit the first heading of the plugin's `CHANGELOG.md` " + + "in this pull request, such as `## 0.2.0-rc.1` for a pre-release.\n" + + "- To leave a plugin out, revert its `CHANGELOG.md` in this pull request.\n" + + "- This pull request is made again each time main moves, which drops such edits: make them just before merging.\n") + for _, p := range plans { + // The section's headings, two levels down, under the summary. + var section strings.Builder + for line := range strings.Lines(Section(p, repoURL, date)) { + if strings.HasPrefix(line, "#") { + line = "##" + line + } + section.WriteString(line) + } + fmt.Fprintf(&b, "\n
%s %s\n\n%s\n
\n", p.Plugin, p.Next, section.String()) + } + return b.String() +} diff --git a/tools/release/commit.go b/tools/release/commit.go new file mode 100644 index 0000000..4121924 --- /dev/null +++ b/tools/release/commit.go @@ -0,0 +1,58 @@ +package release + +import ( + "regexp" + "strings" +) + +// Commit is a commit since a plugin's last release that reaches its image, read as a Conventional Commit. +type Commit struct { + Hash string + Type string // "feat", "fix", …; "" when the subject is not a Conventional Commit + Scope string + Description string // the subject without its type and scope, or the whole subject + Breaking bool // a "!" after the type or scope, or a BREAKING CHANGE footer +} + +var subjectRE = regexp.MustCompile(`^([a-zA-Z]+)(?:\(([^()]*)\))?(!)?: (.+)$`) + +func parseCommit(hash, subject, body string) Commit { + c := Commit{Hash: hash, Description: strings.TrimSpace(subject)} + if m := subjectRE.FindStringSubmatch(c.Description); m != nil { + c.Type, c.Scope, c.Breaking, c.Description = strings.ToLower(m[1]), m[2], m[3] == "!", m[4] + } + for line := range strings.Lines(body) { + if strings.HasPrefix(line, "BREAKING CHANGE:") || strings.HasPrefix(line, "BREAKING-CHANGE:") { + c.Breaking = true + } + } + return c +} + +// bump is how much the commit moves the version. +func (c Commit) bump() Bump { + switch { + case c.Breaking: + return BumpMajor + case c.Type == "feat": + return BumpMinor + default: + return BumpPatch + } +} + +// section is the heading of the changelog the commit is listed under. +func (c Commit) section() string { + switch { + case c.Breaking: + return "Breaking changes" + case c.Type == "feat": + return "Features" + case c.Type == "fix": + return "Fixes" + default: + return "Other changes" + } +} + +var sections = []string{"Breaking changes", "Features", "Fixes", "Other changes"} diff --git a/tools/release/release.go b/tools/release/release.go new file mode 100644 index 0000000..1a89ef8 --- /dev/null +++ b/tools/release/release.go @@ -0,0 +1,219 @@ +// Package release prepares the releases of the plugins, one pull request for all of them: +// +// - Pending lists the plugins whose image changed since their last release (affected.Release), each with its next +// version, from the Conventional Commits that reach its image (affected.Scope); +// - Write puts that version, with those commits, at the top of the plugin's CHANGELOG.md, and Body and Title describe +// the pull request; +// - Tags, once the pull request is merged, lists the tags of the versions at the top of the changelogs that are not +// tagged yet. Each tag, plugins//v, releases the plugin's image (.github/workflows/release.yml). +// +// The tags are what was released: the last release of a plugin is its highest tag, and the changelogs only carry the +// next version until it is tagged, so a version can be edited in the pull request before it is merged. +package release + +import ( + "bytes" + "context" + "fmt" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + + "github.com/mycroblog/plugin/tools/affected" +) + +// Plan is the next release of a plugin. +type Plan struct { + Plugin string `json:"plugin"` + Last *Version `json:"-"` // its highest tag, or nil for its first release + Next Version `json:"-"` + Commits []Commit `json:"-"` // since Last, oldest first, that reach its image +} + +// TagName returns the tag of a version of a plugin. +func TagName(plugin string, v Version) string { + return "plugins/" + plugin + "/v" + v.String() +} + +// Pending returns the next release of each plugin of the repository at root whose image changed since its last +// release, or that was never released, in the order of their names. +func Pending(ctx context.Context, root string) ([]Plan, error) { + plugins, err := affected.Plugins(root) + if err != nil { + return nil, err + } + var plans []Plan + for _, name := range plugins { + p, ok, err := pending(ctx, root, name) + if err != nil { + return nil, fmt.Errorf("%s: %w", name, err) + } + if ok { + plans = append(plans, p) + } + } + return plans, nil +} + +func pending(ctx context.Context, root, name string) (Plan, bool, error) { + tags, err := tagged(ctx, root, name) + if err != nil { + return Plan{}, false, err + } + top, hasTop, err := TopVersion(root, name) + if err != nil { + return Plan{}, false, err + } + if len(tags) == 0 { + if hasTop { + return Plan{}, false, nil // its first version waits for its tag + } + return Plan{Plugin: name, Next: Version{Minor: 1}}, true, nil + } + + last := tags[len(tags)-1] + if hasTop && Compare(top, last) > 0 { + return Plan{}, false, nil // its next version waits for its tag + } + changed, err := affected.Release(ctx, root, TagName(name, last), name) + if err != nil || !changed { + return Plan{}, false, err + } + commits, err := commitsSince(ctx, root, TagName(name, last), name) + if err != nil { + return Plan{}, false, err + } + + // The next version counts from the last release, and comes after the last pre-release: a fix after 0.2.0-rc.1 + // is 0.2.0, not 0.1.1. + bump := BumpPatch + for _, c := range commits { + bump = max(bump, c.bump()) + } + base := Version{} + for _, v := range tags { + if v.Pre == "" { + base = v + } + } + next := base.Next(bump) + if Compare(last.Core(), next) > 0 || last.Pre != "" && Compare(last.Core(), next) == 0 { + next = last.Core() + } + return Plan{Plugin: name, Last: &last, Next: next, Commits: commits}, true, nil +} + +// Tags returns the tags to create for the versions at the top of the changelogs of the repository at root that are +// not tagged yet. A version that does not come after the plugin's last release is an error. +func Tags(ctx context.Context, root string) ([]string, error) { + plugins, err := affected.Plugins(root) + if err != nil { + return nil, err + } + var out []string + for _, name := range plugins { + top, ok, err := TopVersion(root, name) + if err != nil { + return nil, fmt.Errorf("%s: %w", name, err) + } + if !ok { + continue + } + tags, err := tagged(ctx, root, name) + if err != nil { + return nil, fmt.Errorf("%s: %w", name, err) + } + if slices.ContainsFunc(tags, func(v Version) bool { return Compare(v, top) == 0 }) { + continue + } + if len(tags) > 0 && Compare(top, tags[len(tags)-1]) < 0 { + return nil, fmt.Errorf("%s: CHANGELOG.md says %s, which comes before its last release, %s", name, top, tags[len(tags)-1]) + } + out = append(out, TagName(name, top)) + } + return out, nil +} + +// tagged returns the versions of the plugin's tags, lowest first. A tag that is not a version is ignored. +func tagged(ctx context.Context, root, name string) ([]Version, error) { + out, err := git(ctx, root, "tag", "--list", "plugins/"+name+"/v*") + if err != nil { + return nil, err + } + var vs []Version + for t := range strings.Lines(out) { + if v, err := ParseVersion(strings.TrimPrefix(strings.TrimSpace(t), "plugins/"+name+"/v")); err == nil { + vs = append(vs, v) + } + } + slices.SortFunc(vs, Compare) + return vs, nil +} + +// commitsSince returns the commits since base that reach the plugin's image, oldest first, merges left out. +func commitsSince(ctx context.Context, root, base, name string) ([]Commit, error) { + inScope, err := affected.Scope(ctx, root, name) + if err != nil { + return nil, err + } + // One record per commit: \x1e hash \x00 subject \x00 body \x00, then the files it changed, one per line. + out, err := git(ctx, root, "log", "--reverse", "--no-merges", "--no-renames", "--name-only", + "--format=%x1e%H%x00%s%x00%b%x00", base+"..HEAD") + if err != nil { + return nil, err + } + var commits []Commit + for rec := range strings.SplitSeq(out, "\x1e") { + fields := strings.SplitN(rec, "\x00", 4) + if len(fields) < 4 { + continue + } + if slices.ContainsFunc(strings.Fields(fields[3]), inScope) { + commits = append(commits, parseCommit(fields[0], fields[1], fields[2])) + } + } + return commits, nil +} + +func git(ctx context.Context, dir string, args ...string) (string, error) { + cmd := exec.CommandContext(ctx, "git", args...) + cmd.Dir = dir + var stdout, stderr bytes.Buffer + cmd.Stdout, cmd.Stderr = &stdout, &stderr + if err := cmd.Run(); err != nil { + return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(stderr.String())) + } + return stdout.String(), nil +} + +func changelogPath(root, name string) string { + return filepath.Join(root, "plugins", name, "CHANGELOG.md") +} + +// TopVersion returns the version of the first heading "## " of the plugin's CHANGELOG.md, and whether there +// is one. +func TopVersion(root, name string) (Version, bool, error) { + b, err := os.ReadFile(changelogPath(root, name)) + if os.IsNotExist(err) { + return Version{}, false, nil + } + if err != nil { + return Version{}, false, err + } + for line := range strings.Lines(string(b)) { + if h, ok := strings.CutPrefix(line, "## "); ok { + f := strings.Fields(h) + if len(f) == 0 { + break + } + v, err := ParseVersion(f[0]) + if err != nil { + return Version{}, false, fmt.Errorf("CHANGELOG.md: %w", err) + } + return v, true, nil + } + } + return Version{}, false, nil +} diff --git a/tools/release/release_test.go b/tools/release/release_test.go new file mode 100644 index 0000000..0986d6a --- /dev/null +++ b/tools/release/release_test.go @@ -0,0 +1,310 @@ +package release + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "reflect" + "strings" + "testing" + "time" +) + +const goVersion = "1.27.4" + +func v(s string) Version { + ver, err := ParseVersion(s) + if err != nil { + panic(err) + } + return ver +} + +func TestParseVersion(t *testing.T) { + for _, s := range []string{"0.1.0", "1.2.3", "0.2.0-rc.1", "1.0.0-alpha.beta-1"} { + got, err := ParseVersion(s) + if err != nil || got.String() != s { + t.Errorf("ParseVersion(%q) = %v, %v", s, got, err) + } + } + for _, s := range []string{"", "v0.1.0", "01.0.0", "1.2", "1.2.3-", "1.2.3+build", "1.2.3-rc..1"} { + if _, err := ParseVersion(s); err == nil { + t.Errorf("ParseVersion(%q) succeeded", s) + } + } +} + +func TestCompare(t *testing.T) { + // In order of precedence, as in the example of Semantic Versioning 2.0.0, §11. + order := []string{"0.9.9", "1.0.0-alpha", "1.0.0-alpha.1", "1.0.0-alpha.beta", "1.0.0-beta", "1.0.0-beta.2", + "1.0.0-beta.11", "1.0.0-rc.1", "1.0.0", "1.0.1", "1.1.0", "2.0.0"} + for i := range order { + for j := range order { + want := 0 + if i < j { + want = -1 + } else if i > j { + want = 1 + } + if got := Compare(v(order[i]), v(order[j])); got != want { + t.Errorf("Compare(%s, %s) = %d, want %d", order[i], order[j], got, want) + } + } + } +} + +func TestNext(t *testing.T) { + for _, tt := range []struct { + from string + bump Bump + want string + }{ + {"0.1.0", BumpPatch, "0.1.1"}, + {"0.1.3", BumpMinor, "0.2.0"}, + {"0.1.3", BumpMajor, "0.2.0"}, // before 1.0.0, a breaking change moves the minor version + {"1.2.3", BumpPatch, "1.2.4"}, + {"1.2.3", BumpMinor, "1.3.0"}, + {"1.2.3", BumpMajor, "2.0.0"}, + } { + if got := v(tt.from).Next(tt.bump).String(); got != tt.want { + t.Errorf("%s.Next(%d) = %s, want %s", tt.from, tt.bump, got, tt.want) + } + } +} + +func TestParseCommit(t *testing.T) { + for _, tt := range []struct { + subject, body string + want Commit + }{ + {"feat(libvips): add a plugin", "", Commit{Type: "feat", Scope: "libvips", Description: "add a plugin"}}, + {"fix: a crash", "", Commit{Type: "fix", Description: "a crash"}}, + {"feat(server)!: drop http://", "", Commit{Type: "feat", Scope: "server", Description: "drop http://", Breaking: true}}, + {"refactor: move code", "Some text.\n\nBREAKING CHANGE: the flag -x is gone\n", Commit{Type: "refactor", Description: "move code", Breaking: true}}, + {"Update the README", "", Commit{Description: "Update the README"}}, + } { + got := parseCommit("", tt.subject, tt.body) + if got != tt.want { + t.Errorf("parseCommit(%q) = %+v, want %+v", tt.subject, got, tt.want) + } + } +} + +var date = time.Date(2026, 11, 27, 0, 0, 0, 0, time.UTC) + +func TestSection(t *testing.T) { + last := v("0.1.0") + p := Plan{Plugin: "my-media-ffmpeg", Last: &last, Next: v("0.2.0"), Commits: []Commit{ + {Hash: "1111111aaaa", Type: "fix", Scope: "ffmpeg", Description: "keep the rotation"}, + {Hash: "2222222bbbb", Type: "feat", Scope: "server", Description: "serve over vsock"}, + {Hash: "3333333cccc", Type: "chore", Scope: "deps", Description: "bump the Debian image"}, + {Hash: "4444444dddd", Type: "fix", Description: "close the socket"}, + }} + want := `## 0.2.0 (2026-11-27) + +### Features + +- **server:** serve over vsock ([2222222](https://example.com/r/commit/2222222bbbb)) + +### Fixes + +- keep the rotation ([1111111](https://example.com/r/commit/1111111aaaa)) +- close the socket ([4444444](https://example.com/r/commit/4444444dddd)) + +### Other changes + +- **deps:** bump the Debian image ([3333333](https://example.com/r/commit/3333333cccc)) +` + if got := Section(p, "https://example.com/r", date); got != want { + t.Errorf("Section =\n%s\nwant\n%s", got, want) + } +} + +func TestWrite(t *testing.T) { + root := t.TempDir() + if err := os.MkdirAll(filepath.Join(root, "plugins", "p1"), 0o755); err != nil { + t.Fatal(err) + } + first := Plan{Plugin: "p1", Next: v("0.1.0")} + if err := Write(root, []Plan{first}, "https://example.com/r", date); err != nil { + t.Fatal(err) + } + last := v("0.1.0") + second := Plan{Plugin: "p1", Last: &last, Next: v("0.1.1"), Commits: []Commit{{Hash: "abcdef0123", Type: "fix", Description: "a fix"}}} + if err := Write(root, []Plan{second}, "https://example.com/r", date.AddDate(0, 0, 1)); err != nil { + t.Fatal(err) + } + got, err := os.ReadFile(filepath.Join(root, "plugins", "p1", "CHANGELOG.md")) + if err != nil { + t.Fatal(err) + } + want := `# Changelog of p1 + +## 0.1.1 (2026-11-28) + +### Fixes + +- a fix ([abcdef0](https://example.com/r/commit/abcdef0123)) + +## 0.1.0 (2026-11-27) + +First release. +` + if string(got) != want { + t.Errorf("CHANGELOG.md =\n%s\nwant\n%s", got, want) + } + if top, ok, err := TopVersion(root, "p1"); err != nil || !ok || top.String() != "0.1.1" { + t.Errorf("TopVersion = %v, %v, %v", top, ok, err) + } +} + +// fixture is a repository shaped like this one: plugin p1 imports internal/a, and p2 imports nothing of the root. +var fixture = map[string]string{ + "go.mod": "module github.com/mycroblog/plugin\n\ngo " + goVersion + "\n", + "internal/a/a.go": "package a\n\nfunc A() int { return 1 }\n", + "internal/a/a_test.go": "package a\n\nimport \"testing\"\n\nfunc TestA(t *testing.T) {}\n", + "plugins/p1/go.mod": pluginGoMod("p1"), + "plugins/p1/main.go": "package main\n\nimport \"github.com/mycroblog/plugin/internal/a\"\n\nfunc main() { _ = a.A() }\n", + "plugins/p2/go.mod": pluginGoMod("p2"), + "plugins/p2/main.go": "package main\n\nfunc main() {}\n", +} + +func pluginGoMod(name string) string { + return "module github.com/mycroblog/plugin/plugins/" + name + "\n\ngo " + goVersion + "\n\n" + + "require github.com/mycroblog/plugin v0.0.0-00010101000000-000000000000\n\nreplace github.com/mycroblog/plugin => ../..\n" +} + +func TestPendingAndTags(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git is not installed") + } + t.Setenv("GOPROXY", "off") + t.Setenv("GOFLAGS", "") + ctx := context.Background() + root := t.TempDir() + for f, content := range fixture { + write(t, root, f, content) + } + gitRun(t, root, "init", "-q", "-b", "main") + commit(t, root, "chore: the repository") + + // Never released: every plugin, at 0.1.0. + plans, err := Pending(ctx, root) + if err != nil { + t.Fatal(err) + } + if got := summary(plans); !reflect.DeepEqual(got, []string{"p1 -> 0.1.0", "p2 -> 0.1.0"}) { + t.Fatalf("Pending = %v", got) + } + + // The release pull request, merged: its versions get their tags, and nothing is pending. + if err := Write(root, plans, "https://example.com/r", date); err != nil { + t.Fatal(err) + } + commit(t, root, "chore: release p1 0.1.0, p2 0.1.0") + if plans, err := Pending(ctx, root); err != nil || len(plans) != 0 { + t.Fatalf("Pending before the tags = %v, %v; want none: the versions wait for their tags", summary(plans), err) + } + tags, err := Tags(ctx, root) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(tags, []string{"plugins/p1/v0.1.0", "plugins/p2/v0.1.0"}) { + t.Fatalf("Tags = %v", tags) + } + for _, tag := range tags { + gitRun(t, root, "tag", tag) + } + if tags, err := Tags(ctx, root); err != nil || len(tags) != 0 { + t.Fatalf("Tags after tagging = %v, %v", tags, err) + } + if plans, err := Pending(ctx, root); err != nil || len(plans) != 0 { + t.Fatalf("Pending after tagging = %v, %v", summary(plans), err) + } + + // A test, a fix of internal/a, and a feature of p2: p1 gets a patch, p2 a minor version. + write(t, root, "internal/a/a_test.go", "package a\n\nimport \"testing\"\n\nfunc TestA(t *testing.T) { _ = A() }\n") + commit(t, root, "test: call A") + write(t, root, "internal/a/a.go", "package a\n\nfunc A() int { return 2 }\n") + commit(t, root, "fix(a): return 2") + write(t, root, "plugins/p2/main.go", "package main\n\nfunc main() { println() }\n") + commit(t, root, "feat(p2): print a line") + plans, err = Pending(ctx, root) + if err != nil { + t.Fatal(err) + } + if got := summary(plans); !reflect.DeepEqual(got, []string{"p1 0.1.0 -> 0.1.1", "p2 0.1.0 -> 0.2.0"}) { + t.Fatalf("Pending = %v", got) + } + if got := descriptions(plans[0]); !reflect.DeepEqual(got, []string{"return 2"}) { + t.Errorf("p1's commits = %v, want the fix only", got) + } + if got := descriptions(plans[1]); !reflect.DeepEqual(got, []string{"print a line"}) { + t.Errorf("p2's commits = %v, want the feature only", got) + } + + // A pre-release of p2, then a fix: the fix goes into the release of that pre-release. + gitRun(t, root, "tag", "plugins/p2/v0.2.0-rc.1") + write(t, root, "plugins/p2/main.go", "package main\n\nfunc main() { println(1) }\n") + commit(t, root, "fix(p2): print 1") + plans, err = Pending(ctx, root) + if err != nil { + t.Fatal(err) + } + if got := summary(plans); !reflect.DeepEqual(got, []string{"p1 0.1.0 -> 0.1.1", "p2 0.2.0-rc.1 -> 0.2.0"}) { + t.Fatalf("Pending = %v", got) + } + + // A changelog edited by hand to a version before the last release is refused. + write(t, root, "plugins/p1/CHANGELOG.md", "# Changelog of p1\n\n## 0.0.9 (2026-11-27)\n\nOld.\n") + if _, err := Tags(ctx, root); err == nil || !strings.Contains(err.Error(), "before its last release") { + t.Errorf("Tags with an older version = %v, want an error", err) + } +} + +func summary(plans []Plan) []string { + var out []string + for _, p := range plans { + if p.Last == nil { + out = append(out, p.Plugin+" -> "+p.Next.String()) + } else { + out = append(out, p.Plugin+" "+p.Last.String()+" -> "+p.Next.String()) + } + } + return out +} + +func descriptions(p Plan) []string { + var out []string + for _, c := range p.Commits { + out = append(out, c.Description) + } + return out +} + +func commit(t *testing.T, dir, message string) { + t.Helper() + gitRun(t, dir, "add", "-A") + gitRun(t, dir, "commit", "-q", "-m", message) +} + +func write(t *testing.T, dir, f, content string) { + t.Helper() + p := filepath.Join(dir, f) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(content), 0o644); err != nil { + t.Fatal(err) + } +} + +func gitRun(t *testing.T, dir string, args ...string) { + t.Helper() + cmd := exec.Command("git", append([]string{"-c", "user.name=test", "-c", "user.email=test@example.com", "-c", "commit.gpgsign=false", "-c", "tag.gpgsign=false"}, args...)...) + cmd.Dir = dir + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %s: %v: %s", strings.Join(args, " "), err, out) + } +} diff --git a/tools/release/version.go b/tools/release/version.go new file mode 100644 index 0000000..307152e --- /dev/null +++ b/tools/release/version.go @@ -0,0 +1,102 @@ +package release + +import ( + "cmp" + "fmt" + "regexp" + "strconv" + "strings" +) + +// Version is the version of a plugin: Semantic Versioning, without build metadata. +type Version struct { + Major, Minor, Patch int + Pre string // the pre-release, without its "-": "rc.1", or "" for a release +} + +var versionRE = regexp.MustCompile(`^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$`) + +// ParseVersion parses "1.2.3" or "1.2.3-rc.1", without a leading v. +func ParseVersion(s string) (Version, error) { + m := versionRE.FindStringSubmatch(s) + if m == nil { + return Version{}, fmt.Errorf("%q is not a version: ..[-]", s) + } + var v Version + v.Major, _ = strconv.Atoi(m[1]) + v.Minor, _ = strconv.Atoi(m[2]) + v.Patch, _ = strconv.Atoi(m[3]) + v.Pre = m[4] + return v, nil +} + +func (v Version) String() string { + s := fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch) + if v.Pre != "" { + s += "-" + v.Pre + } + return s +} + +// Core returns the release that the version is a pre-release of, or the version itself. +func (v Version) Core() Version { + return Version{Major: v.Major, Minor: v.Minor, Patch: v.Patch} +} + +// Compare compares a and b by the precedence of Semantic Versioning: -1, 0, or +1. +func Compare(a, b Version) int { + if c := cmp.Or(cmp.Compare(a.Major, b.Major), cmp.Compare(a.Minor, b.Minor), cmp.Compare(a.Patch, b.Patch)); c != 0 { + return c + } + switch { + case a.Pre == b.Pre: + return 0 + case a.Pre == "": + return 1 // a release comes after its pre-releases + case b.Pre == "": + return -1 + } + as, bs := strings.Split(a.Pre, "."), strings.Split(b.Pre, ".") + for i := 0; i < len(as) && i < len(bs); i++ { + an, aErr := strconv.Atoi(as[i]) + bn, bErr := strconv.Atoi(bs[i]) + var c int + switch { + case aErr == nil && bErr == nil: + c = cmp.Compare(an, bn) + case aErr == nil: + c = -1 // a numeric identifier comes before an alphanumeric one + case bErr == nil: + c = 1 + default: + c = strings.Compare(as[i], bs[i]) + } + if c != 0 { + return c + } + } + return cmp.Compare(len(as), len(bs)) +} + +// Bump is how much a change moves the version. +type Bump int + +const ( + BumpPatch Bump = iota // a fix, or any other change to the image + BumpMinor // a feature + BumpMajor // a breaking change +) + +// Next returns the version after v for a change of bump. Before 1.0.0, a breaking change moves the minor version, as +// a feature does: 0.x versions make no promise of compatibility, and 1.0.0 is a decision, not a commit. +func (v Version) Next(bump Bump) Version { + v = v.Core() + switch { + case bump == BumpMajor && v.Major > 0: + return Version{Major: v.Major + 1} + case bump >= BumpMinor: + return Version{Major: v.Major, Minor: v.Minor + 1} + default: + return Version{Major: v.Major, Minor: v.Minor, Patch: v.Patch + 1} + } +}