From b5d06bf17deee1799b4867e2fdadb14c9290c6dc Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 12 Nov 2026 22:06:13 +0000 Subject: [PATCH 1/7] Make a RubyGems release a single pull request merge. Prepare release opens release/X.Y.Z, Push Gem checks it, and merging publishes the gem and tags vX.Y.Z. Co-authored-by: ProxyMesh AI --- .cursor/skills/release/SKILL.md | 102 ++-- .github/scripts/release.rb | 438 ++++++++++++++++++ ...github_release_on_release_branch_merge.yml | 55 --- .github/workflows/prepare-release.yml | 91 ++++ .github/workflows/push_gem.yml | 170 ++++--- README.md | 1 + RELEASING.md | 48 ++ 7 files changed, 715 insertions(+), 190 deletions(-) create mode 100644 .github/scripts/release.rb delete mode 100644 .github/workflows/github_release_on_release_branch_merge.yml create mode 100644 .github/workflows/prepare-release.yml create mode 100644 RELEASING.md diff --git a/.cursor/skills/release/SKILL.md b/.cursor/skills/release/SKILL.md index fa2f678..f7a066a 100644 --- a/.cursor/skills/release/SKILL.md +++ b/.cursor/skills/release/SKILL.md @@ -1,97 +1,49 @@ --- name: release description: >- - Bumps RubyProxyHeaders::VERSION in lib/ruby_proxy_headers/version.rb, opens a PR from - branch release/VERSION toward main with auto-merge, and coordinates with CI that - publishes a GitHub Release when that branch merges. Use when the user invokes /release, - /release VERSION, asks for a release PR, version bump, or release automation. + Cuts a ruby-proxy-headers release from RELEASING.md. Prepare release opens a + pull request from release/X.Y.Z; merging it publishes the gem and tags vX.Y.Z. + Use when the user invokes /release, /release VERSION, or asks for a release PR. --- -# Release (`/release` and optional VERSION) +# Release -## When this applies +Follow `RELEASING.md` at the repository root. Do not publish, tag, or merge the release pull request. Do not enable auto-merge. -- User message starts with **`/release`** or **`/release VERSION`** (VERSION optional). -- User asks to cut a release, bump the gem version, or open a release PR with auto-merge. +## Version -## Preconditions +Read `RubyProxyHeaders::VERSION` from `lib/ruby_proxy_headers/version.rb`. -- Working tree clean (`git status`); stash or commit unrelated work first. -- `gh` CLI authenticated (`gh auth status`). -- Remote `origin` is GitHub. -- Repository allows **auto-merge** (Settings → General → Pull Requests → Allow auto-merge). If auto-merge is unavailable, open the PR anyway and tell the user to merge manually after checks pass. +| Input | Spec | +| --- | --- | +| `/release` | `patch` | +| `/release 1.4.0` | `1.4.0` | -## Version selection +The version must be `MAJOR.MINOR.PATCH`. -1. Read the current version from `lib/ruby_proxy_headers/version.rb` (`RubyProxyHeaders::VERSION`, semver `MAJOR.MINOR.PATCH`). -2. If **VERSION was provided**: set the new version to that string (must match `^\d+\.\d+\.\d+` unless the project already uses a different scheme—then follow the existing file format). -3. If **VERSION was omitted**: bump the **patch** segment only (e.g. `0.2.1` → `0.2.2`). If the current value is not `x.y.z`, stop and ask the user for an explicit VERSION. +## Preferred path -## Git identity (this repo) - -Configure once if needed: +From latest `origin/main`: ```bash -git config user.email "cursor@proxymesh.com" -git config user.name "Cursor" +gh workflow run "Prepare release" --ref main -f version=SPEC ``` -## Steps - -1. **Sync main** - - ```bash - git fetch origin main - ``` - -2. **Compute** `NEW_VERSION` (per rules above). **Branch name** is `release/${NEW_VERSION}` (no `v` prefix in the branch name). - -3. **Create branch from latest main** - - ```bash - git checkout -B "release/${NEW_VERSION}" origin/main - ``` - -4. **Edit** `lib/ruby_proxy_headers/version.rb`: set `VERSION = 'NEW_VERSION'` (single-quoted string). - -5. **Refresh** `Gemfile.lock` so the path gem entry matches (CI uses frozen Bundler and fails if the gemspec version changed without a lock update): +Wait until that run opens the pull request titled `Release X.Y.Z`. - ```bash - bundle lock - # If Ruby/Bundler is unavailable, update both `ruby-proxy-headers (OLD)` lines in Gemfile.lock to NEW_VERSION. - ``` +## Manual path -6. **Commit and push** (never push to `main`; push only the release branch) +Use this when the workflow cannot be started. Branch `release/X.Y.Z` from latest `origin/main` and make the same edits Prepare release makes: - ```bash - git add lib/ruby_proxy_headers/version.rb Gemfile.lock - git commit -m "chore: bump version to ${NEW_VERSION}" - git push -u origin "release/${NEW_VERSION}" - ``` +- `lib/ruby_proxy_headers/version.rb`, `VERSION = 'X.Y.Z'` +- every `ruby-proxy-headers (X.Y.Z)` entry in `Gemfile.lock` +- move `## [Unreleased]` in `CHANGELOG.md` to `## [X.Y.Z] - YYYY-MM-DD`, and update the compare links -7. **Open PR** into `main` with a short body (no Cursor boilerplate). Example: +Commit, push `release/X.Y.Z`, and open a pull request into `main` titled `Release X.Y.Z` whose body is that changelog section. - ```bash - gh pr create --base main --head "release/${NEW_VERSION}" \ - --title "Release ${NEW_VERSION}" \ - --body "Bumps the gem version to ${NEW_VERSION} for release." - ``` +Git identity for commits in this repo: -8. **Enable auto-merge** after the PR exists. In non-interactive mode, `gh` requires an explicit merge strategy with `--auto` (use the repository default: usually **`--merge`** for a merge commit, or **`--squash`** / **`--rebase`** if that is what the repo uses). - - ```bash - gh pr merge --auto --merge - ``` - - If `--auto` fails (permissions, auto-merge disabled, or pending checks), leave the PR open and report the error; the user can merge manually after CI passes. You can poll with `gh pr checks --watch` then retry `gh pr merge ... --auto --merge`, or merge manually. - -## After merge - -Merging the PR into `main` runs **Release on merge** (`.github/workflows/github_release_on_release_branch_merge.yml`), which creates a **GitHub Release** for tag `v{version}` from the merge commit. Because releases created with the default `GITHUB_TOKEN` do not trigger other workflows, **Push Gem** (`push_gem.yml`) is also started via **`workflow_run`** when that release workflow finishes. Manual or API-created releases still match the `release: published` trigger on `push_gem.yml`. - -## Quick reference - -| Input | Result | -|--------------------|---------------------------------------------| -| `/release` | Patch bump, branch `release/x.y.(z+1)` | -| `/release 1.4.0` | Version `1.4.0`, branch `release/1.4.0` | +```bash +git config user.email "cursor@proxymesh.com" +git config user.name "Cursor" +``` diff --git a/.github/scripts/release.rb b/.github/scripts/release.rb new file mode 100644 index 0000000..65c1662 --- /dev/null +++ b/.github/scripts/release.rb @@ -0,0 +1,438 @@ +# frozen_string_literal: true + +require 'date' +require 'English' +require 'json' +require 'net/http' +require 'open3' +require 'rubygems/package' +require 'tmpdir' + +# Prepares a release checkout and checks the version manifests. +# One script, so it is longer than RuboCop's library module limit. +# rubocop:disable Metrics/ModuleLength +module GemRelease + SEMVER = '(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)' + VERSION_RE = Regexp.new("\\A#{SEMVER}\\z").freeze + RELEASE_REF_RE = Regexp.new("\\Arelease/#{SEMVER}\\z").freeze + TAG_RE = Regexp.new("\\Av#{SEMVER}\\z").freeze + REPO_RE = %r{\A[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+\z} + VERSION_FILE = 'lib/ruby_proxy_headers/version.rb' + GEM_NAME = 'ruby-proxy-headers' + + class Error < StandardError + end + + USAGE = 'usage: release.rb version|bump|check|check-branch|notes|gate|plan|push-gem|github-release' + + COMMANDS = { + 'version' => ->(*) { puts read_version }, + 'bump' => ->(argv) { bump(argv[1]) }, + 'check' => ->(argv) { run_check(argv.drop(1)) }, + 'check-branch' => ->(*) { check_branch }, + 'notes' => ->(argv) { print changelog_notes(required_version(argv[1])) }, + 'gate' => ->(*) { gate }, + 'plan' => ->(*) { plan }, + 'push-gem' => ->(*) { push_gem }, + 'github-release' => ->(*) { github_release } + }.freeze + + def self.run(argv) + command = COMMANDS[argv.first] + return command.call(argv) if command + + warn USAGE + exit 1 + rescue Error => e + warn e.message + exit 1 + end + + def self.read_version + match = File.read(VERSION_FILE).match(/^\s*VERSION = ['"]([^'"]+)['"]/) + version = match && match[1] + raise Error, "#{VERSION_FILE} has no MAJOR.MINOR.PATCH VERSION" unless version&.match?(VERSION_RE) + + version + end + + def self.bump(spec) + spec = spec.to_s.strip + current = read_version + version = bump_number(current, spec).join('.') + write_version(version) + write_lock(current, version) + write_changelog(current, version, Time.now.utc.strftime('%Y-%m-%d')) + warn "Release #{version}" + emit('version', version) + end + + def self.run_check(argv) + options = { expected: nil, require_changelog: false, gem_path: nil } + parse_check_arg(options, argv) until argv.empty? + check(**options) + end + + def self.parse_check_arg(options, argv) + arg = argv.shift + case arg + when '--version' then options[:expected] = required_version(argv.shift) + when '--require-changelog' then options[:require_changelog] = true + when '--gem' then options[:gem_path] = argv.shift + else raise Error, "unknown argument #{arg}" + end + raise Error, '--gem needs a path' if arg == '--gem' && options[:gem_path].to_s.empty? + end + + def self.check(expected: nil, require_changelog: false, gem_path: nil) + version = read_version + assert_lock(version) + raise Error, "version is #{version}, expected #{expected}" if expected && expected != version + + assert_changelog(version) if require_changelog + assert_gem(version, gem_path) if gem_path + end + + def self.check_branch + return unless ENV.fetch('GITHUB_EVENT_NAME') == 'pull_request' + + ref = ENV.fetch('GITHUB_HEAD_REF', '') + return unless ref.start_with?('release/') + + match = ref.match(RELEASE_REF_RE) + raise Error, 'release branch must be release/X.Y.Z' unless match + + check(expected: version_from(match), require_changelog: true) + end + + def self.gate + case ENV.fetch('GITHUB_EVENT_NAME') + when 'push' then gate_push + when 'release' then gate_tag + else raise Error, "unexpected event #{ENV.fetch('GITHUB_EVENT_NAME')}" + end + end + + def self.plan + action, create, message = plan_action(plan_state) + warn message if message + emit('action', action) + emit('create_release', create ? 'true' : 'false') + end + + def self.plan_state + version = required_version(ENV.fetch('VERSION')) + tag = "v#{version}" + { + mode: ENV.fetch('MODE'), + version: version, + gem_exists: gem_published?(version), + release_exists: release_exists?(tag), + tag_sha: tag_commit(tag), + head_sha: ENV.fetch('TARGET_SHA') + } + end + + def self.push_gem + version = required_version(ENV.fetch('VERSION')) + path = "#{GEM_NAME}-#{version}.gem" + raise Error, "#{path} was not built" unless File.file?(path) + + stdout, stderr, status = Open3.capture3('gem', 'push', path) + return if status.success? + return if "#{stdout}\n#{stderr}".match?(/already exists|Repushing|same version/i) + + warn stdout + warn stderr + raise Error, "gem push failed for #{version}" + end + + def self.github_release + version = required_version(ENV.fetch('VERSION')) + tag = "v#{version}" + return warn("GitHub Release #{tag} already exists.") if release_exists?(tag) + + notes = File.join(Dir.tmpdir, 'release-notes.md') + File.write(notes, release_notes(version)) + create_release(tag, notes) + end + + def self.create_release(tag, notes) + _stdout, stderr, status = Open3.capture3( + 'gh', 'release', 'create', tag, '--repo', repository, + '--target', ENV.fetch('TARGET_SHA'), '--title', tag, '--notes-file', notes + ) + return if status.success? + + warn stderr + raise Error, "could not create GitHub Release #{tag}" + end + + def self.changelog_notes(version) + lines = File.readlines('CHANGELOG.md') + start = lines.index { |line| dated_heading?(line, version) } + raise Error, "CHANGELOG.md has no dated #{version} section" unless start + + rest = lines[(start + 1)..] || [] + stop = rest.index { |line| section_boundary?(line) } + body = stop ? rest[0...stop] : rest + "#{([lines[start]] + body).join.strip}\n" + end + + def self.plan_action(state) + same = !state[:tag_sha].empty? && state[:tag_sha] == state[:head_sha] + return gem_already_published(state, same) if state[:gem_exists] + raise Error, "GitHub Release v#{state[:version]} does not point at this commit" if misplaced_release?(state, same) + + ['push', state[:mode] == 'release', nil] + end + + def self.misplaced_release?(state, same) + state[:mode] == 'release' && state[:release_exists] && !same && !state[:tag_sha].empty? + end + + def self.gem_already_published(state, same) + version = state[:version] + done = ['already_done', false, "#{version} is already published for this commit"] + return done if state[:release_exists] && same + + if !state[:tag_sha].empty? && !same + raise Error, "#{version} is already on RubyGems at #{state[:tag_sha]}. Refusing to push it again." + end + + return ['release_only', true, nil] if state[:mode] == 'release' + + raise Error, "#{version} is already on RubyGems. Refusing to push it again." + end + + def self.bump_number(current, spec) + major, minor, patch = current.split('.').map(&:to_i) + case spec + when 'patch' then [major, minor, patch + 1] + when 'minor' then [major, minor + 1, 0] + when 'major' then [major + 1, 0, 0] + else + raise Error, "#{spec} is not a newer X.Y.Z, patch, minor, or major" unless newer?(spec, current) + + spec.split('.').map(&:to_i) + end + end + + def self.newer?(spec, current) + return false unless spec.match?(VERSION_RE) + + (spec.split('.').map(&:to_i) <=> current.split('.').map(&:to_i)) == 1 + end + + def self.write_version(version) + updated = File.read(VERSION_FILE).sub(/^(\s*VERSION = )['"][^'"]*['"]/, "\\1'#{version}'") + raise Error, "could not update #{VERSION_FILE}" if updated == File.read(VERSION_FILE) + + File.write(VERSION_FILE, updated) + end + + def self.write_lock(old_version, new_version) + count = 0 + pattern = /^(\s*#{GEM_NAME} \()#{Regexp.escape(old_version)}(\).*)$/ + updated = File.read('Gemfile.lock').gsub(pattern) do + count += 1 + "#{Regexp.last_match(1)}#{new_version}#{Regexp.last_match(2)}" + end + raise Error, 'Gemfile.lock has no ruby-proxy-headers version to update' if count.zero? + + File.write('Gemfile.lock', updated) + end + + def self.write_changelog(old_version, version, date) + lines, start, finish = split_unreleased(File.read('CHANGELOG.md')) + text = replace_unreleased(lines, start, finish, version, date) + File.write('CHANGELOG.md', rewrite_links(text, old_version, version)) + end + + def self.split_unreleased(text) + lines = text.lines + start = lines.index { |line| line.strip == '## [Unreleased]' } + raise Error, 'CHANGELOG.md has no ## [Unreleased] section' unless start + + offset = lines[(start + 1)..].index { |line| section_boundary?(line) } + finish = offset ? start + 1 + offset : lines.size + [lines, start, finish] + end + + def self.replace_unreleased(lines, start, finish, version, date) + body = lines[(start + 1)...finish].join.strip + section = "## [Unreleased]\n\n## [#{version}] - #{date}\n" + section += "\n#{body}\n" unless body.empty? + lines[start...finish] = ["#{section}\n"] + lines.join + end + + def self.rewrite_links(text, old_version, version) + lines = text.lines + replace_link(lines, '[Unreleased]:', "[Unreleased]: https://github.com/#{repository}/compare/v#{version}...HEAD\n") + place_version_link(lines, version, old_version) + lines.join + end + + def self.replace_link(lines, prefix, replacement) + index = lines.index { |line| line.start_with?(prefix) } + index ? lines[index] = replacement : lines << replacement + end + + def self.place_version_link(lines, version, old_version) + prefix = "[#{version}]:" + replacement = "#{prefix} https://github.com/#{repository}/compare/v#{old_version}...v#{version}\n" + index = lines.index { |line| line.start_with?(prefix) } + return lines[index] = replacement if index + + after = lines.index { |line| line.start_with?('[Unreleased]:') } + after ? lines.insert(after + 1, replacement) : lines << replacement + end + + def self.gate_push + event = JSON.parse(File.read(ENV.fetch('GITHUB_EVENT_PATH'))) + sha = ENV.fetch('GITHUB_SHA') + version = choose_release(pulls(sha), event.dig('head_commit', 'message').to_s) + emit('publish', version ? 'true' : 'false') + return unless version + + emit('version', version) + emit('sha', sha) + emit('mode', 'release') + end + + def self.gate_tag + match = ENV.fetch('GITHUB_REF_NAME').match(TAG_RE) + raise Error, 'release tag must be vX.Y.Z' unless match + + emit('publish', 'true') + emit('version', version_from(match)) + emit('sha', ENV.fetch('GITHUB_SHA')) + emit('mode', 'gem') + end + + def self.choose_release(pulls, message) + versions = pulls.filter_map { |pull| release_version(pull) } + raise Error, "commit is in more than one release pull request: #{versions.join(', ')}" if versions.size > 1 + return versions.first if versions.any? + + return nil unless release_message?(message) + + raise Error, 'commit looks like a release merge, but no release pull request is attached to it' + end + + def self.release_version(pull) + return unless pull['merged_at'] || pull['merged'] == true + return unless pull.dig('base', 'ref') == 'main' + + match = pull.dig('head', 'ref').to_s.match(RELEASE_REF_RE) + version_from(match) if match + end + + def self.release_message?(text) + text.match?(%r{from \S+/release/#{SEMVER}}) || text.match?(/\ARelease #{SEMVER}\b/) + end + + def self.pulls(sha) + stdout, status = Open3.capture2('gh', 'api', "repos/#{repository}/commits/#{sha}/pulls") + raise Error, 'could not list pull requests for this commit' unless status.success? + + parsed = JSON.parse(stdout) + raise Error, 'could not list pull requests for this commit' unless parsed.is_a?(Array) + + parsed + end + + def self.gem_published?(version) + uri = URI("https://rubygems.org/api/v2/rubygems/#{GEM_NAME}/versions/#{version}.json") + response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 15, read_timeout: 30) do |http| + http.get(uri.request_uri) + end + return true if response.code == '200' + return false if response.code == '404' + + raise Error, "RubyGems returned HTTP #{response.code} for #{version}" + end + + def self.tag_commit(tag) + stdout, status = Open3.capture2('git', 'rev-parse', '--verify', "#{tag}^{commit}") + status.success? ? stdout.strip : '' + end + + def self.release_exists?(tag) + _stdout, status = Open3.capture2('gh', 'release', 'view', tag, '--repo', repository) + status.success? + end + + def self.release_notes(version) + return changelog_notes(version) if File.readlines('CHANGELOG.md').any? { |line| dated_heading?(line, version) } + + "Release #{version}.\n" + end + + def self.assert_lock(version) + found = File.readlines('Gemfile.lock').filter_map { |line| line[/^\s*#{GEM_NAME} \(([^)]+)\)/, 1] } + raise Error, 'Gemfile.lock has no ruby-proxy-headers version' if found.empty? + return if found.uniq == [version] + + raise Error, "Gemfile.lock has #{found.uniq.join(', ')}, #{VERSION_FILE} has #{version}" + end + + def self.assert_changelog(version) + return if File.readlines('CHANGELOG.md').any? { |line| dated_heading?(line, version) } + + raise Error, "CHANGELOG.md has no ## [#{version}] - YYYY-MM-DD section" + end + + def self.assert_gem(version, path) + expected = "#{GEM_NAME}-#{version}.gem" + raise Error, "#{File.basename(path)} is not #{expected}" unless File.basename(path) == expected + + built = Gem::Package.new(path).spec.version.to_s + return if built == version + + raise Error, "built gem is #{built}, expected #{version}" + end + + def self.dated_heading?(line, version) + match = line.strip.match(/\A## \[#{Regexp.escape(version)}\] - (\d{4}-\d{2}-\d{2})\z/) + return false unless match + + Date.iso8601(match[1]) + true + rescue ArgumentError + false + end + + def self.section_boundary?(line) + line.start_with?('## ') || line.match?(/\A\[[^\]]+\]:/) + end + + def self.required_version(value) + raise Error, 'version must be X.Y.Z' unless value.to_s.match?(VERSION_RE) + + value + end + + def self.version_from(match) + "#{match[1]}.#{match[2]}.#{match[3]}" + end + + def self.repository + repo = ENV['GITHUB_REPOSITORY'].to_s + return repo if repo.match?(REPO_RE) + + raise Error, 'GITHUB_REPOSITORY is not set' + end + + def self.emit(key, value) + puts "#{key}=#{value}" + path = ENV.fetch('GITHUB_OUTPUT', '') + return if path.empty? + + File.open(path, 'a') { |file| file.puts "#{key}=#{value}" } + end +end +# rubocop:enable Metrics/ModuleLength + +GemRelease.run(ARGV) if $PROGRAM_NAME == __FILE__ diff --git a/.github/workflows/github_release_on_release_branch_merge.yml b/.github/workflows/github_release_on_release_branch_merge.yml deleted file mode 100644 index 343eeff..0000000 --- a/.github/workflows/github_release_on_release_branch_merge.yml +++ /dev/null @@ -1,55 +0,0 @@ -# When a release/* PR merges into main, create a GitHub release (tag vX.Y.Z). -# Events from GITHUB_TOKEN do not start other workflows; push_gem.yml is triggered via -# workflow_run when this workflow completes (see push_gem.yml). - -name: Release on merge - -on: - pull_request: - types: [closed] - branches: - - main - -concurrency: - group: release-on-merge-${{ github.event.pull_request.number }} - cancel-in-progress: false - -permissions: - contents: write - -jobs: - github-release: - if: >- - github.event.pull_request.merged == true && - startsWith(github.head_ref, 'release/') && - github.event.pull_request.head.repo.full_name == github.repository - runs-on: ubuntu-24.04 - steps: - - name: Checkout merge commit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ github.event.pull_request.merge_commit_sha }} - - - name: Read version from lib/ruby_proxy_headers/version.rb - id: meta - run: | - VERSION=$(ruby -r ./lib/ruby_proxy_headers/version.rb -e 'puts RubyProxyHeaders::VERSION') - echo "version=${VERSION}" >> "${GITHUB_OUTPUT}" - - - name: Create GitHub Release - env: - GH_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - VERSION="${{ steps.meta.outputs.version }}" - TAG="v${VERSION}" - MERGE_SHA="${{ github.event.pull_request.merge_commit_sha }}" - if gh release view "${TAG}" --repo "${{ github.repository }}" >/dev/null 2>&1; then - echo "Release ${TAG} already exists; skipping." - exit 0 - fi - gh release create "${TAG}" \ - --repo "${{ github.repository }}" \ - --target "${MERGE_SHA}" \ - --title "${TAG}" \ - --generate-notes diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml new file mode 100644 index 0000000..ee47f78 --- /dev/null +++ b/.github/workflows/prepare-release.yml @@ -0,0 +1,91 @@ +# Opens a release/X.Y.Z pull request. Does not merge it. + +name: Prepare release + +on: + workflow_dispatch: + inputs: + version: + description: X.Y.Z, patch, minor, or major + required: true + type: string + +permissions: + contents: read + +concurrency: + group: prepare-release + cancel-in-progress: false + +jobs: + prepare: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: write + pull-requests: write + steps: + - name: Require main + run: | + set -euo pipefail + if [[ "${GITHUB_REF}" != "refs/heads/main" ]]; then + echo "Run Prepare release from main." >&2 + exit 1 + fi + + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: main + persist-credentials: true + + - name: Set up Ruby + uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199 # v1 + with: + bundler: none + ruby-version: ruby + + - name: Bump version and changelog + id: bump + env: + RELEASE_SPEC: ${{ inputs.version }} + run: ruby .github/scripts/release.rb bump "${RELEASE_SPEC}" + + - name: Push release branch + env: + VERSION: ${{ steps.bump.outputs.version }} + GIT_AUTHOR_NAME: github-actions[bot] + GIT_AUTHOR_EMAIL: 41898282+github-actions[bot]@users.noreply.github.com + GIT_COMMITTER_NAME: github-actions[bot] + GIT_COMMITTER_EMAIL: 41898282+github-actions[bot]@users.noreply.github.com + run: | + set -euo pipefail + branch="release/${VERSION}" + if git ls-remote --exit-code origin "refs/heads/${branch}" >/dev/null 2>&1; then + echo "Branch ${branch} already exists." >&2 + exit 1 + fi + git checkout -b "${branch}" + git add lib/ruby_proxy_headers/version.rb Gemfile.lock CHANGELOG.md + git commit -m "Release ${VERSION}" + git push origin "HEAD:${branch}" + + - name: Open pull request + env: + VERSION: ${{ steps.bump.outputs.version }} + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + branch="release/${VERSION}" + head="${GITHUB_REPOSITORY%%/*}:${branch}" + count="$(gh pr list --base main --head "${head}" --state open --json number --jq length)" + if [[ "${count}" != "0" ]]; then + echo "An open pull request for ${branch} already exists." >&2 + exit 1 + fi + ruby .github/scripts/release.rb notes "${VERSION}" > "${RUNNER_TEMP}/notes.md" + gh pr create \ + --base main \ + --head "${branch}" \ + --title "Release ${VERSION}" \ + --body-file "${RUNNER_TEMP}/notes.md" diff --git a/.github/workflows/push_gem.yml b/.github/workflows/push_gem.yml index dea7523..668c596 100644 --- a/.github/workflows/push_gem.yml +++ b/.github/workflows/push_gem.yml @@ -1,95 +1,145 @@ -# Trusted publishing to RubyGems.org (OIDC). Configure a pending publisher at: -# https://rubygems.org/profile/oidc/pending_trusted_publishers -# Workflow file name and repository must match RubyGems trusted publisher settings. -# See https://guides.rubygems.org/trusted-publishing/pushing-a-new-gem/ -# and https://guides.rubygems.org/trusted-publishing/releasing-gems/ +# The RubyGems trusted publisher is registered to this filename (push_gem.yml). +# Pull requests run the release check. Merging release/X.Y.Z publishes the gem, +# then tags vX.Y.Z and opens the GitHub Release. The publish job uses the +# GitHub environment "release". name: Push Gem on: + pull_request: + push: + branches: + - main release: types: [published] - workflow_dispatch: - - # GitHub does not start new workflow runs for events caused by the default - # GITHUB_TOKEN (e.g. gh release create in another workflow). After - # "Release on merge" creates a release, trigger this workflow instead. - workflow_run: - workflows: [Release on merge] - types: [completed] - permissions: contents: read jobs: + release-check: + if: github.event_name == 'pull_request' + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: read + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: actionlint + run: | + set -euo pipefail + archive="${RUNNER_TEMP}/actionlint.tar.gz" + curl -sSfL -o "${archive}" \ + https://github.com/rhysd/actionlint/releases/download/v1.7.12/actionlint_1.7.12_linux_amd64.tar.gz + echo "8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8 ${archive}" | sha256sum -c - + tar -xzf "${archive}" -C "${RUNNER_TEMP}" actionlint + "${RUNNER_TEMP}/actionlint" -color + + - name: Set up Ruby + uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199 # v1 + with: + bundler: none + ruby-version: ruby + + - name: Build gem + run: gem build ruby-proxy-headers.gemspec + + - name: Check version manifests and gem + run: | + set -euo pipefail + gems=(ruby-proxy-headers-*.gem) + ruby .github/scripts/release.rb check --gem "${gems[0]}" + + - name: Check release branch + run: ruby .github/scripts/release.rb check-branch + gate: + if: github.event_name != 'pull_request' runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + pull-requests: read outputs: publish: ${{ steps.decide.outputs.publish }} + version: ${{ steps.decide.outputs.version }} + sha: ${{ steps.decide.outputs.sha }} + mode: ${{ steps.decide.outputs.mode }} steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - if: github.event_name == 'workflow_run' + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - ref: main + ref: ${{ github.sha }} + persist-credentials: false - - id: decide + - name: Decide + id: decide env: GH_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - if [[ "${{ github.event_name }}" != "workflow_run" ]]; then - echo "publish=true" >> "${GITHUB_OUTPUT}" - exit 0 - fi - if [[ "${{ github.event.workflow_run.conclusion }}" != "success" ]]; then - echo "publish=false" >> "${GITHUB_OUTPUT}" - exit 0 - fi - VERSION="$(ruby -r ./lib/ruby_proxy_headers/version.rb -e 'puts RubyProxyHeaders::VERSION')" - TAG="v${VERSION}" - if gh release view "${TAG}" --repo "${{ github.repository }}" >/dev/null 2>&1; then - echo "publish=true" >> "${GITHUB_OUTPUT}" - else - echo "No GitHub release ${TAG} yet (or release job was skipped); skipping gem push." - echo "publish=false" >> "${GITHUB_OUTPUT}" - fi + run: ruby .github/scripts/release.rb gate - push: + publish: needs: gate if: >- - github.repository == 'proxymesh/ruby-proxy-headers' && - needs.gate.outputs.publish == 'true' + needs.gate.result == 'success' && + needs.gate.outputs.publish == 'true' && + github.repository == 'proxymesh/ruby-proxy-headers' runs-on: ubuntu-24.04 - + timeout-minutes: 20 + environment: release permissions: contents: write id-token: write - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - ref: ${{ github.event_name == 'workflow_run' && 'main' || github.ref }} + ref: ${{ needs.gate.outputs.sha }} + fetch-depth: 0 persist-credentials: false - - name: Verify release tag matches gem version - if: github.event_name == 'release' - env: - REF_NAME: ${{ github.ref_name }} - run: | - VERSION=$(ruby -r ./lib/ruby_proxy_headers/version.rb -e 'puts RubyProxyHeaders::VERSION') - if [ "v${VERSION}" != "${REF_NAME}" ]; then - echo "Release tag must be v${VERSION} (RubyProxyHeaders::VERSION); got ${REF_NAME}" >&2 - exit 1 - fi - - name: Set up Ruby - uses: ruby/setup-ruby@v1 # kept unpinned per maintainer guidance — pinning freezes available Ruby versions + uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199 # v1 with: - # workflow_run gets a read-only Actions cache token for the default branch - # (https://github.blog/changelog/2026-06-26-read-only-actions-cache-for-untrusted-triggers/), - # so saving the bundler cache would only warn. Keep caching for trusted triggers. - bundler-cache: ${{ github.event_name != 'workflow_run' }} + bundler: none ruby-version: ruby - - uses: rubygems/release-gem@7f9650160c1a4e7989fdc9855807bdbd421d8b6b # v1.4.1 + - name: Check version + env: + VERSION: ${{ needs.gate.outputs.version }} + run: ruby .github/scripts/release.rb check --version "${VERSION}" + + - name: Plan + id: plan + env: + VERSION: ${{ needs.gate.outputs.version }} + MODE: ${{ needs.gate.outputs.mode }} + TARGET_SHA: ${{ needs.gate.outputs.sha }} + GH_TOKEN: ${{ github.token }} + run: ruby .github/scripts/release.rb plan + + - name: Build gem + if: steps.plan.outputs.action == 'push' + run: gem build ruby-proxy-headers.gemspec + + - name: Configure RubyGems credentials + if: steps.plan.outputs.action == 'push' + uses: rubygems/configure-rubygems-credentials@dc5a8d8553e6ee01fc26761a49e99e733d17954a # v2.1.0 + + - name: Push gem + if: steps.plan.outputs.action == 'push' + env: + VERSION: ${{ needs.gate.outputs.version }} + run: ruby .github/scripts/release.rb push-gem + + - name: Create GitHub Release + if: steps.plan.outputs.create_release == 'true' + env: + VERSION: ${{ needs.gate.outputs.version }} + TARGET_SHA: ${{ needs.gate.outputs.sha }} + GH_TOKEN: ${{ github.token }} + run: ruby .github/scripts/release.rb github-release diff --git a/README.md b/README.md index 97cb3c6..a541478 100644 --- a/README.md +++ b/README.md @@ -132,3 +132,4 @@ bundle exec ruby test/test_proxy_headers.rb -v - [python-proxy-headers](https://github.com/proxymesh/python-proxy-headers) - [javascript-proxy-headers](https://github.com/proxymesh/javascript-proxy-headers) - [proxy-examples (Ruby)](https://github.com/proxymesh/proxy-examples/tree/main/ruby) +- [Releasing](RELEASING.md) diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 0000000..3806141 --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,48 @@ +# Releasing + +## Cut a release + +1. On GitHub, open **Actions** → **Prepare release** → **Run workflow** on `main`. +2. Set **version** to `X.Y.Z`, `patch`, `minor`, or `major`. +3. The workflow pushes `release/X.Y.Z` and opens a pull request titled `Release X.Y.Z`. The body is the changelog section. It does not auto-merge. +4. Wait until **Push Gem / release-check** is green, then merge the pull request. + +Opening the pull request by hand still works. From an up-to-date `main`, bump every version manifest, move `## [Unreleased]` in `CHANGELOG.md` to `## [X.Y.Z] - YYYY-MM-DD`, push `release/X.Y.Z`, and open a pull request titled `Release X.Y.Z` whose body is that changelog section. Do not auto-merge. + +Version manifests: + +- `lib/ruby_proxy_headers/version.rb` (`RubyProxyHeaders::VERSION`) +- `Gemfile.lock` (every `ruby-proxy-headers` version entry) + +`ruby-proxy-headers.gemspec` reads `RubyProxyHeaders::VERSION`. + +## What runs + +### Prepare + +`.github/workflows/prepare-release.yml` runs on `workflow_dispatch`. It bumps the manifests, moves the changelog section, and opens the pull request. + +### Validate + +`.github/workflows/push_gem.yml` runs **release-check** on pull requests. It runs actionlint, checks that `version.rb` and `Gemfile.lock` agree, and runs `gem build`. + +On a `release/X.Y.Z` pull request it also checks that `X.Y.Z` matches those manifests and that `CHANGELOG.md` has a `## [X.Y.Z] - YYYY-MM-DD` section. + +### Publish + +Pushing the merge to `main` runs **publish** in `.github/workflows/push_gem.yml` when that commit is the merge of a `release/X.Y.Z` pull request. The job uses the GitHub environment `release`. It builds the gem, pushes it to RubyGems with trusted publishing, then creates tag `vX.Y.Z` and a GitHub Release. The release notes are that changelog section. If the section is missing, the notes are `Release X.Y.Z.` so an older release pull request still publishes. + +A re-run does not push a version that is already on RubyGems for this commit. If that version is already on RubyGems for a different commit, the job fails and names the version. + +The workflow filename stays `push_gem.yml` so the existing trusted publisher keeps matching. Tags are `vX.Y.Z`. Existing tags already use that form; older tags are left as they are. + +Publishing a GitHub Release by hand (`release: published`) still pushes the gem when the tag is `vX.Y.Z` and that version is not already on RubyGems. `workflow_dispatch` publish was removed. + +## One-time setup + +Do this once, before the next release. This change does not modify repository or RubyGems settings. + +1. Create a GitHub environment named `release` (**Settings → Environments**). Add required reviewers so the publish job waits for approval. It does not need secrets. +2. On the `ruby-proxy-headers` trusted publisher, set the GitHub environment to `release`. Keep the repository `proxymesh/ruby-proxy-headers` and the workflow filename `push_gem.yml`. A publisher with a blank environment will reject the next push until the environment matches. If the environment cannot be edited, create a publisher with those values and remove the old one. +3. Publishing uses OpenID Connect. No RubyGems API token is read from the workflow. After a publish succeeds, delete any leftover RubyGems token from repository or environment secrets. +4. **Prepare release** opens the pull request as `github-actions[bot]`. Actions workflow permissions need read and write access, and **Allow GitHub Actions to create and approve pull requests** should stay enabled. From 1bad2f43cd0f6cc8f2f07d8b4a43dae0529d0951 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 12 Nov 2026 22:22:39 +0000 Subject: [PATCH 2/7] Shrink the release flow to the shared shape. The bump script only edits manifests and prints changelog notes, and Push Gem publishes with gem push then creates the GitHub Release. Co-authored-by: ProxyMesh AI --- .cursor/skills/release/SKILL.md | 2 +- .github/scripts/release.rb | 409 +++--------------- .github/workflows/prepare-release.yml | 47 +- .github/workflows/proxy_integration_tests.yml | 2 +- .github/workflows/push_gem.yml | 176 ++++---- .github/workflows/unit_tests.yml | 2 +- RELEASING.md | 32 +- spec/release_script_spec.rb | 26 ++ 8 files changed, 227 insertions(+), 469 deletions(-) create mode 100644 spec/release_script_spec.rb diff --git a/.cursor/skills/release/SKILL.md b/.cursor/skills/release/SKILL.md index f7a066a..687ac45 100644 --- a/.cursor/skills/release/SKILL.md +++ b/.cursor/skills/release/SKILL.md @@ -29,7 +29,7 @@ From latest `origin/main`: gh workflow run "Prepare release" --ref main -f version=SPEC ``` -Wait until that run opens the pull request titled `Release X.Y.Z`. +The workflow runs the version, changelog, and gem build checks before it pushes, because a pull request it opens does not run pull_request workflows. Wait until the run opens the pull request titled `Release X.Y.Z`. ## Manual path diff --git a/.github/scripts/release.rb b/.github/scripts/release.rb index 65c1662..0aa2cd7 100644 --- a/.github/scripts/release.rb +++ b/.github/scripts/release.rb @@ -1,227 +1,80 @@ # frozen_string_literal: true -require 'date' require 'English' -require 'json' -require 'net/http' -require 'open3' -require 'rubygems/package' -require 'tmpdir' -# Prepares a release checkout and checks the version manifests. -# One script, so it is longer than RuboCop's library module limit. -# rubocop:disable Metrics/ModuleLength +# Bumps the gem version and prints a changelog section. module GemRelease - SEMVER = '(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)' - VERSION_RE = Regexp.new("\\A#{SEMVER}\\z").freeze - RELEASE_REF_RE = Regexp.new("\\Arelease/#{SEMVER}\\z").freeze - TAG_RE = Regexp.new("\\Av#{SEMVER}\\z").freeze - REPO_RE = %r{\A[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+\z} VERSION_FILE = 'lib/ruby_proxy_headers/version.rb' - GEM_NAME = 'ruby-proxy-headers' + VERSION_RE = /\A(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)\z/ class Error < StandardError end - USAGE = 'usage: release.rb version|bump|check|check-branch|notes|gate|plan|push-gem|github-release' - - COMMANDS = { - 'version' => ->(*) { puts read_version }, - 'bump' => ->(argv) { bump(argv[1]) }, - 'check' => ->(argv) { run_check(argv.drop(1)) }, - 'check-branch' => ->(*) { check_branch }, - 'notes' => ->(argv) { print changelog_notes(required_version(argv[1])) }, - 'gate' => ->(*) { gate }, - 'plan' => ->(*) { plan }, - 'push-gem' => ->(*) { push_gem }, - 'github-release' => ->(*) { github_release } - }.freeze - def self.run(argv) - command = COMMANDS[argv.first] - return command.call(argv) if command - - warn USAGE - exit 1 + case argv.first + when 'bump' then bump(argv[1]) + when 'notes' then print notes(argv[1]) + else warn 'usage: release.rb bump SPEC|notes X.Y.Z' + exit 1 + end rescue Error => e warn e.message exit 1 end - def self.read_version - match = File.read(VERSION_FILE).match(/^\s*VERSION = ['"]([^'"]+)['"]/) - version = match && match[1] - raise Error, "#{VERSION_FILE} has no MAJOR.MINOR.PATCH VERSION" unless version&.match?(VERSION_RE) - - version - end - def self.bump(spec) - spec = spec.to_s.strip current = read_version - version = bump_number(current, spec).join('.') + version = next_version(current, spec.to_s.strip) write_version(version) write_lock(current, version) write_changelog(current, version, Time.now.utc.strftime('%Y-%m-%d')) - warn "Release #{version}" - emit('version', version) - end - - def self.run_check(argv) - options = { expected: nil, require_changelog: false, gem_path: nil } - parse_check_arg(options, argv) until argv.empty? - check(**options) - end - - def self.parse_check_arg(options, argv) - arg = argv.shift - case arg - when '--version' then options[:expected] = required_version(argv.shift) - when '--require-changelog' then options[:require_changelog] = true - when '--gem' then options[:gem_path] = argv.shift - else raise Error, "unknown argument #{arg}" - end - raise Error, '--gem needs a path' if arg == '--gem' && options[:gem_path].to_s.empty? - end - - def self.check(expected: nil, require_changelog: false, gem_path: nil) - version = read_version - assert_lock(version) - raise Error, "version is #{version}, expected #{expected}" if expected && expected != version - - assert_changelog(version) if require_changelog - assert_gem(version, gem_path) if gem_path - end - - def self.check_branch - return unless ENV.fetch('GITHUB_EVENT_NAME') == 'pull_request' - - ref = ENV.fetch('GITHUB_HEAD_REF', '') - return unless ref.start_with?('release/') - - match = ref.match(RELEASE_REF_RE) - raise Error, 'release branch must be release/X.Y.Z' unless match - - check(expected: version_from(match), require_changelog: true) - end - - def self.gate - case ENV.fetch('GITHUB_EVENT_NAME') - when 'push' then gate_push - when 'release' then gate_tag - else raise Error, "unexpected event #{ENV.fetch('GITHUB_EVENT_NAME')}" - end - end - - def self.plan - action, create, message = plan_action(plan_state) - warn message if message - emit('action', action) - emit('create_release', create ? 'true' : 'false') - end - - def self.plan_state - version = required_version(ENV.fetch('VERSION')) - tag = "v#{version}" - { - mode: ENV.fetch('MODE'), - version: version, - gem_exists: gem_published?(version), - release_exists: release_exists?(tag), - tag_sha: tag_commit(tag), - head_sha: ENV.fetch('TARGET_SHA') - } - end - - def self.push_gem - version = required_version(ENV.fetch('VERSION')) - path = "#{GEM_NAME}-#{version}.gem" - raise Error, "#{path} was not built" unless File.file?(path) - - stdout, stderr, status = Open3.capture3('gem', 'push', path) - return if status.success? - return if "#{stdout}\n#{stderr}".match?(/already exists|Repushing|same version/i) - - warn stdout - warn stderr - raise Error, "gem push failed for #{version}" + append_output(version) end - def self.github_release - version = required_version(ENV.fetch('VERSION')) - tag = "v#{version}" - return warn("GitHub Release #{tag} already exists.") if release_exists?(tag) + def self.notes(version) + raise Error, 'version must be X.Y.Z' unless version.to_s.match?(VERSION_RE) - notes = File.join(Dir.tmpdir, 'release-notes.md') - File.write(notes, release_notes(version)) - create_release(tag, notes) - end - - def self.create_release(tag, notes) - _stdout, stderr, status = Open3.capture3( - 'gh', 'release', 'create', tag, '--repo', repository, - '--target', ENV.fetch('TARGET_SHA'), '--title', tag, '--notes-file', notes - ) - return if status.success? - - warn stderr - raise Error, "could not create GitHub Release #{tag}" - end - - def self.changelog_notes(version) lines = File.readlines('CHANGELOG.md') - start = lines.index { |line| dated_heading?(line, version) } + start = heading_index(lines, version) raise Error, "CHANGELOG.md has no dated #{version} section" unless start - rest = lines[(start + 1)..] || [] - stop = rest.index { |line| section_boundary?(line) } - body = stop ? rest[0...stop] : rest - "#{([lines[start]] + body).join.strip}\n" + slice_section(lines, start) end - def self.plan_action(state) - same = !state[:tag_sha].empty? && state[:tag_sha] == state[:head_sha] - return gem_already_published(state, same) if state[:gem_exists] - raise Error, "GitHub Release v#{state[:version]} does not point at this commit" if misplaced_release?(state, same) - - ['push', state[:mode] == 'release', nil] + def self.heading_index(lines, version) + pattern = /\A## \[#{Regexp.escape(version)}\] - \d{4}-\d{2}-\d{2}\z/ + lines.index { |line| line.strip.match?(pattern) } end - def self.misplaced_release?(state, same) - state[:mode] == 'release' && state[:release_exists] && !same && !state[:tag_sha].empty? + def self.slice_section(lines, start) + rest = lines[(start + 1)..] || [] + stop = rest.index { |line| line.start_with?('## ') || line.match?(/\A\[[^\]]+\]:/) } + "#{([lines[start]] + (stop ? rest[0...stop] : rest)).join.strip}\n" end - def self.gem_already_published(state, same) - version = state[:version] - done = ['already_done', false, "#{version} is already published for this commit"] - return done if state[:release_exists] && same - - if !state[:tag_sha].empty? && !same - raise Error, "#{version} is already on RubyGems at #{state[:tag_sha]}. Refusing to push it again." - end - - return ['release_only', true, nil] if state[:mode] == 'release' + def self.read_version + match = File.read(VERSION_FILE).match(/^\s*VERSION = ['"]([^'"]+)['"]/) + version = match && match[1] + raise Error, 'version.rb has no MAJOR.MINOR.PATCH' unless version&.match?(VERSION_RE) - raise Error, "#{version} is already on RubyGems. Refusing to push it again." + version end - def self.bump_number(current, spec) + def self.next_version(current, spec) major, minor, patch = current.split('.').map(&:to_i) case spec - when 'patch' then [major, minor, patch + 1] - when 'minor' then [major, minor + 1, 0] - when 'major' then [major + 1, 0, 0] + when 'patch' then "#{major}.#{minor}.#{patch + 1}" + when 'minor' then "#{major}.#{minor + 1}.0" + when 'major' then "#{major + 1}.0.0" else raise Error, "#{spec} is not a newer X.Y.Z, patch, minor, or major" unless newer?(spec, current) - spec.split('.').map(&:to_i) + spec end end def self.newer?(spec, current) - return false unless spec.match?(VERSION_RE) - - (spec.split('.').map(&:to_i) <=> current.split('.').map(&:to_i)) == 1 + spec.match?(VERSION_RE) && (spec.split('.').map(&:to_i) <=> current.split('.').map(&:to_i)) == 1 end def self.write_version(version) @@ -233,206 +86,48 @@ def self.write_version(version) def self.write_lock(old_version, new_version) count = 0 - pattern = /^(\s*#{GEM_NAME} \()#{Regexp.escape(old_version)}(\).*)$/ + pattern = /^(\s*ruby-proxy-headers \()#{Regexp.escape(old_version)}(\).*)$/ updated = File.read('Gemfile.lock').gsub(pattern) do count += 1 "#{Regexp.last_match(1)}#{new_version}#{Regexp.last_match(2)}" end - raise Error, 'Gemfile.lock has no ruby-proxy-headers version to update' if count.zero? + raise Error, 'Gemfile.lock has no ruby-proxy-headers version' if count.zero? File.write('Gemfile.lock', updated) end def self.write_changelog(old_version, version, date) - lines, start, finish = split_unreleased(File.read('CHANGELOG.md')) - text = replace_unreleased(lines, start, finish, version, date) - File.write('CHANGELOG.md', rewrite_links(text, old_version, version)) + lines, start, finish = unreleased_span(File.read('CHANGELOG.md')) + body = lines[(start + 1)...finish].join.strip + heading = "## [Unreleased]\n\n## [#{version}] - #{date}\n" + heading = "#{heading}\n#{body}\n" unless body.empty? + lines[start...finish] = ["#{heading}\n"] + File.write('CHANGELOG.md', with_links(lines.join, old_version, version)) end - def self.split_unreleased(text) + def self.unreleased_span(text) lines = text.lines start = lines.index { |line| line.strip == '## [Unreleased]' } raise Error, 'CHANGELOG.md has no ## [Unreleased] section' unless start - offset = lines[(start + 1)..].index { |line| section_boundary?(line) } - finish = offset ? start + 1 + offset : lines.size - [lines, start, finish] + offset = lines[(start + 1)..].index { |line| line.start_with?('## ') || line.match?(/\A\[[^\]]+\]:/) } + [lines, start, offset ? start + 1 + offset : lines.size] end - def self.replace_unreleased(lines, start, finish, version, date) - body = lines[(start + 1)...finish].join.strip - section = "## [Unreleased]\n\n## [#{version}] - #{date}\n" - section += "\n#{body}\n" unless body.empty? - lines[start...finish] = ["#{section}\n"] - lines.join - end - - def self.rewrite_links(text, old_version, version) - lines = text.lines - replace_link(lines, '[Unreleased]:', "[Unreleased]: https://github.com/#{repository}/compare/v#{version}...HEAD\n") - place_version_link(lines, version, old_version) - lines.join - end + def self.with_links(text, old_version, version) + repo = ENV.fetch('GITHUB_REPOSITORY') + unreleased = "[Unreleased]: https://github.com/#{repo}/compare/v#{version}...HEAD" + current = "[#{version}]: https://github.com/#{repo}/compare/v#{old_version}...v#{version}" + text = text.sub(/^\[Unreleased\]:.*$/, unreleased) + return text if text.include?("#{current}\n") - def self.replace_link(lines, prefix, replacement) - index = lines.index { |line| line.start_with?(prefix) } - index ? lines[index] = replacement : lines << replacement + text.sub(/(\[Unreleased\]:.*\n)/, "\\1#{current}\n") end - def self.place_version_link(lines, version, old_version) - prefix = "[#{version}]:" - replacement = "#{prefix} https://github.com/#{repository}/compare/v#{old_version}...v#{version}\n" - index = lines.index { |line| line.start_with?(prefix) } - return lines[index] = replacement if index - - after = lines.index { |line| line.start_with?('[Unreleased]:') } - after ? lines.insert(after + 1, replacement) : lines << replacement - end - - def self.gate_push - event = JSON.parse(File.read(ENV.fetch('GITHUB_EVENT_PATH'))) - sha = ENV.fetch('GITHUB_SHA') - version = choose_release(pulls(sha), event.dig('head_commit', 'message').to_s) - emit('publish', version ? 'true' : 'false') - return unless version - - emit('version', version) - emit('sha', sha) - emit('mode', 'release') - end - - def self.gate_tag - match = ENV.fetch('GITHUB_REF_NAME').match(TAG_RE) - raise Error, 'release tag must be vX.Y.Z' unless match - - emit('publish', 'true') - emit('version', version_from(match)) - emit('sha', ENV.fetch('GITHUB_SHA')) - emit('mode', 'gem') - end - - def self.choose_release(pulls, message) - versions = pulls.filter_map { |pull| release_version(pull) } - raise Error, "commit is in more than one release pull request: #{versions.join(', ')}" if versions.size > 1 - return versions.first if versions.any? - - return nil unless release_message?(message) - - raise Error, 'commit looks like a release merge, but no release pull request is attached to it' - end - - def self.release_version(pull) - return unless pull['merged_at'] || pull['merged'] == true - return unless pull.dig('base', 'ref') == 'main' - - match = pull.dig('head', 'ref').to_s.match(RELEASE_REF_RE) - version_from(match) if match - end - - def self.release_message?(text) - text.match?(%r{from \S+/release/#{SEMVER}}) || text.match?(/\ARelease #{SEMVER}\b/) - end - - def self.pulls(sha) - stdout, status = Open3.capture2('gh', 'api', "repos/#{repository}/commits/#{sha}/pulls") - raise Error, 'could not list pull requests for this commit' unless status.success? - - parsed = JSON.parse(stdout) - raise Error, 'could not list pull requests for this commit' unless parsed.is_a?(Array) - - parsed - end - - def self.gem_published?(version) - uri = URI("https://rubygems.org/api/v2/rubygems/#{GEM_NAME}/versions/#{version}.json") - response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 15, read_timeout: 30) do |http| - http.get(uri.request_uri) - end - return true if response.code == '200' - return false if response.code == '404' - - raise Error, "RubyGems returned HTTP #{response.code} for #{version}" - end - - def self.tag_commit(tag) - stdout, status = Open3.capture2('git', 'rev-parse', '--verify', "#{tag}^{commit}") - status.success? ? stdout.strip : '' - end - - def self.release_exists?(tag) - _stdout, status = Open3.capture2('gh', 'release', 'view', tag, '--repo', repository) - status.success? - end - - def self.release_notes(version) - return changelog_notes(version) if File.readlines('CHANGELOG.md').any? { |line| dated_heading?(line, version) } - - "Release #{version}.\n" - end - - def self.assert_lock(version) - found = File.readlines('Gemfile.lock').filter_map { |line| line[/^\s*#{GEM_NAME} \(([^)]+)\)/, 1] } - raise Error, 'Gemfile.lock has no ruby-proxy-headers version' if found.empty? - return if found.uniq == [version] - - raise Error, "Gemfile.lock has #{found.uniq.join(', ')}, #{VERSION_FILE} has #{version}" - end - - def self.assert_changelog(version) - return if File.readlines('CHANGELOG.md').any? { |line| dated_heading?(line, version) } - - raise Error, "CHANGELOG.md has no ## [#{version}] - YYYY-MM-DD section" - end - - def self.assert_gem(version, path) - expected = "#{GEM_NAME}-#{version}.gem" - raise Error, "#{File.basename(path)} is not #{expected}" unless File.basename(path) == expected - - built = Gem::Package.new(path).spec.version.to_s - return if built == version - - raise Error, "built gem is #{built}, expected #{version}" - end - - def self.dated_heading?(line, version) - match = line.strip.match(/\A## \[#{Regexp.escape(version)}\] - (\d{4}-\d{2}-\d{2})\z/) - return false unless match - - Date.iso8601(match[1]) - true - rescue ArgumentError - false - end - - def self.section_boundary?(line) - line.start_with?('## ') || line.match?(/\A\[[^\]]+\]:/) - end - - def self.required_version(value) - raise Error, 'version must be X.Y.Z' unless value.to_s.match?(VERSION_RE) - - value - end - - def self.version_from(match) - "#{match[1]}.#{match[2]}.#{match[3]}" - end - - def self.repository - repo = ENV['GITHUB_REPOSITORY'].to_s - return repo if repo.match?(REPO_RE) - - raise Error, 'GITHUB_REPOSITORY is not set' - end - - def self.emit(key, value) - puts "#{key}=#{value}" + def self.append_output(version) path = ENV.fetch('GITHUB_OUTPUT', '') - return if path.empty? - - File.open(path, 'a') { |file| file.puts "#{key}=#{value}" } + File.open(path, 'a') { |file| file.puts "version=#{version}" } unless path.empty? end end -# rubocop:enable Metrics/ModuleLength GemRelease.run(ARGV) if $PROGRAM_NAME == __FILE__ diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml index ee47f78..ab6268b 100644 --- a/.github/workflows/prepare-release.yml +++ b/.github/workflows/prepare-release.yml @@ -1,4 +1,6 @@ # Opens a release/X.Y.Z pull request. Does not merge it. +# A pull request opened with GITHUB_TOKEN does not run pull_request workflows, +# so this job runs the release checks before it pushes. name: Prepare release @@ -10,8 +12,7 @@ on: required: true type: string -permissions: - contents: read +permissions: {} concurrency: group: prepare-release @@ -20,7 +21,7 @@ concurrency: jobs: prepare: runs-on: ubuntu-24.04 - timeout-minutes: 10 + timeout-minutes: 15 permissions: contents: write pull-requests: write @@ -40,7 +41,7 @@ jobs: persist-credentials: true - name: Set up Ruby - uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199 # v1 + uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199 # v1.338.0 with: bundler: none ruby-version: ruby @@ -51,6 +52,35 @@ jobs: RELEASE_SPEC: ${{ inputs.version }} run: ruby .github/scripts/release.rb bump "${RELEASE_SPEC}" + - name: Check version files + env: + VERSION: ${{ steps.bump.outputs.version }} + run: | + set -euo pipefail + file_version="$(ruby -r ./lib/ruby_proxy_headers/version.rb -e 'puts RubyProxyHeaders::VERSION')" + if [[ "${VERSION}" != "${file_version}" ]]; then + echo "bumped ${VERSION} but version.rb is ${file_version}" >&2 + exit 1 + fi + lock="$(grep -E '^[[:space:]]*ruby-proxy-headers \([0-9]+\.[0-9]+\.[0-9]+\)' Gemfile.lock || true)" + if [[ -z "${lock}" ]] || grep -v "ruby-proxy-headers (${VERSION})" <<<"${lock}" | grep -q .; then + echo "Gemfile.lock does not match ${VERSION}" >&2 + exit 1 + fi + + - name: Check changelog + env: + VERSION: ${{ steps.bump.outputs.version }} + run: ruby .github/scripts/release.rb notes "${VERSION}" >/dev/null + + - name: Build gem + env: + VERSION: ${{ steps.bump.outputs.version }} + run: | + set -euo pipefail + gem build ruby-proxy-headers.gemspec + test -f "ruby-proxy-headers-${VERSION}.gem" + - name: Push release branch env: VERSION: ${{ steps.bump.outputs.version }} @@ -76,16 +106,9 @@ jobs: GH_TOKEN: ${{ github.token }} run: | set -euo pipefail - branch="release/${VERSION}" - head="${GITHUB_REPOSITORY%%/*}:${branch}" - count="$(gh pr list --base main --head "${head}" --state open --json number --jq length)" - if [[ "${count}" != "0" ]]; then - echo "An open pull request for ${branch} already exists." >&2 - exit 1 - fi ruby .github/scripts/release.rb notes "${VERSION}" > "${RUNNER_TEMP}/notes.md" gh pr create \ --base main \ - --head "${branch}" \ + --head "release/${VERSION}" \ --title "Release ${VERSION}" \ --body-file "${RUNNER_TEMP}/notes.md" diff --git a/.github/workflows/proxy_integration_tests.yml b/.github/workflows/proxy_integration_tests.yml index a94d23d..2b37ed4 100644 --- a/.github/workflows/proxy_integration_tests.yml +++ b/.github/workflows/proxy_integration_tests.yml @@ -21,7 +21,7 @@ jobs: persist-credentials: false - name: Set up Ruby - uses: ruby/setup-ruby@v1 # kept unpinned per maintainer guidance — pinning freezes available Ruby versions + uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199 # v1.338.0 with: bundler-cache: true ruby-version: ruby diff --git a/.github/workflows/push_gem.yml b/.github/workflows/push_gem.yml index 668c596..87c1e44 100644 --- a/.github/workflows/push_gem.yml +++ b/.github/workflows/push_gem.yml @@ -1,23 +1,18 @@ # The RubyGems trusted publisher is registered to this filename (push_gem.yml). -# Pull requests run the release check. Merging release/X.Y.Z publishes the gem, -# then tags vX.Y.Z and opens the GitHub Release. The publish job uses the -# GitHub environment "release". name: Push Gem on: pull_request: + branches: [main] push: - branches: - - main - release: - types: [published] + branches: [main] -permissions: - contents: read +permissions: {} jobs: release-check: + name: Release check if: github.event_name == 'pull_request' runs-on: ubuntu-24.04 timeout-minutes: 15 @@ -29,117 +24,134 @@ jobs: with: persist-credentials: false - - name: actionlint - run: | - set -euo pipefail - archive="${RUNNER_TEMP}/actionlint.tar.gz" - curl -sSfL -o "${archive}" \ - https://github.com/rhysd/actionlint/releases/download/v1.7.12/actionlint_1.7.12_linux_amd64.tar.gz - echo "8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8 ${archive}" | sha256sum -c - - tar -xzf "${archive}" -C "${RUNNER_TEMP}" actionlint - "${RUNNER_TEMP}/actionlint" -color - - name: Set up Ruby - uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199 # v1 + uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199 # v1.338.0 with: bundler: none ruby-version: ruby + - name: Check version files + run: | + set -euo pipefail + version="$(ruby -r ./lib/ruby_proxy_headers/version.rb -e 'puts RubyProxyHeaders::VERSION')" + lock="$(grep -E '^[[:space:]]*ruby-proxy-headers \([0-9]+\.[0-9]+\.[0-9]+\)' Gemfile.lock || true)" + if [[ -z "${lock}" ]] || grep -v "ruby-proxy-headers (${version})" <<<"${lock}" | grep -q .; then + echo "Gemfile.lock does not match ${version}" >&2 + exit 1 + fi + - name: Build gem run: gem build ruby-proxy-headers.gemspec - - name: Check version manifests and gem + - name: Check release branch + if: startsWith(github.head_ref, 'release/') + env: + HEAD_REF: ${{ github.head_ref }} run: | set -euo pipefail - gems=(ruby-proxy-headers-*.gem) - ruby .github/scripts/release.rb check --gem "${gems[0]}" + version="${HEAD_REF#release/}" + file_version="$(ruby -r ./lib/ruby_proxy_headers/version.rb -e 'puts RubyProxyHeaders::VERSION')" + if [[ "${version}" != "${file_version}" ]]; then + echo "${HEAD_REF} does not match ${file_version}" >&2 + exit 1 + fi + ruby .github/scripts/release.rb notes "${version}" >/dev/null - - name: Check release branch - run: ruby .github/scripts/release.rb check-branch - - gate: - if: github.event_name != 'pull_request' + publish: + if: github.event_name == 'push' runs-on: ubuntu-24.04 - timeout-minutes: 10 + timeout-minutes: 20 + environment: release permissions: contents: read + id-token: write pull-requests: read - outputs: - publish: ${{ steps.decide.outputs.publish }} - version: ${{ steps.decide.outputs.version }} - sha: ${{ steps.decide.outputs.sha }} - mode: ${{ steps.decide.outputs.mode }} steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - ref: ${{ github.sha }} persist-credentials: false - - name: Decide - id: decide + - name: Release version + id: release env: GH_TOKEN: ${{ github.token }} - run: ruby .github/scripts/release.rb gate - - publish: - needs: gate - if: >- - needs.gate.result == 'success' && - needs.gate.outputs.publish == 'true' && - github.repository == 'proxymesh/ruby-proxy-headers' - runs-on: ubuntu-24.04 - timeout-minutes: 20 - environment: release - permissions: - contents: write - id-token: write - steps: - - name: Checkout - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ needs.gate.outputs.sha }} - fetch-depth: 0 - persist-credentials: false + run: | + set -euo pipefail + version="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${GITHUB_SHA}/pulls" --jq '[.[] | select(.merged_at != null and .base.ref == "main" and (.head.ref | test("^release/[0-9]+\\.[0-9]+\\.[0-9]+$"))) | .head.ref] | if length == 0 then "" elif length == 1 then .[0][8:] else error("more than one release pull request") end')" + if [[ -z "${version}" ]]; then + echo "publish=false" >> "${GITHUB_OUTPUT}" + exit 0 + fi + echo "publish=true" >> "${GITHUB_OUTPUT}" + echo "version=${version}" >> "${GITHUB_OUTPUT}" - name: Set up Ruby - uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199 # v1 + if: steps.release.outputs.publish == 'true' + uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199 # v1.338.0 with: bundler: none ruby-version: ruby - - name: Check version - env: - VERSION: ${{ needs.gate.outputs.version }} - run: ruby .github/scripts/release.rb check --version "${VERSION}" - - - name: Plan - id: plan - env: - VERSION: ${{ needs.gate.outputs.version }} - MODE: ${{ needs.gate.outputs.mode }} - TARGET_SHA: ${{ needs.gate.outputs.sha }} - GH_TOKEN: ${{ github.token }} - run: ruby .github/scripts/release.rb plan - - name: Build gem - if: steps.plan.outputs.action == 'push' + if: steps.release.outputs.publish == 'true' run: gem build ruby-proxy-headers.gemspec - name: Configure RubyGems credentials - if: steps.plan.outputs.action == 'push' + if: steps.release.outputs.publish == 'true' uses: rubygems/configure-rubygems-credentials@dc5a8d8553e6ee01fc26761a49e99e733d17954a # v2.1.0 - name: Push gem - if: steps.plan.outputs.action == 'push' + if: steps.release.outputs.publish == 'true' env: - VERSION: ${{ needs.gate.outputs.version }} - run: ruby .github/scripts/release.rb push-gem + VERSION: ${{ steps.release.outputs.version }} + run: gem push "ruby-proxy-headers-${VERSION}.gem" + + github-release: + needs: publish + if: github.event_name == 'push' && needs.publish.result == 'success' + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: write + pull-requests: read + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Release version + id: release + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + version="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${GITHUB_SHA}/pulls" --jq '[.[] | select(.merged_at != null and .base.ref == "main" and (.head.ref | test("^release/[0-9]+\\.[0-9]+\\.[0-9]+$"))) | .head.ref] | if length == 0 then "" elif length == 1 then .[0][8:] else error("more than one release pull request") end')" + if [[ -z "${version}" ]]; then + echo "publish=false" >> "${GITHUB_OUTPUT}" + exit 0 + fi + echo "publish=true" >> "${GITHUB_OUTPUT}" + echo "version=${version}" >> "${GITHUB_OUTPUT}" + + - name: Set up Ruby + if: steps.release.outputs.publish == 'true' + uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199 # v1.338.0 + with: + bundler: none + ruby-version: ruby - name: Create GitHub Release - if: steps.plan.outputs.create_release == 'true' + if: steps.release.outputs.publish == 'true' env: - VERSION: ${{ needs.gate.outputs.version }} - TARGET_SHA: ${{ needs.gate.outputs.sha }} + VERSION: ${{ steps.release.outputs.version }} GH_TOKEN: ${{ github.token }} - run: ruby .github/scripts/release.rb github-release + run: | + set -euo pipefail + ruby .github/scripts/release.rb notes "${VERSION}" > "${RUNNER_TEMP}/notes.md" + gh release view "v${VERSION}" --repo "${GITHUB_REPOSITORY}" \ + || gh release create "v${VERSION}" \ + --repo "${GITHUB_REPOSITORY}" \ + --title "v${VERSION}" \ + --notes-file "${RUNNER_TEMP}/notes.md" diff --git a/.github/workflows/unit_tests.yml b/.github/workflows/unit_tests.yml index 6bf1db3..8361b4c 100644 --- a/.github/workflows/unit_tests.yml +++ b/.github/workflows/unit_tests.yml @@ -20,7 +20,7 @@ jobs: persist-credentials: false - name: Set up Ruby ${{ matrix.ruby-version }} - uses: ruby/setup-ruby@v1 # kept unpinned per maintainer guidance — pinning freezes available Ruby versions + uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199 # v1.338.0 with: ruby-version: ${{ matrix.ruby-version }} bundler-cache: true diff --git a/RELEASING.md b/RELEASING.md index 3806141..2ab126c 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -4,10 +4,10 @@ 1. On GitHub, open **Actions** → **Prepare release** → **Run workflow** on `main`. 2. Set **version** to `X.Y.Z`, `patch`, `minor`, or `major`. -3. The workflow pushes `release/X.Y.Z` and opens a pull request titled `Release X.Y.Z`. The body is the changelog section. It does not auto-merge. -4. Wait until **Push Gem / release-check** is green, then merge the pull request. +3. The workflow bumps the version, moves the changelog section, runs the release checks, and opens a pull request titled `Release X.Y.Z`. It does not auto-merge. +4. Merge that pull request when you are ready. -Opening the pull request by hand still works. From an up-to-date `main`, bump every version manifest, move `## [Unreleased]` in `CHANGELOG.md` to `## [X.Y.Z] - YYYY-MM-DD`, push `release/X.Y.Z`, and open a pull request titled `Release X.Y.Z` whose body is that changelog section. Do not auto-merge. +Opening the pull request by hand still works. From an up-to-date `main`, bump every version manifest, move `## [Unreleased]` in `CHANGELOG.md` to `## [X.Y.Z] - YYYY-MM-DD`, and open a pull request titled `Release X.Y.Z` whose body is that changelog section. Do not auto-merge. Version manifests: @@ -18,31 +18,33 @@ Version manifests: ## What runs -### Prepare +### Prepare release -`.github/workflows/prepare-release.yml` runs on `workflow_dispatch`. It bumps the manifests, moves the changelog section, and opens the pull request. +`.github/workflows/prepare-release.yml` runs on `workflow_dispatch` from `main`. It bumps the manifests, moves the changelog section, checks that the version matches and the changelog has a dated section, builds the gem, and opens the pull request. -### Validate +A pull request opened with `GITHUB_TOKEN` does not run `pull_request` workflows, so those checks run in this job before the branch is pushed. -`.github/workflows/push_gem.yml` runs **release-check** on pull requests. It runs actionlint, checks that `version.rb` and `Gemfile.lock` agree, and runs `gem build`. +### Release check -On a `release/X.Y.Z` pull request it also checks that `X.Y.Z` matches those manifests and that `CHANGELOG.md` has a `## [X.Y.Z] - YYYY-MM-DD` section. +`.github/workflows/push_gem.yml` runs **Release check** on pull requests into `main`. It checks that `version.rb` and `Gemfile.lock` agree and runs `gem build`. On a `release/X.Y.Z` pull request it also checks that `X.Y.Z` matches those files and that `CHANGELOG.md` has a `## [X.Y.Z] - YYYY-MM-DD` section. ### Publish -Pushing the merge to `main` runs **publish** in `.github/workflows/push_gem.yml` when that commit is the merge of a `release/X.Y.Z` pull request. The job uses the GitHub environment `release`. It builds the gem, pushes it to RubyGems with trusted publishing, then creates tag `vX.Y.Z` and a GitHub Release. The release notes are that changelog section. If the section is missing, the notes are `Release X.Y.Z.` so an older release pull request still publishes. +A push to `main` runs **publish** and **github-release** in `.github/workflows/push_gem.yml`. Each job looks up the pull request for that commit and does nothing when it is not a merged `release/X.Y.Z` pull request. -A re-run does not push a version that is already on RubyGems for this commit. If that version is already on RubyGems for a different commit, the job fails and names the version. +**publish** uses the GitHub environment `release`. It builds the gem and pushes it with `gem push` after `rubygems/configure-rubygems-credentials`. A version already on RubyGems fails the push. **github-release** then runs `gh release view` or `gh release create` with the changelog section as the notes. -The workflow filename stays `push_gem.yml` so the existing trusted publisher keeps matching. Tags are `vX.Y.Z`. Existing tags already use that form; older tags are left as they are. +The workflow filename stays `push_gem.yml` so the existing trusted publisher keeps matching. -Publishing a GitHub Release by hand (`release: published`) still pushes the gem when the tag is `vX.Y.Z` and that version is not already on RubyGems. `workflow_dispatch` publish was removed. - -## One-time setup +## One-time owner setup Do this once, before the next release. This change does not modify repository or RubyGems settings. 1. Create a GitHub environment named `release` (**Settings → Environments**). Add required reviewers so the publish job waits for approval. It does not need secrets. -2. On the `ruby-proxy-headers` trusted publisher, set the GitHub environment to `release`. Keep the repository `proxymesh/ruby-proxy-headers` and the workflow filename `push_gem.yml`. A publisher with a blank environment will reject the next push until the environment matches. If the environment cannot be edited, create a publisher with those values and remove the old one. +2. On the `ruby-proxy-headers` trusted publisher, set the GitHub environment to `release`. Keep the repository `proxymesh/ruby-proxy-headers` and the workflow filename `push_gem.yml`. A publisher with a blank environment will reject the next push until it matches. If the environment cannot be edited, create a publisher with those values and remove the old one. 3. Publishing uses OpenID Connect. No RubyGems API token is read from the workflow. After a publish succeeds, delete any leftover RubyGems token from repository or environment secrets. 4. **Prepare release** opens the pull request as `github-actions[bot]`. Actions workflow permissions need read and write access, and **Allow GitHub Actions to create and approve pull requests** should stay enabled. + +## Tags + +Tags are `vX.Y.Z`. Existing tags already use that form. Older tags are left as they are. diff --git a/spec/release_script_spec.rb b/spec/release_script_spec.rb new file mode 100644 index 0000000..ebae864 --- /dev/null +++ b/spec/release_script_spec.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'fileutils' +require 'open3' +require 'tmpdir' + +RSpec.describe 'release script' do + it 'bumps a patch and prints the dated changelog section' do + Dir.mktmpdir do |dir| + FileUtils.mkdir_p("#{dir}/lib/ruby_proxy_headers") + File.write("#{dir}/lib/ruby_proxy_headers/version.rb", "module RubyProxyHeaders\n VERSION = '0.2.3'\nend\n") + File.write("#{dir}/Gemfile.lock", " ruby-proxy-headers (0.2.3)\n") + File.write("#{dir}/CHANGELOG.md", "## [Unreleased]\n\n- Note\n\n## [0.1.0] - 2024-02-28\n\n[Unreleased]: https://github.com/proxymesh/ruby-proxy-headers/compare/v0.1.0...HEAD\n") + script = File.expand_path('../.github/scripts/release.rb', __dir__) + env = { 'GITHUB_REPOSITORY' => 'proxymesh/ruby-proxy-headers' } + _output, status = Open3.capture2e(env, 'ruby', script, 'bump', 'patch', chdir: dir) + expect(status).to be_success + expect(File.read("#{dir}/lib/ruby_proxy_headers/version.rb")).to include("VERSION = '0.2.4'") + notes, notes_status = Open3.capture2e(env, 'ruby', script, 'notes', '0.2.4', chdir: dir) + expect(notes_status).to be_success + expect(notes).to include('## [0.2.4] - ') + expect(notes).to include('- Note') + end + end +end From 6b229abd685a05be70e655bf6dba32ec6b1c112d Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 12 Nov 2026 22:38:28 +0000 Subject: [PATCH 3/7] Look up release merges before using the release environment. A lookup job finds a merged release/X.Y.Z pull request, and release.rb check replaces the duplicated version checks. Co-authored-by: ProxyMesh AI --- .cursor/skills/release/SKILL.md | 2 +- .github/scripts/release.rb | 88 +++++++++---------- .github/workflows/prepare-release.yml | 24 +----- .github/workflows/push_gem.yml | 120 +++++++++++++------------- CHANGELOG.md | 4 +- RELEASING.md | 10 ++- spec/release_script_spec.rb | 6 +- 7 files changed, 119 insertions(+), 135 deletions(-) diff --git a/.cursor/skills/release/SKILL.md b/.cursor/skills/release/SKILL.md index 687ac45..8de9888 100644 --- a/.cursor/skills/release/SKILL.md +++ b/.cursor/skills/release/SKILL.md @@ -37,7 +37,7 @@ Use this when the workflow cannot be started. Branch `release/X.Y.Z` from latest - `lib/ruby_proxy_headers/version.rb`, `VERSION = 'X.Y.Z'` - every `ruby-proxy-headers (X.Y.Z)` entry in `Gemfile.lock` -- move `## [Unreleased]` in `CHANGELOG.md` to `## [X.Y.Z] - YYYY-MM-DD`, and update the compare links +- move `## Unreleased` in `CHANGELOG.md` to `## X.Y.Z - YYYY-MM-DD`, and update the compare links Commit, push `release/X.Y.Z`, and open a pull request into `main` titled `Release X.Y.Z` whose body is that changelog section. diff --git a/.github/scripts/release.rb b/.github/scripts/release.rb index 0aa2cd7..dba03a9 100644 --- a/.github/scripts/release.rb +++ b/.github/scripts/release.rb @@ -13,8 +13,9 @@ class Error < StandardError def self.run(argv) case argv.first when 'bump' then bump(argv[1]) + when 'check' then check(argv[1]) when 'notes' then print notes(argv[1]) - else warn 'usage: release.rb bump SPEC|notes X.Y.Z' + else warn 'usage: release.rb bump SPEC|check [X.Y.Z]|notes X.Y.Z' exit 1 end rescue Error => e @@ -28,33 +29,49 @@ def self.bump(spec) write_version(version) write_lock(current, version) write_changelog(current, version, Time.now.utc.strftime('%Y-%m-%d')) - append_output(version) + path = ENV.fetch('GITHUB_OUTPUT', '') + File.open(path, 'a') { |file| file.puts "version=#{version}" } unless path.empty? + end + + def self.check(expected = nil) + version = read_version + assert_lock(version) + raise Error, "version is #{version}, expected #{expected}" unless expected.nil? || expected == version + + head = ENV.fetch('HEAD_REF') { ENV.fetch('GITHUB_HEAD_REF', '') } + assert_branch(head, version) + notes(version) if head.start_with?('release/') || expected + end + + def self.assert_branch(head, version) + return unless head.start_with?('release/') + + raise Error, "branch #{head} does not match #{version}" unless head == "release/#{version}" + end + + def self.assert_lock(version) + found = File.readlines('Gemfile.lock').filter_map { |line| line[/^\s*ruby-proxy-headers \(([^)]+)\)/, 1] } + raise Error, 'Gemfile.lock does not match version.rb' if found.empty? || found.uniq != [version] end def self.notes(version) raise Error, 'version must be X.Y.Z' unless version.to_s.match?(VERSION_RE) lines = File.readlines('CHANGELOG.md') - start = heading_index(lines, version) - raise Error, "CHANGELOG.md has no dated #{version} section" unless start + start = lines.index { |line| line.strip.match?(/\A## #{Regexp.escape(version)} - \d{4}-\d{2}-\d{2}\z/) } + raise Error, "CHANGELOG.md has no ## #{version} - YYYY-MM-DD section" unless start - slice_section(lines, start) + section_body(lines, start) end - def self.heading_index(lines, version) - pattern = /\A## \[#{Regexp.escape(version)}\] - \d{4}-\d{2}-\d{2}\z/ - lines.index { |line| line.strip.match?(pattern) } - end - - def self.slice_section(lines, start) + def self.section_body(lines, start) rest = lines[(start + 1)..] || [] - stop = rest.index { |line| line.start_with?('## ') || line.match?(/\A\[[^\]]+\]:/) } + stop = rest.index { |line| line.start_with?('## ') } "#{([lines[start]] + (stop ? rest[0...stop] : rest)).join.strip}\n" end def self.read_version - match = File.read(VERSION_FILE).match(/^\s*VERSION = ['"]([^'"]+)['"]/) - version = match && match[1] + version = File.read(VERSION_FILE)[/^\s*VERSION = ['"]([^'"]+)['"]/, 1] raise Error, 'version.rb has no MAJOR.MINOR.PATCH' unless version&.match?(VERSION_RE) version @@ -85,49 +102,32 @@ def self.write_version(version) end def self.write_lock(old_version, new_version) - count = 0 pattern = /^(\s*ruby-proxy-headers \()#{Regexp.escape(old_version)}(\).*)$/ - updated = File.read('Gemfile.lock').gsub(pattern) do - count += 1 - "#{Regexp.last_match(1)}#{new_version}#{Regexp.last_match(2)}" - end - raise Error, 'Gemfile.lock has no ruby-proxy-headers version' if count.zero? + original = File.read('Gemfile.lock') + updated = original.gsub(pattern) { "#{Regexp.last_match(1)}#{new_version}#{Regexp.last_match(2)}" } + raise Error, 'Gemfile.lock has no ruby-proxy-headers version' if updated == original File.write('Gemfile.lock', updated) end def self.write_changelog(old_version, version, date) - lines, start, finish = unreleased_span(File.read('CHANGELOG.md')) + lines, start, finish = unreleased_bounds body = lines[(start + 1)...finish].join.strip - heading = "## [Unreleased]\n\n## [#{version}] - #{date}\n" - heading = "#{heading}\n#{body}\n" unless body.empty? - lines[start...finish] = ["#{heading}\n"] - File.write('CHANGELOG.md', with_links(lines.join, old_version, version)) + lines[start...finish] = ["## Unreleased\n\n## #{version} - #{date}\n\n#{body}\n\n"] + repo = ENV.fetch('GITHUB_REPOSITORY', 'proxymesh/ruby-proxy-headers') + tail = "[#{version}]: https://github.com/#{repo}/compare/v#{old_version}...v#{version}" + text = lines.join.sub(/^\[Unreleased\]:.*$/, "[Unreleased]: https://github.com/#{repo}/compare/v#{version}...HEAD") + File.write('CHANGELOG.md', text.include?(tail) ? text : text.sub(/(\[Unreleased\]:.*\n)/, "\\1#{tail}\n")) end - def self.unreleased_span(text) - lines = text.lines - start = lines.index { |line| line.strip == '## [Unreleased]' } - raise Error, 'CHANGELOG.md has no ## [Unreleased] section' unless start + def self.unreleased_bounds + lines = File.read('CHANGELOG.md').lines + start = lines.index { |line| line.strip == '## Unreleased' } + raise Error, 'CHANGELOG.md has no ## Unreleased section' unless start offset = lines[(start + 1)..].index { |line| line.start_with?('## ') || line.match?(/\A\[[^\]]+\]:/) } [lines, start, offset ? start + 1 + offset : lines.size] end - - def self.with_links(text, old_version, version) - repo = ENV.fetch('GITHUB_REPOSITORY') - unreleased = "[Unreleased]: https://github.com/#{repo}/compare/v#{version}...HEAD" - current = "[#{version}]: https://github.com/#{repo}/compare/v#{old_version}...v#{version}" - text = text.sub(/^\[Unreleased\]:.*$/, unreleased) - return text if text.include?("#{current}\n") - - text.sub(/(\[Unreleased\]:.*\n)/, "\\1#{current}\n") - end - - def self.append_output(version) - path = ENV.fetch('GITHUB_OUTPUT', '') - File.open(path, 'a') { |file| file.puts "version=#{version}" } unless path.empty? - end end GemRelease.run(ARGV) if $PROGRAM_NAME == __FILE__ diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml index ab6268b..b5b65c0 100644 --- a/.github/workflows/prepare-release.yml +++ b/.github/workflows/prepare-release.yml @@ -52,26 +52,10 @@ jobs: RELEASE_SPEC: ${{ inputs.version }} run: ruby .github/scripts/release.rb bump "${RELEASE_SPEC}" - - name: Check version files + - name: Check version and changelog env: VERSION: ${{ steps.bump.outputs.version }} - run: | - set -euo pipefail - file_version="$(ruby -r ./lib/ruby_proxy_headers/version.rb -e 'puts RubyProxyHeaders::VERSION')" - if [[ "${VERSION}" != "${file_version}" ]]; then - echo "bumped ${VERSION} but version.rb is ${file_version}" >&2 - exit 1 - fi - lock="$(grep -E '^[[:space:]]*ruby-proxy-headers \([0-9]+\.[0-9]+\.[0-9]+\)' Gemfile.lock || true)" - if [[ -z "${lock}" ]] || grep -v "ruby-proxy-headers (${VERSION})" <<<"${lock}" | grep -q .; then - echo "Gemfile.lock does not match ${VERSION}" >&2 - exit 1 - fi - - - name: Check changelog - env: - VERSION: ${{ steps.bump.outputs.version }} - run: ruby .github/scripts/release.rb notes "${VERSION}" >/dev/null + run: ruby .github/scripts/release.rb check "${VERSION}" - name: Build gem env: @@ -91,10 +75,6 @@ jobs: run: | set -euo pipefail branch="release/${VERSION}" - if git ls-remote --exit-code origin "refs/heads/${branch}" >/dev/null 2>&1; then - echo "Branch ${branch} already exists." >&2 - exit 1 - fi git checkout -b "${branch}" git add lib/ruby_proxy_headers/version.rb Gemfile.lock CHANGELOG.md git commit -m "Release ${VERSION}" diff --git a/.github/workflows/push_gem.yml b/.github/workflows/push_gem.yml index 87c1e44..437f3a1 100644 --- a/.github/workflows/push_gem.yml +++ b/.github/workflows/push_gem.yml @@ -10,6 +10,10 @@ on: permissions: {} +concurrency: + group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.ref }} + cancel-in-progress: false + jobs: release-check: name: Release check @@ -30,128 +34,124 @@ jobs: bundler: none ruby-version: ruby - - name: Check version files - run: | - set -euo pipefail - version="$(ruby -r ./lib/ruby_proxy_headers/version.rb -e 'puts RubyProxyHeaders::VERSION')" - lock="$(grep -E '^[[:space:]]*ruby-proxy-headers \([0-9]+\.[0-9]+\.[0-9]+\)' Gemfile.lock || true)" - if [[ -z "${lock}" ]] || grep -v "ruby-proxy-headers (${version})" <<<"${lock}" | grep -q .; then - echo "Gemfile.lock does not match ${version}" >&2 - exit 1 - fi + - name: Check version and changelog + env: + HEAD_REF: ${{ github.head_ref }} + run: ruby .github/scripts/release.rb check - name: Build gem run: gem build ruby-proxy-headers.gemspec - - name: Check release branch - if: startsWith(github.head_ref, 'release/') - env: - HEAD_REF: ${{ github.head_ref }} - run: | - set -euo pipefail - version="${HEAD_REF#release/}" - file_version="$(ruby -r ./lib/ruby_proxy_headers/version.rb -e 'puts RubyProxyHeaders::VERSION')" - if [[ "${version}" != "${file_version}" ]]; then - echo "${HEAD_REF} does not match ${file_version}" >&2 - exit 1 - fi - ruby .github/scripts/release.rb notes "${version}" >/dev/null - - publish: + lookup: if: github.event_name == 'push' runs-on: ubuntu-24.04 - timeout-minutes: 20 - environment: release + timeout-minutes: 10 permissions: contents: read - id-token: write pull-requests: read + outputs: + version: ${{ steps.release.outputs.version }} steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - name: Release version + - name: Find the release pull request id: release env: GH_TOKEN: ${{ github.token }} run: | set -euo pipefail - version="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${GITHUB_SHA}/pulls" --jq '[.[] | select(.merged_at != null and .base.ref == "main" and (.head.ref | test("^release/[0-9]+\\.[0-9]+\\.[0-9]+$"))) | .head.ref] | if length == 0 then "" elif length == 1 then .[0][8:] else error("more than one release pull request") end')" - if [[ -z "${version}" ]]; then - echo "publish=false" >> "${GITHUB_OUTPUT}" + pulls="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${GITHUB_SHA}/pulls")" + mapfile -t refs < <( + jq -r --arg repo "$GITHUB_REPOSITORY" ' + .[] + | select( + .base.ref == "main" + and .merged_at != null + and (.head.ref | test("^release/[0-9]+\\.[0-9]+\\.[0-9]+$")) + and .head.repo.full_name == $repo + ) + | .head.ref + ' <<<"$pulls" + ) + if [ "${#refs[@]}" -eq 0 ]; then + echo "Not a release merge." exit 0 fi - echo "publish=true" >> "${GITHUB_OUTPUT}" - echo "version=${version}" >> "${GITHUB_OUTPUT}" + if [ "${#refs[@]}" -ne 1 ]; then + echo "This commit matches more than one release pull request." >&2 + exit 1 + fi + version="${refs[0]#release/}" + echo "version=${version}" >> "$GITHUB_OUTPUT" + + publish: + needs: lookup + if: needs.lookup.outputs.version != '' + runs-on: ubuntu-24.04 + timeout-minutes: 20 + environment: release + permissions: + contents: read + id-token: write + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Set up Ruby - if: steps.release.outputs.publish == 'true' uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199 # v1.338.0 with: bundler: none ruby-version: ruby + - name: Check version and changelog + env: + HEAD_REF: release/${{ needs.lookup.outputs.version }} + run: ruby .github/scripts/release.rb check + - name: Build gem - if: steps.release.outputs.publish == 'true' run: gem build ruby-proxy-headers.gemspec - name: Configure RubyGems credentials - if: steps.release.outputs.publish == 'true' uses: rubygems/configure-rubygems-credentials@dc5a8d8553e6ee01fc26761a49e99e733d17954a # v2.1.0 - name: Push gem - if: steps.release.outputs.publish == 'true' env: - VERSION: ${{ steps.release.outputs.version }} + VERSION: ${{ needs.lookup.outputs.version }} run: gem push "ruby-proxy-headers-${VERSION}.gem" github-release: - needs: publish - if: github.event_name == 'push' && needs.publish.result == 'success' + needs: [lookup, publish] + if: needs.lookup.outputs.version != '' && needs.publish.result == 'success' runs-on: ubuntu-24.04 timeout-minutes: 10 permissions: contents: write - pull-requests: read steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - name: Release version - id: release - env: - GH_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - version="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${GITHUB_SHA}/pulls" --jq '[.[] | select(.merged_at != null and .base.ref == "main" and (.head.ref | test("^release/[0-9]+\\.[0-9]+\\.[0-9]+$"))) | .head.ref] | if length == 0 then "" elif length == 1 then .[0][8:] else error("more than one release pull request") end')" - if [[ -z "${version}" ]]; then - echo "publish=false" >> "${GITHUB_OUTPUT}" - exit 0 - fi - echo "publish=true" >> "${GITHUB_OUTPUT}" - echo "version=${version}" >> "${GITHUB_OUTPUT}" - - name: Set up Ruby - if: steps.release.outputs.publish == 'true' uses: ruby/setup-ruby@b3aaceaef7e0ee231b499e7b5f49c03fc1d32199 # v1.338.0 with: bundler: none ruby-version: ruby - name: Create GitHub Release - if: steps.release.outputs.publish == 'true' env: - VERSION: ${{ steps.release.outputs.version }} GH_TOKEN: ${{ github.token }} + VERSION: ${{ needs.lookup.outputs.version }} run: | set -euo pipefail ruby .github/scripts/release.rb notes "${VERSION}" > "${RUNNER_TEMP}/notes.md" - gh release view "v${VERSION}" --repo "${GITHUB_REPOSITORY}" \ + gh release view "v${VERSION}" \ || gh release create "v${VERSION}" \ - --repo "${GITHUB_REPOSITORY}" \ + --target "$GITHUB_SHA" \ --title "v${VERSION}" \ --notes-file "${RUNNER_TEMP}/notes.md" diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b14f78..4d338d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,13 +5,13 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## Unreleased ### Changed - Require Ruby >= 3.2. Dependabot resolves Bundler updates against the gemspec floor, and Ruby 3.1 cannot select nokogiri 1.19 (the release line that installs on the integration job's current Ruby). -## [0.1.0] - 2024-02-28 +## 0.1.0 - 2024-02-28 ### Added diff --git a/RELEASING.md b/RELEASING.md index 2ab126c..a3c825b 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -7,7 +7,7 @@ 3. The workflow bumps the version, moves the changelog section, runs the release checks, and opens a pull request titled `Release X.Y.Z`. It does not auto-merge. 4. Merge that pull request when you are ready. -Opening the pull request by hand still works. From an up-to-date `main`, bump every version manifest, move `## [Unreleased]` in `CHANGELOG.md` to `## [X.Y.Z] - YYYY-MM-DD`, and open a pull request titled `Release X.Y.Z` whose body is that changelog section. Do not auto-merge. +Opening the pull request by hand still works. From an up-to-date `main`, bump every version manifest, move `## Unreleased` in `CHANGELOG.md` to `## X.Y.Z - YYYY-MM-DD`, and open a pull request titled `Release X.Y.Z` whose body is that changelog section. Do not auto-merge. Version manifests: @@ -26,11 +26,13 @@ A pull request opened with `GITHUB_TOKEN` does not run `pull_request` workflows, ### Release check -`.github/workflows/push_gem.yml` runs **Release check** on pull requests into `main`. It checks that `version.rb` and `Gemfile.lock` agree and runs `gem build`. On a `release/X.Y.Z` pull request it also checks that `X.Y.Z` matches those files and that `CHANGELOG.md` has a `## [X.Y.Z] - YYYY-MM-DD` section. +`.github/workflows/push_gem.yml` runs **Release check** on pull requests into `main`. It checks that `version.rb` and `Gemfile.lock` agree and runs `gem build`. On a `release/X.Y.Z` pull request it also checks that the branch name matches the version and that `CHANGELOG.md` has a `## X.Y.Z - YYYY-MM-DD` section. + +Don't make **Release check** a required check: release pull requests are opened with `GITHUB_TOKEN`, so it doesn't run on them unless you close and reopen the PR. ### Publish -A push to `main` runs **publish** and **github-release** in `.github/workflows/push_gem.yml`. Each job looks up the pull request for that commit and does nothing when it is not a merged `release/X.Y.Z` pull request. +A push to `main` runs **lookup** in `.github/workflows/push_gem.yml`. It reads the pull request for that commit. When that pull request was merged from the same repository, targets `main`, and its branch is `release/X.Y.Z`, **publish** and **github-release** run. Otherwise they are skipped, and the `release` environment is not used. **publish** uses the GitHub environment `release`. It builds the gem and pushes it with `gem push` after `rubygems/configure-rubygems-credentials`. A version already on RubyGems fails the push. **github-release** then runs `gh release view` or `gh release create` with the changelog section as the notes. @@ -40,7 +42,7 @@ The workflow filename stays `push_gem.yml` so the existing trusted publisher kee Do this once, before the next release. This change does not modify repository or RubyGems settings. -1. Create a GitHub environment named `release` (**Settings → Environments**). Add required reviewers so the publish job waits for approval. It does not need secrets. +1. Create a GitHub environment named `release` (**Settings → Environments**). Required reviewers are optional. It does not need secrets. 2. On the `ruby-proxy-headers` trusted publisher, set the GitHub environment to `release`. Keep the repository `proxymesh/ruby-proxy-headers` and the workflow filename `push_gem.yml`. A publisher with a blank environment will reject the next push until it matches. If the environment cannot be edited, create a publisher with those values and remove the old one. 3. Publishing uses OpenID Connect. No RubyGems API token is read from the workflow. After a publish succeeds, delete any leftover RubyGems token from repository or environment secrets. 4. **Prepare release** opens the pull request as `github-actions[bot]`. Actions workflow permissions need read and write access, and **Allow GitHub Actions to create and approve pull requests** should stay enabled. diff --git a/spec/release_script_spec.rb b/spec/release_script_spec.rb index ebae864..5478859 100644 --- a/spec/release_script_spec.rb +++ b/spec/release_script_spec.rb @@ -11,7 +11,7 @@ FileUtils.mkdir_p("#{dir}/lib/ruby_proxy_headers") File.write("#{dir}/lib/ruby_proxy_headers/version.rb", "module RubyProxyHeaders\n VERSION = '0.2.3'\nend\n") File.write("#{dir}/Gemfile.lock", " ruby-proxy-headers (0.2.3)\n") - File.write("#{dir}/CHANGELOG.md", "## [Unreleased]\n\n- Note\n\n## [0.1.0] - 2024-02-28\n\n[Unreleased]: https://github.com/proxymesh/ruby-proxy-headers/compare/v0.1.0...HEAD\n") + File.write("#{dir}/CHANGELOG.md", "## Unreleased\n\n- Note\n\n## 0.1.0 - 2024-02-28\n\n[Unreleased]: https://github.com/proxymesh/ruby-proxy-headers/compare/v0.1.0...HEAD\n") script = File.expand_path('../.github/scripts/release.rb', __dir__) env = { 'GITHUB_REPOSITORY' => 'proxymesh/ruby-proxy-headers' } _output, status = Open3.capture2e(env, 'ruby', script, 'bump', 'patch', chdir: dir) @@ -19,7 +19,9 @@ expect(File.read("#{dir}/lib/ruby_proxy_headers/version.rb")).to include("VERSION = '0.2.4'") notes, notes_status = Open3.capture2e(env, 'ruby', script, 'notes', '0.2.4', chdir: dir) expect(notes_status).to be_success - expect(notes).to include('## [0.2.4] - ') + expect(notes).to include('## 0.2.4 - ') + _checked, check_status = Open3.capture2e(env, 'ruby', script, 'check', '0.2.4', chdir: dir) + expect(check_status).to be_success expect(notes).to include('- Note') end end From 9b9972d2771823c1c87eadc298241cbab1619258 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 12 Nov 2026 22:45:48 +0000 Subject: [PATCH 4/7] Stop rewriting unused changelog footer links. Headings stay unbracketed, and the unit and integration jobs get a 15 minute timeout. Co-authored-by: ProxyMesh AI --- .cursor/skills/release/SKILL.md | 2 +- .github/scripts/release.rb | 11 ++++------- .github/workflows/proxy_integration_tests.yml | 1 + .github/workflows/unit_tests.yml | 1 + CHANGELOG.md | 3 --- spec/release_script_spec.rb | 3 ++- 6 files changed, 9 insertions(+), 12 deletions(-) diff --git a/.cursor/skills/release/SKILL.md b/.cursor/skills/release/SKILL.md index 8de9888..394ecbf 100644 --- a/.cursor/skills/release/SKILL.md +++ b/.cursor/skills/release/SKILL.md @@ -37,7 +37,7 @@ Use this when the workflow cannot be started. Branch `release/X.Y.Z` from latest - `lib/ruby_proxy_headers/version.rb`, `VERSION = 'X.Y.Z'` - every `ruby-proxy-headers (X.Y.Z)` entry in `Gemfile.lock` -- move `## Unreleased` in `CHANGELOG.md` to `## X.Y.Z - YYYY-MM-DD`, and update the compare links +- move `## Unreleased` in `CHANGELOG.md` to `## X.Y.Z - YYYY-MM-DD` Commit, push `release/X.Y.Z`, and open a pull request into `main` titled `Release X.Y.Z` whose body is that changelog section. diff --git a/.github/scripts/release.rb b/.github/scripts/release.rb index dba03a9..4a1d20e 100644 --- a/.github/scripts/release.rb +++ b/.github/scripts/release.rb @@ -28,7 +28,7 @@ def self.bump(spec) version = next_version(current, spec.to_s.strip) write_version(version) write_lock(current, version) - write_changelog(current, version, Time.now.utc.strftime('%Y-%m-%d')) + write_changelog(version, Time.now.utc.strftime('%Y-%m-%d')) path = ENV.fetch('GITHUB_OUTPUT', '') File.open(path, 'a') { |file| file.puts "version=#{version}" } unless path.empty? end @@ -110,14 +110,11 @@ def self.write_lock(old_version, new_version) File.write('Gemfile.lock', updated) end - def self.write_changelog(old_version, version, date) + def self.write_changelog(version, date) lines, start, finish = unreleased_bounds body = lines[(start + 1)...finish].join.strip lines[start...finish] = ["## Unreleased\n\n## #{version} - #{date}\n\n#{body}\n\n"] - repo = ENV.fetch('GITHUB_REPOSITORY', 'proxymesh/ruby-proxy-headers') - tail = "[#{version}]: https://github.com/#{repo}/compare/v#{old_version}...v#{version}" - text = lines.join.sub(/^\[Unreleased\]:.*$/, "[Unreleased]: https://github.com/#{repo}/compare/v#{version}...HEAD") - File.write('CHANGELOG.md', text.include?(tail) ? text : text.sub(/(\[Unreleased\]:.*\n)/, "\\1#{tail}\n")) + File.write('CHANGELOG.md', lines.join) end def self.unreleased_bounds @@ -125,7 +122,7 @@ def self.unreleased_bounds start = lines.index { |line| line.strip == '## Unreleased' } raise Error, 'CHANGELOG.md has no ## Unreleased section' unless start - offset = lines[(start + 1)..].index { |line| line.start_with?('## ') || line.match?(/\A\[[^\]]+\]:/) } + offset = lines[(start + 1)..].index { |line| line.start_with?('## ') } [lines, start, offset ? start + 1 + offset : lines.size] end end diff --git a/.github/workflows/proxy_integration_tests.yml b/.github/workflows/proxy_integration_tests.yml index 2b37ed4..6ebd03d 100644 --- a/.github/workflows/proxy_integration_tests.yml +++ b/.github/workflows/proxy_integration_tests.yml @@ -14,6 +14,7 @@ permissions: jobs: integration: runs-on: ubuntu-24.04 + timeout-minutes: 15 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/.github/workflows/unit_tests.yml b/.github/workflows/unit_tests.yml index 8361b4c..4a4dedf 100644 --- a/.github/workflows/unit_tests.yml +++ b/.github/workflows/unit_tests.yml @@ -9,6 +9,7 @@ permissions: jobs: rspec: runs-on: ubuntu-24.04 + timeout-minutes: 15 strategy: matrix: diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d338d4..0e315d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,3 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `RestClient` module for RestClient integration - Comprehensive documentation - Test suite with RSpec - -[Unreleased]: https://github.com/proxymeshai/ruby-proxy-headers/compare/v0.1.0...HEAD -[0.1.0]: https://github.com/proxymeshai/ruby-proxy-headers/releases/tag/v0.1.0 diff --git a/spec/release_script_spec.rb b/spec/release_script_spec.rb index 5478859..94d962b 100644 --- a/spec/release_script_spec.rb +++ b/spec/release_script_spec.rb @@ -11,7 +11,7 @@ FileUtils.mkdir_p("#{dir}/lib/ruby_proxy_headers") File.write("#{dir}/lib/ruby_proxy_headers/version.rb", "module RubyProxyHeaders\n VERSION = '0.2.3'\nend\n") File.write("#{dir}/Gemfile.lock", " ruby-proxy-headers (0.2.3)\n") - File.write("#{dir}/CHANGELOG.md", "## Unreleased\n\n- Note\n\n## 0.1.0 - 2024-02-28\n\n[Unreleased]: https://github.com/proxymesh/ruby-proxy-headers/compare/v0.1.0...HEAD\n") + File.write("#{dir}/CHANGELOG.md", "## Unreleased\n\n- Note\n\n## 0.1.0 - 2024-02-28\n") script = File.expand_path('../.github/scripts/release.rb', __dir__) env = { 'GITHUB_REPOSITORY' => 'proxymesh/ruby-proxy-headers' } _output, status = Open3.capture2e(env, 'ruby', script, 'bump', 'patch', chdir: dir) @@ -23,6 +23,7 @@ _checked, check_status = Open3.capture2e(env, 'ruby', script, 'check', '0.2.4', chdir: dir) expect(check_status).to be_success expect(notes).to include('- Note') + expect(File.read("#{dir}/CHANGELOG.md")).not_to include('[0.2.4]:') end end end From 972a6e95ce68ef3ff47951eb1e0682b975c8d7d0 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 12 Nov 2026 23:51:10 +0000 Subject: [PATCH 5/7] Publish without a GitHub release environment. Drop the publish job environment key and document a blank trusted publisher environment field. Co-authored-by: ProxyMesh AI --- .github/workflows/push_gem.yml | 1 - RELEASING.md | 11 +++++------ 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/.github/workflows/push_gem.yml b/.github/workflows/push_gem.yml index 437f3a1..0b216ae 100644 --- a/.github/workflows/push_gem.yml +++ b/.github/workflows/push_gem.yml @@ -92,7 +92,6 @@ jobs: if: needs.lookup.outputs.version != '' runs-on: ubuntu-24.04 timeout-minutes: 20 - environment: release permissions: contents: read id-token: write diff --git a/RELEASING.md b/RELEASING.md index a3c825b..74886ef 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -32,9 +32,9 @@ Don't make **Release check** a required check: release pull requests are opened ### Publish -A push to `main` runs **lookup** in `.github/workflows/push_gem.yml`. It reads the pull request for that commit. When that pull request was merged from the same repository, targets `main`, and its branch is `release/X.Y.Z`, **publish** and **github-release** run. Otherwise they are skipped, and the `release` environment is not used. +A push to `main` runs **lookup** in `.github/workflows/push_gem.yml`. It reads the pull request for that commit. When that pull request was merged from the same repository, targets `main`, and its branch is `release/X.Y.Z`, **publish** and **github-release** run. Otherwise they are skipped. -**publish** uses the GitHub environment `release`. It builds the gem and pushes it with `gem push` after `rubygems/configure-rubygems-credentials`. A version already on RubyGems fails the push. **github-release** then runs `gh release view` or `gh release create` with the changelog section as the notes. +**publish** builds the gem and pushes it with `gem push` after `rubygems/configure-rubygems-credentials`. A version already on RubyGems fails the push. **github-release** then runs `gh release view` or `gh release create` with the changelog section as the notes. The workflow filename stays `push_gem.yml` so the existing trusted publisher keeps matching. @@ -42,10 +42,9 @@ The workflow filename stays `push_gem.yml` so the existing trusted publisher kee Do this once, before the next release. This change does not modify repository or RubyGems settings. -1. Create a GitHub environment named `release` (**Settings → Environments**). Required reviewers are optional. It does not need secrets. -2. On the `ruby-proxy-headers` trusted publisher, set the GitHub environment to `release`. Keep the repository `proxymesh/ruby-proxy-headers` and the workflow filename `push_gem.yml`. A publisher with a blank environment will reject the next push until it matches. If the environment cannot be edited, create a publisher with those values and remove the old one. -3. Publishing uses OpenID Connect. No RubyGems API token is read from the workflow. After a publish succeeds, delete any leftover RubyGems token from repository or environment secrets. -4. **Prepare release** opens the pull request as `github-actions[bot]`. Actions workflow permissions need read and write access, and **Allow GitHub Actions to create and approve pull requests** should stay enabled. +1. On the `ruby-proxy-headers` trusted publisher, leave the GitHub environment field blank. Keep the repository `proxymesh/ruby-proxy-headers` and the workflow filename `push_gem.yml`. If the environment cannot be edited, create a publisher with those values and remove the old one. +2. Publishing uses OpenID Connect. No RubyGems API token is read from the workflow. After a publish succeeds, delete any leftover RubyGems token from repository secrets. +3. **Prepare release** opens the pull request as `github-actions[bot]`. Actions workflow permissions need read and write access, and **Allow GitHub Actions to create and approve pull requests** should stay enabled. ## Tags From cc3c679bcf736e692c9279ccac15133e60176ef1 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 13 Nov 2026 00:13:58 +0000 Subject: [PATCH 6/7] Clarify trusted publisher confirmation in RELEASING.md. Step 1 assumes the publisher already exists and describes how to verify or fix its environment field. Co-authored-by: ProxyMesh AI --- RELEASING.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/RELEASING.md b/RELEASING.md index 74886ef..be89eca 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -42,7 +42,10 @@ The workflow filename stays `push_gem.yml` so the existing trusted publisher kee Do this once, before the next release. This change does not modify repository or RubyGems settings. -1. On the `ruby-proxy-headers` trusted publisher, leave the GitHub environment field blank. Keep the repository `proxymesh/ruby-proxy-headers` and the workflow filename `push_gem.yml`. If the environment cannot be edited, create a publisher with those values and remove the old one. +1. Confirm the existing `ruby-proxy-headers` trusted publisher has repository + `proxymesh/ruby-proxy-headers`, workflow `push_gem.yml`, and a blank GitHub + environment. If its environment is set, edit it to blank; if it cannot be + edited, create a publisher with those values and remove the old one. 2. Publishing uses OpenID Connect. No RubyGems API token is read from the workflow. After a publish succeeds, delete any leftover RubyGems token from repository secrets. 3. **Prepare release** opens the pull request as `github-actions[bot]`. Actions workflow permissions need read and write access, and **Allow GitHub Actions to create and approve pull requests** should stay enabled. From ef336296bf77e76df2a9f3ddfef0c2c649ec2fe2 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 13 Nov 2026 00:16:34 +0000 Subject: [PATCH 7/7] Drop RubyGems owner setup from RELEASING.md. Trusted publishing is unchanged; the doc keeps only the Actions PR permission note. Co-authored-by: ProxyMesh AI --- RELEASING.md | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/RELEASING.md b/RELEASING.md index be89eca..49581ca 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -36,18 +36,13 @@ A push to `main` runs **lookup** in `.github/workflows/push_gem.yml`. It reads t **publish** builds the gem and pushes it with `gem push` after `rubygems/configure-rubygems-credentials`. A version already on RubyGems fails the push. **github-release** then runs `gh release view` or `gh release create` with the changelog section as the notes. -The workflow filename stays `push_gem.yml` so the existing trusted publisher keeps matching. +The workflow filename stays `push_gem.yml`. ## One-time owner setup -Do this once, before the next release. This change does not modify repository or RubyGems settings. - -1. Confirm the existing `ruby-proxy-headers` trusted publisher has repository - `proxymesh/ruby-proxy-headers`, workflow `push_gem.yml`, and a blank GitHub - environment. If its environment is set, edit it to blank; if it cannot be - edited, create a publisher with those values and remove the old one. -2. Publishing uses OpenID Connect. No RubyGems API token is read from the workflow. After a publish succeeds, delete any leftover RubyGems token from repository secrets. -3. **Prepare release** opens the pull request as `github-actions[bot]`. Actions workflow permissions need read and write access, and **Allow GitHub Actions to create and approve pull requests** should stay enabled. +**Prepare release** opens the pull request as `github-actions[bot]`. Actions +workflow permissions need read and write access, and **Allow GitHub Actions to +create and approve pull requests** should stay enabled. ## Tags