From 707b7bd279a7a62876349b6b580d536d912580ce Mon Sep 17 00:00:00 2001 From: Andrew Tongen Date: Tue, 3 Nov 2026 16:39:39 -0600 Subject: [PATCH] Add release Rake tasks and idempotent release workflow rake release:prepare[VERSION] sets Drip::VERSION and moves the [Unreleased] CHANGELOG.md entries under a dated section; prereleases (X.Y.Z.rcN) change only the version. rake release:tag checks branch, tree, tags, RubyGems, CHANGELOG.md, and CI on HEAD, then creates and pushes the tag after confirmation. rake release:notes renders the notes the workflow publishes. The decision logic lives in rakelib/release_tools and is unit tested. Bundler's rake release is removed; build and install remain. release.yml builds the gem and notes in an unprivileged job, then creates a draft GitHub release, pushes the gem unless it is already on RubyGems, and publishes the draft in a separate job. Each step skips completed work, so a failed run can be re-run. Running the workflow manually is a dry run that uploads the gem and notes as an artifact. --- .github/workflows/release.yml | 111 +++++++++++---- .rubocop.yml | 1 + CHANGELOG.md | 6 +- README.md | 33 +++-- Rakefile | 10 +- rakelib/release.rake | 137 ++++++++++++++++++ rakelib/release_tools.rb | 32 +++++ rakelib/release_tools/changelog.rb | 94 ++++++++++++ rakelib/release_tools/checks.rb | 72 ++++++++++ rakelib/release_tools/version.rb | 30 ++++ test/rakelib/release_tools_test.rb | 222 +++++++++++++++++++++++++++++ 11 files changed, 709 insertions(+), 39 deletions(-) create mode 100644 rakelib/release.rake create mode 100644 rakelib/release_tools.rb create mode 100644 rakelib/release_tools/changelog.rb create mode 100644 rakelib/release_tools/checks.rb create mode 100644 rakelib/release_tools/version.rb create mode 100644 test/rakelib/release_tools_test.rb diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2136d82..b80dfb7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -3,6 +3,7 @@ name: Release on: push: tags: ["v*"] + workflow_dispatch: permissions: {} @@ -16,13 +17,15 @@ jobs: permissions: contents: read - release: + build: needs: test runs-on: ubuntu-latest - environment: release permissions: - contents: write - id-token: write + contents: read + outputs: + version: ${{ steps.metadata.outputs.version }} + tag: ${{ steps.metadata.outputs.tag }} + prerelease: ${{ steps.metadata.outputs.prerelease }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -34,40 +37,92 @@ jobs: - run: bundle install - name: Verify tagged commit is on main + if: github.event_name == 'push' run: | if ! git merge-base --is-ancestor "${GITHUB_SHA}" origin/main; then echo "tag ${GITHUB_REF_NAME} (${GITHUB_SHA}) is not on main" >&2 exit 1 fi - - name: Verify tag matches Drip::VERSION - run: | - version="$(bundle exec ruby -Ilib -e 'require "drip/version"; print Drip::VERSION')" - if [ "${GITHUB_REF_NAME}" != "v${version}" ]; then - echo "tag ${GITHUB_REF_NAME} does not match Drip::VERSION v${version}" >&2 - exit 1 - fi + - name: Read release metadata + id: metadata + env: + TAG: ${{ github.event_name == 'push' && github.ref_name || '' }} + run: bundle exec rake "release:metadata[${TAG}]" >> "${GITHUB_OUTPUT}" - - name: Extract release notes from CHANGELOG.md + - name: Build gem and release notes + env: + VERSION: ${{ steps.metadata.outputs.version }} run: | - version="${GITHUB_REF_NAME#v}" - awk -v v="$version" ' - /^## \[/ { in_section = index($0, "## [" v "]") == 1; next } - in_section { print } - ' CHANGELOG.md > "${RUNNER_TEMP}/release-notes.md" - if ! grep -q '[^[:space:]]' "${RUNNER_TEMP}/release-notes.md"; then - echo "no CHANGELOG.md section found for ${version}" >&2 - exit 1 - fi + mkdir dist + gem build drip-ruby.gemspec --output "dist/drip-ruby-${VERSION}.gem" + bundle exec rake "release:notes[${VERSION}]" > dist/release-notes.md + cat dist/release-notes.md >> "${GITHUB_STEP_SUMMARY}" + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: release + path: dist/ + if-no-files-found: error - - uses: rubygems/release-gem@7f9650160c1a4e7989fdc9855807bdbd421d8b6b # v1.4.1 + release: + if: github.event_name == 'push' + needs: build + runs-on: ubuntu-latest + environment: release + permissions: + contents: write + id-token: write + steps: + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: release + path: dist + - uses: ruby/setup-ruby@14594264cd68ce8a2345dd349bc3d138a4ef85c8 # v1.327.0 + with: + ruby-version: "3.4" + - uses: rubygems/configure-rubygems-credentials@bc6dd217f8a4f919d6835fcfefd470ef821f5c44 # v1.0.0 - - name: Create GitHub release + - name: Create or update the draft GitHub release env: GH_TOKEN: ${{ github.token }} + TAG: ${{ needs.build.outputs.tag }} + PRERELEASE: ${{ needs.build.outputs.prerelease }} + run: | + draft="$(gh release view "${TAG}" --repo "${GITHUB_REPOSITORY}" --json isDraft --jq .isDraft 2>/dev/null || echo missing)" + case "${draft}" in + missing) + flags=(--draft --verify-tag --title "${TAG}" --notes-file dist/release-notes.md) + if [ "${PRERELEASE}" = "true" ]; then flags+=(--prerelease); fi + gh release create "${TAG}" dist/*.gem --repo "${GITHUB_REPOSITORY}" "${flags[@]}" + ;; + true) + gh release upload "${TAG}" dist/*.gem --repo "${GITHUB_REPOSITORY}" --clobber + ;; + *) + echo "release ${TAG} is already published" + ;; + esac + + - name: Push gem to RubyGems + env: + VERSION: ${{ needs.build.outputs.version }} run: | - gh release create "${GITHUB_REF_NAME}" pkg/*.gem \ - --repo "${GITHUB_REPOSITORY}" \ - --title "${GITHUB_REF_NAME}" \ - --notes-file "${RUNNER_TEMP}/release-notes.md" \ - --verify-tag + if curl -fsS https://rubygems.org/api/v1/versions/drip-ruby.json | + jq -e --arg v "${VERSION}" 'any(.[]; .number == $v)' >/dev/null; then + echo "drip-ruby ${VERSION} is already on RubyGems" + else + gem push "dist/drip-ruby-${VERSION}.gem" + fi + + publish: + needs: [build, release] + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Publish the GitHub release + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ needs.build.outputs.tag }} + run: gh release edit "${TAG}" --repo "${GITHUB_REPOSITORY}" --draft=false diff --git a/.rubocop.yml b/.rubocop.yml index e49c468..b79e0bb 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -57,3 +57,4 @@ Metrics/ClassLength: Metrics/BlockLength: Exclude: - 'test/**/*' + - 'rakelib/**/*.rake' diff --git a/CHANGELOG.md b/CHANGELOG.md index 571e10a..bf27d9c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,13 +6,15 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ## [Unreleased] -[main]: https://github.com/DripEmail/drip-ruby/compare/v3.5.0...HEAD +[Unreleased]: https://github.com/DripEmail/drip-ruby/compare/v3.5.0...HEAD ### Changed - Raised `required_ruby_version` to `>= 3.2`; Ruby 3.1 is no longer supported. - CI runs the test suite on Ruby 3.2, 3.3, 3.4, and 4.0. - Releases are published from GitHub Actions when a `v*` tag on `main` is - pushed, after the CI suite passes. + pushed, after the CI suite passes. `rake release:prepare` and + `rake release:tag` drive the release; `rake release` (from Bundler) is + removed. Prerelease versions (`X.Y.Z.rcN`) are supported. - The gem package contains only `lib/`, `LICENSE.txt`, `README.md`, and `CHANGELOG.md`, and building it no longer requires a git checkout. diff --git a/README.md b/README.md index 4d03639..ce976fe 100644 --- a/README.md +++ b/README.md @@ -238,11 +238,28 @@ subscriber.email ## Releasing -1. Set `Drip::VERSION` in `lib/drip/version.rb`. -2. Move the `[Unreleased]` entries in `CHANGELOG.md` under a new `## [x.y.z] - YYYY-MM-DD` heading. -3. Merge to `main`. -4. From an up-to-date `main`, tag and push: `git tag -a vX.Y.Z -m vX.Y.Z && git push origin vX.Y.Z`. - -Pushing the tag triggers `.github/workflows/release.yml`, which checks that the -tag matches `Drip::VERSION`, publishes the gem to RubyGems, and creates the -GitHub release with the matching `CHANGELOG.md` section as its notes. +Releases are cut with Rake tasks and published by +`.github/workflows/release.yml` when a `v*` tag is pushed. Versions are +`X.Y.Z`, or `X.Y.Z.alphaN` / `X.Y.Z.betaN` / `X.Y.Z.rcN` for prereleases. + +1. On a branch off an up-to-date `main`, run + `bundle exec rake "release:prepare[X.Y.Z]"`. It sets `Drip::VERSION`, and + for a final release moves the `[Unreleased]` entries in `CHANGELOG.md` + under a dated `## [X.Y.Z]` section. A prerelease changes only the version; + its notes come from `[Unreleased]`. The task then runs rubocop and the + test suite. +2. Commit, open a pull request, and merge it after review. +3. On an up-to-date `main`, run `bundle exec rake release:tag`. It checks the + branch, working tree, version, existing tags, RubyGems, `CHANGELOG.md`, and + the CI result for `HEAD` (via `gh`), prints the release notes, and asks for + confirmation before creating and pushing the tag. + +The workflow runs the CI suite, verifies the tag is on `main` and matches +`Drip::VERSION`, builds the gem, creates a draft GitHub release with the gem +attached, pushes the gem to RubyGems, and publishes the GitHub release. Each +step skips work that is already done, so a failed run can be re-run. + +`bundle exec rake release:notes` previews the notes for the current version. +Running the Release workflow manually (`workflow_dispatch`) is a dry run: it +runs the tests, builds the gem and notes, and uploads them as a workflow +artifact without publishing anything. diff --git a/Rakefile b/Rakefile index 09a2d74..bbed770 100644 --- a/Rakefile +++ b/Rakefile @@ -1,8 +1,16 @@ # frozen_string_literal: true -require "bundler/gem_tasks" +require "bundler/gem_helper" require "rake/testtask" +gem_helper = Bundler::GemHelper.new(__dir__) + +desc "Build the gem into pkg/" +task(:build) { gem_helper.build_gem } + +desc "Build and install the gem into system gems" +task(:install) { gem_helper.install_gem } + require "rubocop/rake_task" RuboCop::RakeTask.new diff --git a/rakelib/release.rake b/rakelib/release.rake new file mode 100644 index 0000000..af6d757 --- /dev/null +++ b/rakelib/release.rake @@ -0,0 +1,137 @@ +# frozen_string_literal: true + +require "json" +require "net/http" +require "open3" +require_relative "release_tools" + +module ReleaseTasks + VERSION_FILE = "lib/drip/version.rb" + CHANGELOG = "CHANGELOG.md" + RUBYGEMS_VERSIONS = URI("https://rubygems.org/api/v1/versions/drip-ruby.json") + +module_function + + def capture(*command) + out, err, status = Open3.capture3(*command) + raise ReleaseTools::Error, "#{command.join(' ')} failed: #{err.strip}" unless status.success? + + out.strip + rescue SystemCallError => e + raise ReleaseTools::Error, "#{command.first}: #{e.message}" + end + + def git(*) = capture("git", *) + def fetch = git("fetch", "--quiet", "--tags", "origin") + def branch = git("rev-parse", "--abbrev-ref", "HEAD") + def clean? = git("status", "--porcelain").empty? + def tags = git("tag", "--list", "v*").lines(chomp: true) + + def published_versions + response = Net::HTTP.get_response(RUBYGEMS_VERSIONS) + return [] if response.is_a?(Net::HTTPNotFound) + raise ReleaseTools::Error, "RubyGems lookup failed: HTTP #{response.code}" unless response.is_a?(Net::HTTPSuccess) + + JSON.parse(response.body).map { |entry| entry.fetch("number") } + end + + def ci_conclusion(sha) + capture("gh", "run", "list", "--workflow", "ci.yml", "--commit", sha, "--event", "push", + "--json", "conclusion", "--jq", '.[0].conclusion // ""') + end + + def current_version = ReleaseTools::Version.new(string: ReleaseTools.version_from_source(File.read(VERSION_FILE))) + + def abort_on(problems) + abort(["Release checks failed:", *problems.map { |problem| " - #{problem}" }].join("\n")) if problems.any? + end + + def run + yield + rescue ReleaseTools::Error => e + abort(e.message) + end +end + +namespace :release do + desc "Set Drip::VERSION to VERSION and roll CHANGELOG.md, on a branch off an up-to-date main" + task :prepare, [:version] do |_task, args| + ReleaseTasks.run do + ReleaseTasks.fetch + ReleaseTasks.abort_on(ReleaseTools::Checks.prepare_problems(ReleaseTools::Checks::PrepareFacts.new( + version: args[:version].to_s, + branch: ReleaseTasks.branch, + clean: ReleaseTasks.clean?, + based_on_origin_main: system("git", "merge-base", "--is-ancestor", "origin/main", "HEAD"), + tags: ReleaseTasks.tags, + changelog: File.read(ReleaseTasks::CHANGELOG) + ))) + + version = ReleaseTools::Version.new(string: args[:version]) + File.write(ReleaseTasks::VERSION_FILE, ReleaseTools.with_version(File.read(ReleaseTasks::VERSION_FILE), version)) + unless version.prerelease? + changelog = ReleaseTools::Changelog.release(File.read(ReleaseTasks::CHANGELOG), version, Date.today) + File.write(ReleaseTasks::CHANGELOG, changelog) + end + + sh "bundle", "exec", "rake" + sh "git", "--no-pager", "diff", "--stat" + puts <<~NEXT + + Prepared #{version.tag}. Next: + git commit -am "Release #{version.tag}" + push the branch, open a PR, and merge it after review + then, on an up-to-date main: bundle exec rake release:tag + NEXT + end + end + + desc "Check that main is releasable, then create and push the v tag" + task :tag do + ReleaseTasks.run do + ReleaseTasks.fetch + head = ReleaseTasks.git("rev-parse", "HEAD") + changelog = File.read(ReleaseTasks::CHANGELOG) + ReleaseTasks.abort_on(ReleaseTools::Checks.tag_problems(ReleaseTools::Checks::TagFacts.new( + branch: ReleaseTasks.branch, + clean: ReleaseTasks.clean?, + head:, + origin_main: ReleaseTasks.git("rev-parse", "origin/main"), + version_source: File.read(ReleaseTasks::VERSION_FILE), + tags: ReleaseTasks.tags, + published_versions: ReleaseTasks.published_versions, + changelog:, + today: Date.today, + ci_conclusion: ReleaseTasks.ci_conclusion(head) + ))) + + version = ReleaseTasks.current_version + puts "Release notes for #{version.tag}:\n\n#{ReleaseTools::Changelog.notes(changelog, version)}" + print "Type #{version.tag} to create and push the tag: " + abort("Not tagged.") unless $stdin.gets.to_s.strip == version.tag + + sh "git", "tag", "-a", version.tag, "-m", version.tag + sh "git", "push", "origin", version.tag + puts <<~NEXT + + Pushed #{version.tag}. Watch the release: + gh run watch "$(gh run list --workflow release.yml --event push --limit 1 --json databaseId --jq '.[0].databaseId')" + NEXT + end + end + + desc "Print the release notes for VERSION (default: Drip::VERSION)" + task :notes, [:version] do |_task, args| + ReleaseTasks.run do + version = args[:version] ? ReleaseTools::Version.new(string: args[:version]) : ReleaseTasks.current_version + $stdout.write(ReleaseTools::Changelog.notes(File.read(ReleaseTasks::CHANGELOG), version)) + end + end + + desc "Print release metadata as GitHub Actions outputs, checking TAG against Drip::VERSION when given" + task :metadata, [:tag] do |_task, args| + ReleaseTasks.run do + ReleaseTools.metadata(File.read(ReleaseTasks::VERSION_FILE), args[:tag]).each { |key, value| puts "#{key}=#{value}" } + end + end +end diff --git a/rakelib/release_tools.rb b/rakelib/release_tools.rb new file mode 100644 index 0000000..1bc2a21 --- /dev/null +++ b/rakelib/release_tools.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +require_relative "release_tools/version" +require_relative "release_tools/changelog" +require_relative "release_tools/checks" + +module ReleaseTools + class Error < StandardError; end + + VERSION_CONSTANT = /VERSION = "([^"]*)"/ + +module_function + + def version_from_source(source) + source[VERSION_CONSTANT, 1] or raise Error, "no VERSION constant found" + end + + def with_version(source, version) + raise Error, "no VERSION constant found" unless source.match?(VERSION_CONSTANT) + + source.sub(VERSION_CONSTANT, %(VERSION = "#{version}")) + end + + def latest_version(tags) = tags.filter_map { |tag| Version.from_tag(tag) }.max + + def metadata(version_source, tag) + version = Version.new(string: version_from_source(version_source)) + raise Error, "tag #{tag} does not match Drip::VERSION #{version.tag}" unless tag.nil? || tag == version.tag + + { "version" => version.to_s, "tag" => version.tag, "prerelease" => version.prerelease?.to_s } + end +end diff --git a/rakelib/release_tools/changelog.rb b/rakelib/release_tools/changelog.rb new file mode 100644 index 0000000..7827160 --- /dev/null +++ b/rakelib/release_tools/changelog.rb @@ -0,0 +1,94 @@ +# frozen_string_literal: true + +require "date" + +module ReleaseTools + module Changelog + HEADING = /\A## \[([^\]]+)\](?: - (\d{4}-\d{2}-\d{2}))?\s*\z/ + UNRELEASED = "Unreleased" + COMPARE_URL = "https://github.com/DripEmail/drip-ruby/compare" + PREVIOUS_TAG = %r{\A#{Regexp.escape(COMPARE_URL)}/(v\S+)\.\.\.HEAD\z} + + Section = Data.define(:label, :date, :link, :body, :raw) + Document = Data.define(:preamble, :sections) + + module_function + + def parse(text) + preamble = text[/\A.*?(?=^## \[|\z)/m] + sections = text.delete_prefix(preamble).split(/^(?=## \[)/).map { |chunk| parse_section(chunk) } + Document.new(preamble:, sections:) + end + + def render(document) = document.preamble + document.sections.map(&:raw).join + + def parse_section(raw) + heading, *rest = raw.lines + label, date = parse_heading(heading) + pattern = link_pattern(label) + link = rest.filter_map { |line| line[pattern, 1] }.first + Section.new(label:, date:, link:, body: rest.grep_v(pattern).join.strip, raw:) + end + + def parse_heading(heading) + label, date = heading.match(HEADING)&.captures + raise Error, "malformed CHANGELOG.md heading #{heading.strip.inspect}" unless label + + [label, date && Date.iso8601(date)] + end + + def link_pattern(label) = /\A\[#{Regexp.escape(label)}\]: (\S+)\s*\z/ + + def build_section(label, date, link, body) + heading = date ? "## [#{label}] - #{date.iso8601}" : "## [#{label}]" + parse_section("#{[heading, "[#{label}]: #{link}", body].reject(&:empty?).join("\n\n")}\n\n") + end + + def compare(from, to) = "#{COMPARE_URL}/#{from}...#{to}" + + def find(document, label) = document.sections.find { |section| section.label == label } + + def unreleased(document) + find(document, UNRELEASED) or raise Error, "CHANGELOG.md has no [#{UNRELEASED}] section" + end + + def previous_tag(document) + unreleased(document).link.to_s[PREVIOUS_TAG, 1] or + raise Error, "[#{UNRELEASED}] link must be #{compare('', 'HEAD')}" + end + + def nonempty(section) + raise Error, "CHANGELOG.md section [#{section.label}] is empty" if section.body.empty? + + section + end + + def release(text, version, date) + raise Error, "prereleases do not get a CHANGELOG.md section" if version.prerelease? + + document = parse(text) + current = nonempty(unreleased(document)) + released = released_sections(document, version, date) + render(document.with(sections: document.sections.flat_map { |section| section.equal?(current) ? released : [section] })) + end + + def released_sections(document, version, date) + [ + build_section(UNRELEASED, nil, compare(version.tag, "HEAD"), ""), + build_section(version.to_s, date, compare(previous_tag(document), version.tag), unreleased(document).body) + ] + end + + def notes_section(document, version) + section = version.prerelease? ? unreleased(document) : find(document, version.to_s) + section or raise Error, "CHANGELOG.md has no section for #{version}" + end + + def notes(text, version) + section = nonempty(notes_section(parse(text), version)) + raise Error, "CHANGELOG.md section [#{section.label}] has no compare link" unless section.link + + "#{section.body}\n\n**Full diff**: #{section.link.sub(/HEAD\z/, version.tag)}\n" + end + end +end diff --git a/rakelib/release_tools/checks.rb b/rakelib/release_tools/checks.rb new file mode 100644 index 0000000..e2bf9e4 --- /dev/null +++ b/rakelib/release_tools/checks.rb @@ -0,0 +1,72 @@ +# frozen_string_literal: true + +module ReleaseTools + module Checks + PrepareFacts = Data.define(:version, :branch, :clean, :based_on_origin_main, :tags, :changelog) + TagFacts = Data.define(:branch, :clean, :head, :origin_main, :version_source, :tags, + :published_versions, :changelog, :today, :ci_conclusion) + + module_function + + def failures(*checks) = checks.filter_map { |failed, message| message if failed } + + def prepare_problems(facts) + failures( + [facts.branch == "main", "run on a release branch, not main"], + [!facts.clean, "working tree is not clean"], + [!facts.based_on_origin_main, "branch does not contain origin/main; rebase onto an up-to-date main"] + ) + version_problems(facts.version, facts.tags) + unreleased_problems(facts.changelog) + end + + def tag_problems(facts) + string = ReleaseTools.version_from_source(facts.version_source) + repository_problems(facts) + version_problems(string, facts.tags) + publication_problems(facts, string) + rescue Error => e + [e.message] + end + + def repository_problems(facts) + failures( + [facts.branch != "main", "run on main, not #{facts.branch}"], + [!facts.clean, "working tree is not clean"], + [facts.head != facts.origin_main, "HEAD is not origin/main; pull first"] + ) + end + + def publication_problems(facts, string) + ci = facts.ci_conclusion.to_s.empty? ? "missing" : facts.ci_conclusion + failures( + [facts.published_versions.include?(string), "drip-ruby #{string} is already on RubyGems"], + [ci != "success", "CI on HEAD is #{ci}, not success"] + ) + (Version.valid?(string) ? changelog_problems(facts.changelog, Version.new(string:), facts.today) : []) + end + + def version_problems(string, tags) + version = Version.new(string:) + latest = ReleaseTools.latest_version(tags) + failures( + [latest && version <= latest, "#{version} is not greater than the latest tag #{latest&.tag}"], + [tags.include?(version.tag), "tag #{version.tag} already exists"] + ) + rescue Error => e + [e.message] + end + + def unreleased_problems(text) + document = Changelog.parse(text) + Changelog.previous_tag(document) + Changelog.nonempty(Changelog.unreleased(document)) + [] + rescue Error => e + [e.message] + end + + def changelog_problems(text, version, today) + Changelog.notes(text, version) + date = Changelog.find(Changelog.parse(text), version.to_s)&.date + failures([date && date > today, "CHANGELOG.md date for #{version} is after today"]) + rescue Error => e + [e.message] + end + end +end diff --git a/rakelib/release_tools/version.rb b/rakelib/release_tools/version.rb new file mode 100644 index 0000000..a909819 --- /dev/null +++ b/rakelib/release_tools/version.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +require "rubygems" + +module ReleaseTools + VERSION_FORMAT = /\A\d+\.\d+\.\d+(?:\.(?:alpha|beta|rc)\d+)?\z/ + + Version = Data.define(:string) do + include Comparable + + def self.valid?(string) = VERSION_FORMAT.match?(string.to_s) + + def self.from_tag(tag) + string = tag.to_s.delete_prefix("v") + new(string:) if tag.to_s.start_with?("v") && valid?(string) + end + + def initialize(string:) + raise Error, "malformed version #{string.inspect}: expected X.Y.Z or X.Y.Z.(alpha|beta|rc)N" unless Version.valid?(string) + + super + end + + def <=>(other) = gem_version <=> other.gem_version + def gem_version = Gem::Version.new(string) + def prerelease? = gem_version.prerelease? + def tag = "v#{string}" + def to_s = string + end +end diff --git a/test/rakelib/release_tools_test.rb b/test/rakelib/release_tools_test.rb new file mode 100644 index 0000000..74b0fb6 --- /dev/null +++ b/test/rakelib/release_tools_test.rb @@ -0,0 +1,222 @@ +# frozen_string_literal: true + +require_relative '../test_helper' +require_relative '../../rakelib/release_tools' + +class ReleaseToolsTest < Drip::TestCase + CHANGELOG = <<~MD + # Changelog + Intro. + + ## [Unreleased] + + [Unreleased]: https://github.com/DripEmail/drip-ruby/compare/v3.5.0...HEAD + + ### Fixed + - A bug. + + ## [3.5.0] - 2026-07-10 + + [3.5.0]: https://github.com/DripEmail/drip-ruby/compare/v3.4.2...v3.5.0 + + ### Changed + - Things. + MD + + RELEASED = <<~MD + # Changelog + Intro. + + ## [Unreleased] + + [Unreleased]: https://github.com/DripEmail/drip-ruby/compare/v3.5.1...HEAD + + ## [3.5.1] - 2026-11-03 + + [3.5.1]: https://github.com/DripEmail/drip-ruby/compare/v3.5.0...v3.5.1 + + ### Fixed + - A bug. + + ## [3.5.0] - 2026-07-10 + + [3.5.0]: https://github.com/DripEmail/drip-ruby/compare/v3.4.2...v3.5.0 + + ### Changed + - Things. + MD + + EMPTY_UNRELEASED = CHANGELOG.sub("### Fixed\n- A bug.\n\n", "") + TODAY = Date.new(2026, 11, 3) + + def version(string) = ReleaseTools::Version.new(string:) + + def tag_facts(**overrides) + ReleaseTools::Checks::TagFacts.new(branch: "main", clean: true, head: "abc", origin_main: "abc", + version_source: %(VERSION = "3.5.0"\n), tags: %w[v3.4.2], + published_versions: %w[3.4.2], changelog: CHANGELOG, today: TODAY, ci_conclusion: "success", **overrides) + end + + def prepare_facts(**overrides) + ReleaseTools::Checks::PrepareFacts.new(version: "3.5.1", branch: "release-3.5.1", clean: true, based_on_origin_main: true, + tags: %w[v3.4.2 v3.5.0], changelog: CHANGELOG, **overrides) + end + + context "Version" do + should "accept final and prerelease versions" do + %w[3.5.1 10.0.0 3.5.1.rc1 3.5.1.alpha2 3.5.1.beta10].each { |string| assert ReleaseTools::Version.valid?(string) } + end + + should "reject other formats" do + ["3.5", "v3.5.1", "3.5.1-rc1", "3.5.1.rc", "3.5.1.pre1", "", nil].each do |string| + refute ReleaseTools::Version.valid?(string) + assert_raises(ReleaseTools::Error) { version(string) } + end + end + + should "order prereleases before the final release" do + assert_operator version("3.5.1.rc1"), :<, version("3.5.1") + assert_operator version("3.5.1.rc2"), :>, version("3.5.1.rc1") + assert_operator version("3.10.0"), :>, version("3.9.9") + end + + should "know whether it is a prerelease and its tag" do + assert version("3.5.1.rc1").prerelease? + refute version("3.5.1").prerelease? + assert_equal "v3.5.1", version("3.5.1").tag + end + + should "parse only well-formed v tags" do + assert_equal version("3.5.0"), ReleaseTools::Version.from_tag("v3.5.0") + assert_nil ReleaseTools::Version.from_tag("3.5.0") + assert_nil ReleaseTools::Version.from_tag("vnext") + end + end + + context "version source" do + should "read and replace the VERSION constant" do + source = %(module Drip\n VERSION = "3.5.0"\nend\n) + assert_equal "3.5.0", ReleaseTools.version_from_source(source) + assert_equal %(module Drip\n VERSION = "3.5.1"\nend\n), ReleaseTools.with_version(source, version("3.5.1")) + end + + should "fail without a VERSION constant" do + assert_raises(ReleaseTools::Error) { ReleaseTools.version_from_source("") } + assert_raises(ReleaseTools::Error) { ReleaseTools.with_version("", version("3.5.1")) } + end + end + + should "find the latest version among tags" do + assert_equal version("3.5.1.rc1"), ReleaseTools.latest_version(%w[v3.4.2 v3.5.1.rc1 v3.5.0 junk]) + assert_nil ReleaseTools.latest_version([]) + end + + context "metadata" do + should "describe Drip::VERSION" do + assert_equal({ "version" => "3.5.1.rc1", "tag" => "v3.5.1.rc1", "prerelease" => "true" }, + ReleaseTools.metadata(%(VERSION = "3.5.1.rc1"), nil)) + end + + should "accept a matching tag and reject a mismatched one" do + assert_equal "v3.5.1", ReleaseTools.metadata(%(VERSION = "3.5.1"), "v3.5.1")["tag"] + assert_raises(ReleaseTools::Error) { ReleaseTools.metadata(%(VERSION = "3.5.1"), "v3.5.2") } + end + end + + context "changelog" do + should "round-trip the repository CHANGELOG.md unchanged" do + text = File.read(File.expand_path("../../CHANGELOG.md", __dir__)) + assert_equal text, ReleaseTools::Changelog.render(ReleaseTools::Changelog.parse(text)) + end + + should "parse sections" do + unreleased, released = ReleaseTools::Changelog.parse(CHANGELOG).sections + assert_equal ["Unreleased", nil, "### Fixed\n- A bug."], [unreleased.label, unreleased.date, unreleased.body] + assert_equal ["3.5.0", Date.new(2026, 7, 10)], [released.label, released.date] + assert_equal "https://github.com/DripEmail/drip-ruby/compare/v3.4.2...v3.5.0", released.link + end + + should "reject malformed headings" do + assert_raises(ReleaseTools::Error) { ReleaseTools::Changelog.parse("## [3.5.0] on Tuesday\n") } + end + + should "move Unreleased entries under a dated release section" do + assert_equal RELEASED, ReleaseTools::Changelog.release(CHANGELOG, version("3.5.1"), TODAY) + end + + should "refuse to release an empty Unreleased section or a prerelease" do + assert_raises(ReleaseTools::Error) { ReleaseTools::Changelog.release(EMPTY_UNRELEASED, version("3.5.1"), TODAY) } + assert_raises(ReleaseTools::Error) { ReleaseTools::Changelog.release(CHANGELOG, version("3.5.1.rc1"), TODAY) } + end + + should "require an Unreleased compare link against the previous tag" do + broken = CHANGELOG.sub("compare/v3.5.0...HEAD", "compare/main") + assert_raises(ReleaseTools::Error) { ReleaseTools::Changelog.release(broken, version("3.5.1"), TODAY) } + end + end + + context "notes" do + should "render a final release section with a visible compare link" do + expected = "### Fixed\n- A bug.\n\n**Full diff**: https://github.com/DripEmail/drip-ruby/compare/v3.5.0...v3.5.1\n" + assert_equal expected, ReleaseTools::Changelog.notes(RELEASED, version("3.5.1")) + end + + should "render a prerelease from Unreleased, comparing up to its tag" do + expected = "### Fixed\n- A bug.\n\n**Full diff**: https://github.com/DripEmail/drip-ruby/compare/v3.5.0...v3.5.1.rc1\n" + assert_equal expected, ReleaseTools::Changelog.notes(CHANGELOG, version("3.5.1.rc1")) + end + + should "fail for a missing or empty section" do + assert_raises(ReleaseTools::Error) { ReleaseTools::Changelog.notes(CHANGELOG, version("3.6.0")) } + assert_raises(ReleaseTools::Error) { ReleaseTools::Changelog.notes(EMPTY_UNRELEASED, version("3.5.1.rc1")) } + end + end + + context "prepare_problems" do + should "pass for a valid release branch" do + assert_empty ReleaseTools::Checks.prepare_problems(prepare_facts) + assert_empty ReleaseTools::Checks.prepare_problems(prepare_facts(version: "3.5.1.rc1")) + end + + should "report every failed check" do + problems = ReleaseTools::Checks.prepare_problems(prepare_facts( + version: "3.5.0", branch: "main", clean: false, based_on_origin_main: false, changelog: EMPTY_UNRELEASED + )) + assert_equal 6, problems.size, problems.inspect + end + + should "report a malformed version" do + assert_match(/malformed version/, ReleaseTools::Checks.prepare_problems(prepare_facts(version: "")).join) + end + end + + context "tag_problems" do + should "pass for a releasable main" do + assert_empty ReleaseTools::Checks.tag_problems(tag_facts) + end + + should "report every failed check" do + problems = ReleaseTools::Checks.tag_problems(tag_facts( + branch: "topic", clean: false, origin_main: "def", tags: %w[v3.5.0], + published_versions: %w[3.5.0], ci_conclusion: "" + )) + assert_equal 7, problems.size, problems.inspect + assert_includes problems, "CI on HEAD is missing, not success" + end + + should "report a release section dated after today" do + assert_equal ["CHANGELOG.md date for 3.5.0 is after today"], + ReleaseTools::Checks.tag_problems(tag_facts(today: Date.new(2026, 7, 9))) + end + + should "report a version with no CHANGELOG.md section" do + assert_equal ["CHANGELOG.md has no section for 3.5.1"], + ReleaseTools::Checks.tag_problems(tag_facts(version_source: %(VERSION = "3.5.1"\n))) + end + + should "report a malformed or missing version" do + assert_match(/malformed version/, ReleaseTools::Checks.tag_problems(tag_facts(version_source: %(VERSION = "next"))).join) + assert_equal ["no VERSION constant found"], ReleaseTools::Checks.tag_problems(tag_facts(version_source: "")) + end + end +end