From 761e593d5a75d60b7305c7ef9c2c79158c699b73 Mon Sep 17 00:00:00 2001 From: "Daniel (dB.) Doubrovkine" Date: Fri, 20 Nov 2026 23:41:42 -0500 Subject: [PATCH] Rewrite the documentation in plain language Rewrite the README, user guide, workflow and component references, and project docs in short, direct sentences, with numbered steps for procedures and lists for parallel facts. Explain or replace internal jargon, and give each repeated rule one home: rerun and recovery rules in RELEASING, contributor commands and tests in CONTRIBUTING, design rationale in DESIGN, and agent rules in AGENTS, with links elsewhere. Fix statements the code contradicts, a broken README anchor, and the self-release example's missing dry-run input. Headings other pages link to are unchanged. CHANGELOG and UPGRADING are left as historical records. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011Gr21hZDQo5axDMuFgzL6s --- AGENTS.md | 47 ++++---- CHANGELOG.md | 1 + CONTRIBUTING.md | 78 ++++++++++--- DESIGN.md | 78 +++++-------- README.md | 80 +++++++------ RELEASING.md | 67 +++++------ docs/actions/action.md | 39 +++---- docs/actions/release.md | 129 +++++++++++---------- docs/changelog/base.md | 22 ++-- docs/changelog/intridea.md | 26 ++--- docs/changelog/keep_a_changelog.md | 26 ++--- docs/changelog/notes.md | 10 +- docs/destination.md | 20 ++-- docs/destination/ruby_gems.md | 14 +-- docs/execution_context.md | 32 +++-- docs/execution_context/github.md | 12 +- docs/execution_provider.md | 24 ++-- docs/execution_provider/github.md | 10 +- docs/hosting/github_release.md | 20 ++-- docs/markdown.md | 12 +- docs/package/collection.md | 14 ++- docs/package/ruby_gem.md | 31 +++-- docs/release.md | 18 +-- docs/source_control/git.md | 26 ++--- docs/tasks.md | 72 ++++++++---- docs/testing.md | 58 +++++---- docs/usage.md | 102 ++++++++-------- docs/version/plain_text.md | 6 +- docs/version/references.md | 10 +- docs/version/ruby_constant.md | 16 +-- docs/workflow/environment.md | 23 ++-- docs/workflow/hooks.md | 48 +++++--- docs/workflow/reviewed_ruby_gem.md | 37 ++++-- docs/workflow/ruby_gem.md | 41 ++++--- docs/workflow/ruby_gems_credentials.md | 39 +++++-- docs/workflow/semantic_ruby_gem.md | 57 +++++---- examples/gitlab_semantic_release/README.md | 40 ++++--- examples/lifecycle_hooks/README.md | 6 +- examples/self_release/README.md | 33 +++--- 39 files changed, 799 insertions(+), 625 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f150e94..f6eb5b1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,25 +1,26 @@ # Working on `ruby-gem-release` -Read [CONTRIBUTING.md](CONTRIBUTING.md) and [DESIGN.md](DESIGN.md). This project provides GitHub Actions interfaces and Ruby release tasks, not a general-purpose release service. - -Every release action and callback must be idempotent for the same checkout and inputs. Reconcile its own outputs: rebuild reproducibly, accept published gems only on matching checksums, preserve immutable Git tags, and replace mutable hosted notes/assets. Test accepted-but-response-lost outcomes. Preserve artifacts before publication for manual inspection; do not introduce recovery flags, artifact discovery, state restoration, or a completion journal. - -The reusable workflow belongs in `.github/workflows/`, the gem API and Rake tasks belong in `lib/` and `tasks/`, and focused RSpec examples belong in `spec/`. Support Ruby 3.3 and newer; use public RubyGems, Rake, GitHub Actions, and RubyGems Trusted Publishing interfaces. - -Keep release orchestration reusable while leaving project-specific preparation and version bump commands configurable by the calling repository. Test task behavior with focused unit tests and execute both interfaces' callback commands in real consumers with local Git remotes and isolated package and hosting publication. Consumer tests do not validate live Actions authentication or artifact uploads; never dispatch a publishing workflow from PR CI. - -Keep orchestration permutations and YAML assertions in focused source specs (`bundle exec rake spec:unit`). Keep real-process smoke coverage in `spec/integration/`, including the portable consumers; do not stub their transport or installed-gem loading. CI runs source tests and installed-gem integration separately, without repeating the full integration suite against source. Profile before and after changes to the harness instead of assuming a speedup. - -Keep semantic releases opt-in. Calculate from reachable released tags, not development versions; persist one immutable decision across processes, preserve it when recording the next version, and never reanalyze during preparation or publication. Preserve manual workflow defaults and publication guards. Semantic consumer fixtures must verify success, publication failure, and empty-release rejection against the installed artifact without real publication. - -The root `action.yml` exposes the same Ruby tasks as a composite action. Keep both interfaces consistent without making version-pinned workflows depend on moving action references: pin every external action and reusable workflow to a full commit SHA with its version as a trailing comment, never a tag or branch. Action callers own job permissions, runner, environment, and concurrency. Preserve authentication selection and failure-aware artifact preservation; run installed-artifact consumer CI and `actionlint .github/workflows/*.yml examples/.github/workflows/*.yml` when changing YAML interfaces. - -Run `bundle exec rake` locally for specs and RuboCop before every push, and `bundle exec rake build` for package construction when applicable. Danger checks the changelog in PR CI, not as a routine local command. Document user-visible changes in `CHANGELOG.md`, listing entries within each release chronologically and keeping `- Your contribution here.` as the last entry in the next-release section; keep Markdown paragraphs on one source line. - -The normal RuboCop command checks prose, Markdown Ruby examples, spelling, and YAML through `rubocop-prose`, `rubocop-md`, `rubocop-spellcheck`, and `rubocop-yaml`. Fix typos rather than suppressing checks; keep reviewed project vocabulary in `.spellcheck.txt` alongside the bundled English dictionary. - -Preserve the logo asset and its provenance, README placement, and rendering checks described in [DESIGN.md](DESIGN.md). - -Preserve unrelated worktree changes. Use a separate worktree for each PR with a `dblock/` branch from `master`, keeping the primary checkout on `master` when clean. Keep one coherent commit per PR; amend it when making updates and use `git push --force-with-lease` for the topic branch when needed. Use squash or rebase merges, not merge commits. Ordinary development changes require PRs; explicitly authorized release automation may push release preparation and next development iteration commits directly without PRs. Never force-push to `master`. Do not merge, publish, or create release tags without authorization. - -After a PR merges, clean up its local worktree and branch when no longer needed: verify the merged PR, inspect for uncommitted changes and dependent work, remove only clean worktrees, and delete the branch only when no work would be lost. Never discard changes to perform cleanup. +Read [CONTRIBUTING.md](CONTRIBUTING.md) for setup, commands, tests, and PR rules, and [DESIGN.md](DESIGN.md) for the design. This project provides GitHub Actions interfaces and Ruby release tasks, not a general-purpose release service. + +## Rules to Keep + +Do not break these: + +- The reusable workflow lives in `.github/workflows/`, the gem API and Rake tasks in `lib/` and `tasks/`, and specs in `spec/`. The root `action.yml` exposes the same tasks as a composite action. +- Support Ruby 3.3 and newer. Use only public RubyGems, Rake, GitHub Actions, and Trusted Publishing interfaces. +- Keep orchestration reusable; calling repositories configure their own preparation and version bump commands. +- Every release action and callback follows the [rerun rules](RELEASING.md#verify-and-recover). Do not add recovery flags, artifact discovery, state restoration, or a completion journal. +- Keep semantic releases opt-in. Versions come from reachable release tags, not development versions. Record one immutable decision, keep it when recording the next version, and never reanalyze during preparation or publication. +- Keep the manual workflow defaults and publication guards unchanged. +- Keep the reusable workflow and composite action consistent. Pin every external action and reusable workflow to a full commit SHA with a trailing version comment, never a tag or branch. +- Keep authentication selection and artifact upload on failure working. +- Do not stub environment exports or installed-gem loading in the portable consumer specs. +- Profile the test harness before and after changing it; do not assume a speedup. +- Keep the logo, its provenance, and its README placement as described in [DESIGN.md](DESIGN.md#self-release-and-artwork). + +## Safety + +- Never dispatch a publishing workflow from PR CI. +- Do not merge, publish, or create release tags without authorization. +- Never force-push `master`. +- Preserve unrelated worktree changes, and never discard changes to clean up. diff --git a/CHANGELOG.md b/CHANGELOG.md index 66684d4..cea2acf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ - [#91](https://github.com/dblock/ruby-gem-release/pull/91): Accept an Intridea Next section with release notes but no contribution placeholder, rejecting a placeholder marked differently from the configured one - [@dblock](https://github.com/dblock). - [#92](https://github.com/dblock/ruby-gem-release/pull/92): Document manual recovery from the preserved bundle when the default branch advances during publication - [@dblock](https://github.com/dblock). - [#93](https://github.com/dblock/ruby-gem-release/pull/93): Document disabling the local Bundler `release` tasks so the workflow is the only release path - [@dblock](https://github.com/dblock). +- [#95](https://github.com/dblock/ruby-gem-release/pull/95): Rewrite the documentation in plain language, consolidating repeated rules so each lives in one place - [@dblock](https://github.com/dblock). - Your contribution here. ## 0.9.0 (2026/11/20) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5901191..d743293 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,37 +1,83 @@ # Contributing -Create a topic branch from `master` and keep each pull request focused on one coherent change. +Make one focused change per pull request. -Use a separate worktree for each PR with a `dblock/` branch, keeping the primary checkout on `master` when clean. Ordinary development changes go through PRs. Authorized release automation is an exception: release preparation and next development iteration commits may be pushed directly without PRs. The default-branch ruleset blocks force pushes and deletion but does not enforce PRs, allowing release automation and other writers to make fast-forward pushes. - -After a PR merges, verify its merged state and check for uncommitted changes and dependent work before removing its clean, unneeded worktree and local branch. Do not discard work to clean up. +- Use a separate worktree for each PR, on a `dblock/` branch from `master`. Keep the primary checkout on `master` when it is clean. +- Ordinary changes go through PRs. Only authorized release automation pushes directly, for release and next development commits. The default-branch ruleset blocks force pushes and deletion but does not require PRs, so release automation and other writers can push fast-forward commits. +- After a PR merges, confirm it merged and check for uncommitted changes and dependent work. Then remove the clean worktree and local branch. Never discard work to clean up. ## Setup and Validation -Ruby 3.3 or newer is supported. Install dependencies with `bundle install`, run the specs and RuboCop locally with `bundle exec rake` before every push, and construct the gem with `bundle exec rake build` when applicable. Danger checks the changelog in PR CI rather than as a routine local command. +Ruby 3.3 or newer is supported. + +```sh +bundle install +bundle exec rake +bundle exec rake build +``` + +`bundle exec rake` runs the specs and RuboCop; run it before every push. `bundle exec rake build` builds the gem when packaging changes. Danger checks the changelog in PR CI; you do not run it locally. -RuboCop includes Markdown prose checks with `rubocop-prose`, Ruby code block checks with `rubocop-md`, spelling checks with `rubocop-spellcheck`, and YAML checks with `rubocop-yaml`. Keep paragraphs on one source line, fix spelling mistakes, and add reviewed project vocabulary to `.spellcheck.txt`. Repository spelling checks cover comments and documentation, not Ruby strings; the standard license text is excluded from spelling and paragraph-length checks. +RuboCop also checks documentation and YAML: -Danger uses the reusable [danger-pr-comment](https://github.com/danger/danger-pr-comment) workflows. The read-only pull request job checks out full history and uses the default `danger dry_run` command, exporting a report instead of posting comments. A separate `workflow_run` job posts the report without checking out or executing contribution code. It does not create a comment for an empty report, but always updates an existing report comment. Keep full history available for fork commits and their merge base; the commenting workflow must be on `master` before it can respond to completed runs. +- `rubocop-prose` checks Markdown prose. +- `rubocop-md` checks Ruby code blocks in Markdown. +- `rubocop-spellcheck` checks spelling in comments and documentation, not Ruby strings. +- `rubocop-yaml` checks YAML. + +Keep each paragraph on one source line. Fix spelling mistakes; add only reviewed project words to `.spellcheck.txt`. The license text is excluded from spelling and paragraph-length checks. + +Danger runs through the reusable [danger-pr-comment](https://github.com/danger/danger-pr-comment) workflows. A read-only PR job checks out full history and runs `danger dry_run`, which saves a report instead of commenting. A separate `workflow_run` job posts the report without checking out or running contributed code. It skips empty reports but always updates an existing report comment. Keep full history so fork commits and their merge base are available. The commenting workflow only responds once it is on `master`. ## Tests -Idempotence is required for every release action, including custom callbacks. Reconcile each task's own outputs using its current checkout and inputs; replace mutable outputs, but reject immutable checksum or tag conflicts. Cover response-lost success, repetition, and conflicts. Do not add recovery flags, artifact discovery, state restoration, or a completion journal. +Every release action must follow the [rerun rules](RELEASING.md#verify-and-recover). Test success with a lost response, reruns, and checksum or tag conflicts. + +Specs live in `spec/`. Add focused specs for task behavior, and use real consumer projects to run the commands of the reusable workflow and composite action. Coverage reports (HTML and LCOV) go to `coverage/`, and CI uploads them to Coveralls. -RSpec examples live in `spec/`; add focused examples for release-task behavior and use real consumers to execute the reusable workflow and composite action's callback commands. Specs write HTML and LCOV coverage reports under `coverage/`, which CI uploads to Coveralls. +| Command | Runs | +| --- | --- | +| `bundle exec rake spec:unit` | Source specs, excluding `spec/integration/`. Run by the Test workflow. | +| `bundle exec rake spec:integration` | Consumer integration specs. CI runs them on the installed gem. | +| `bundle exec rake spec` | The full suite, in parallel. | +| `bundle exec rake spec:serial` | The full suite, serially. | +| `bundle exec rake` | The full suite plus RuboCop. | -Run focused source tests with `bundle exec rake spec:unit`, which excludes `spec/integration/`. This includes in-process Rake coverage of documented configurations, timezone and version behavior, and lightweight YAML and shell-contract checks without creating consumer repositories. The Test workflow runs this task; installed-gem CI runs `bundle exec rake spec:integration` so consumer integration is not repeated against source in CI. `bundle exec rake spec` and the default task still run the complete suite locally. +Unit specs cover documented configurations, timezone and version behavior, and YAML and shell contracts in-process, without creating consumer repositories. CI does not run integration specs against source. -Consumer integration specs live in the `composite`, `workflow`, and `consumer` directories under `spec/integration/`; CI runs each directory as an explicit matrix entry for each supported Ruby version. Keep a small real-process matrix covering both Actions interfaces' success, failure/recovery, empty-release rejection, custom registry, and credential propagation. Preserve the provider-neutral consumers across separate processes: they verify environment transport, private state, and installed-library loading. Stub orchestration boundaries in focused specs, not these smoke tests. Existing domain specs cover detailed format, version, timezone, Git, and authentication edge cases without repeating whole release pipelines. +`spec` and `spec:integration` run spec files in parallel with `parallel_tests` and merge coverage at the end. Workers default to the number of processors. -`bundle exec rake spec` and `spec:integration` run independent spec files concurrently with `parallel_tests`; coverage reports are generated once, after all workers finish. Workers default to the available processors. Set `PARALLEL_TEST_PROCESSORS=2` to limit workers, or use `bundle exec rake spec:serial` for a serial full-suite run. `SPEC=spec/path_spec.rb` selects files and `SPEC_OPTS='--seed 12345'` passes RSpec options. +- `PARALLEL_TEST_PROCESSORS=2` limits workers. +- `SPEC=spec/path_spec.rb` selects files. +- `SPEC_OPTS='--seed 12345'` passes RSpec options. -Run one integration suite locally with, for example, `SPEC='spec/integration/consumer/**/*_spec.rb' bundle exec rake spec:integration`. CI runs the same selectors against the installed gem, so add new integration specs to one of these directories; files elsewhere under `spec/integration/` run locally but not in CI. +### Integration Specs -Profile integration examples with `bundle exec rake spec:integration SPEC_OPTS='--profile 15 --seed 12345'`. Compare before and after on the same machine and Ruby, including subprocess counts when changing the harness; do not enforce environment-dependent timing thresholds. +Integration specs live in `spec/integration/composite`, `spec/integration/workflow`, and `spec/integration/consumer`. CI runs each directory as a matrix entry per supported Ruby. Put new integration specs in one of these directories; files elsewhere run locally but not in CI. Run one suite with: -The release integration workflow builds and installs the actual gem, then exercises both interfaces' callback commands with real local Git pushes and isolated RubyGems and GitHub publication boundaries. Tests verify release and next development iteration commits, artifact identity, and publication ordering without publishing packages or creating hosted releases. They do not execute live Actions authentication or artifact uploading. Preserve authentication selection and failure-aware artifact upload when changing either interface. Validate workflow examples with `actionlint .github/workflows/*.yml examples/.github/workflows/*.yml`. +```sh +SPEC='spec/integration/consumer/**/*_spec.rb' bundle exec rake spec:integration +``` + +Keep this real-process matrix small. It covers both Actions interfaces: success, failure and recovery, empty-release rejection, a custom registry, and credential propagation. Keep the provider-neutral consumers running across separate processes; they check environment exports, private state, and loading the installed gem. Semantic consumer fixtures cover success, publication failure, and empty-release rejection against the installed gem. Stub orchestration in focused specs, not in these smoke tests. Domain specs cover format, version, timezone, Git, and authentication edge cases. + +The release integration workflow builds and installs the real gem. It runs both interfaces' commands with real pushes to local Git remotes and fake RubyGems and GitHub publication; unexpected network requests fail. Tests check release and next development commits, artifact identity, and publication order, without publishing anything. They do not test live Actions authentication or artifact upload, so preserve authentication selection and upload-on-failure behavior when you change either interface. When you change YAML interfaces, check installed-gem consumer CI and validate the workflows with: + +```sh +actionlint .github/workflows/*.yml examples/.github/workflows/*.yml +``` + +To profile integration specs, run the command below. Compare before and after on the same machine and Ruby, including subprocess counts when you change the harness. Do not enforce timing thresholds. + +```sh +bundle exec rake spec:integration SPEC_OPTS='--profile 15 --seed 12345' +``` ## Pull Requests -Keep one coherent commit per PR; amend updates and use `git push --force-with-lease` on the topic branch. Squash and rebase merges are supported; merge commits are disabled. Update affected documentation and append notable changes to the current Next changelog section with the PR link and author attribution, above `- Your contribution here.`. Keep Markdown paragraphs on one line. See [RELEASING.md](RELEASING.md). +- Keep one coherent commit per PR. Amend it and push with `git push --force-with-lease` on the topic branch. +- Squash and rebase merges are allowed; merge commits are disabled. +- Update affected documentation. +- Add user-visible changes to the Next section of `CHANGELOG.md`, oldest first, with the PR link and author, above `- Your contribution here.`, which stays last. + +See [RELEASING.md](RELEASING.md) for releases. diff --git a/DESIGN.md b/DESIGN.md index da3e00c..1685bac 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1,81 +1,63 @@ # Design -`ruby-gem-release` provides a reusable GitHub Actions workflow, a composite action, and Ruby lifecycle tasks. Projects choose version and changelog conventions; replaceable components retain one publication sequence. +`ruby-gem-release` provides a reusable GitHub Actions workflow, a composite action, and Ruby release tasks. Projects choose their version and changelog formats. Components are replaceable, but every release publishes in the same order. ## Component Boundaries -| Component | Responsibility | -| --- | --- | -| `Workflow::RubyGem` | Install the manual release callbacks. | -| `Workflow::ReviewedRubyGem` | Publish an existing signed source without preparing or pushing Git changes. | -| `Workflow::SemanticRubyGem` | Select and persist a commit-driven release, then use the same publication sequence. | -| `Tasks` | Register callbacks, construct contexts, and capture failures. | -| `ExecutionProvider` | Transport inputs, exports, execution metadata, and authentication services. | -| `Workflow::Environment` | Check the checkout and capture initial or prepared package metadata. | -| `Workflow::State` | Persist supported callback data in private JSON. | -| `Package::RubyGem` | Read metadata, build reproducibly, and verify the exact archive. | -| `Destination::RubyGems` | Authenticate, check availability, and upload the verified artifact. | -| `SourceControl::Git` | Stage trusted edits, check concurrency, commit, tag, and push. | -| `Hosting::GitHubRelease` | Create the hosted release after the remote tag exists. | - -Execution platform, registry, and hosting are independent choices. Built-in external support covers GitHub Actions, RubyGems, and GitHub Releases. Hosting providers need idempotent `publish!(release, package:)`, not a shared base class. Class, reference, and spec paths mirror namespaces. +| Component | Responsibility | +| --- | --- | +| `Workflow::RubyGem` | Install the manual release tasks. | +| `Workflow::ReviewedRubyGem` | Publish an existing signed tag without editing or pushing Git changes. | +| `Workflow::SemanticRubyGem` | Pick the version from commits, then publish in the same order. | +| `Tasks` | Register callbacks, build contexts, and report failures. | +| `ExecutionProvider` | Pass inputs and exports between steps; supply run metadata and authentication. | +| `Workflow::Environment` | Check the checkout and read package metadata before and after preparation. | +| `Workflow::State` | Store callback data in a private JSON file. | +| `Package::RubyGem` | Read metadata, build reproducibly, and verify the exact gem file. | +| `Destination::RubyGems` | Authenticate, check whether the version exists, and upload the verified gem. | +| `SourceControl::Git` | Stage edits, detect concurrent changes, commit, tag, and push. | +| `Hosting::GitHubRelease` | Create the GitHub Release after the remote tag exists. | + +Execution platform, registry, and hosting are independent choices. Built-in support covers GitHub Actions, RubyGems, and GitHub Releases. A hosting provider needs only an idempotent `publish!(release, package:)`; there is no base class. Class, documentation, and spec paths mirror namespaces. ## Lifecycle and Publication -Both interfaces install dependencies, capture context, validate, prepare files, resolve the version, test, checkpoint and preserve artifacts, publish, prepare the next development iteration, and notify success. Validation raises on invalid state, including nothing to release; normal completion succeeds, while returning `false` also fails. Errors stop downstream operations and reach the failure callback after successful Ruby setup. +Both interfaces run one fixed [step order](docs/actions/release.md#execution). Components and hooks can be replaced or added, but they cannot reorder the publication guards. -The checkpoint task commits prepared edits, builds reproducibly, tags locally, and creates a recovery bundle. After artifacts are preserved, publication repeats commit, build, and tag preparation before verifying or uploading the gem, atomically pushing its commit and tag, and creating or updating the hosted release. Git checks for concurrent branch changes before publication and again before pushing. +Registry upload and Git push cannot be atomic together. So a checkpoint saves the built gem and a Git bundle before anything is published, and publication uploads the gem before it pushes the commit and tag together. If the upload fails, nothing is pushed and no GitHub Release is created. -Every release action must be idempotent for the same checkout and inputs, without recovery flags, artifact discovery, restored context, or a completion journal. Tasks reconcile their own outputs; a fresh workflow uses its current checkout and inputs rather than discovering an older unfinished release. Registry publication and Git pushes cannot be atomic together, so both interfaces preserve artifacts before publication for manual inspection. See [rerunning releases](RELEASING.md#verify-and-recover). +Release steps are idempotent instead of resuming from saved progress. Each rerun checks its own outputs, so there is no recovery state to store, restore, or trust. The rules are in [Verify and Recover](RELEASING.md#verify-and-recover). -Keep both YAML interfaces thin and consistent. The reusable workflow does not depend on a moving composite-action reference: a pinned release must remain independent of later action versions. Both interfaces, and this repository's own workflows, pin every external action and reusable workflow to a commit SHA with its version as a comment, so a caller that pins a release by SHA also fixes every action that runs with release credentials. Dependabot proposes updates to those pins. Composite callers own permissions, runner, environment protection, and concurrency. Commands run with release privileges and must be trusted. +Keep both YAML interfaces thin and consistent. The reusable workflow does not reference the composite action by a moving ref, so a pinned release never changes later. Both interfaces and this repository's workflows pin every external action and reusable workflow to a commit SHA with a version comment. Pinning a release by SHA therefore fixes every action that runs with release credentials. Dependabot proposes pin updates. Composite action callers own permissions, runner, environment protection, and concurrency. Commands run with release privileges and must be trusted. ## Preparation and Artifact Guards -Standard capture rejects non-default branches and dirty checkouts after dependency installation. The opt-in reviewed workflow permits an explicit branch list, requires the current remote tip and exact existing signed remote tag, and never prepares commits, tags, pushes, or a development version. Capture and resolution use the configured package; built-in selection requires one root gemspec or an explicit path. Dates and the initial version are captured once, with UTC as the timezone default. +What is tested is what is released. Only trusted preparation edits are staged, and publication fails on any later change to the working tree or index instead of staging it. See [Git preparation](docs/source_control/git.md#clean-checkout-and-preparation). -`Git#stage_changes!` requires a clean checkout or the exact previously prepared index before trusted edits, stages literal changed paths, and records the index tree. Resolution also stages custom preparation-command outputs before testing. Publication rejects later working-tree or index changes and never stages them. Development iteration edits use the same boundary, including custom version-object side effects. +Lifecycle hooks add checks and project edits without replacing the release order; only preparation hooks may edit files. See the [hook guide](docs/workflow/hooks.md). Already-reviewed signed tags use the separate [reviewed workflow](docs/workflow/reviewed_ruby_gem.md), which shares the hook lifecycle but never commits, tags, pushes, or bumps. -Resolution validates the prepared version; publishing tasks enforce their own postconditions. RubyGems accepts an existing version only when its checksum matches. Git reuses matching release and development trees without moving tags or rewinding remote descendants. Hosting replaces differing metadata and assets. Development increments are anchored to the supplied release version, not a recorded completion marker. - -Lifecycle hooks add checks and project edits without replacing the release sequence. The editing workflows and the reviewed workflow compose a shared lifecycle for hooks and task installation; the reviewed workflow does not inherit version, changelog, commit, tag, or bump behavior. Preparation hooks run inside trusted staging; other hooks validate or observe. See the [hook guide](docs/workflow/hooks.md). - -Version objects update exactly one constant assignment without evaluating the file, or a plain text numeric version file. An opt-in decorator wraps a version object and updates configured reference patterns to the released version during the next development bump. Changelog objects load optional `Commonmarker` when parsing sections, then edit original source to preserve formatting. Core installation and loading require no native dependencies. Handwritten formats reject empty notes before writing; malformed content fails rather than skipping. See [version](docs/version/ruby_constant.md), [references](docs/version/references.md), [changelog](docs/changelog/base.md), and [Git](docs/source_control/git.md) contracts. +Version and changelog objects edit source text without evaluating it, so formatting is preserved. Changelog parsing loads the optional `Commonmarker` gem, so the core gem needs no native dependencies. Malformed content fails instead of being skipped. See the [version](docs/version/ruby_constant.md), [references](docs/version/references.md), and [changelog](docs/changelog/base.md) contracts. ## Contexts and State -Callbacks receive frozen execution snapshots containing an immutable `Release`, current step, observed history, configured workflow, run metadata, and optional semantic analysis. Domain operations receive only `Release`. Contexts are data, not platform clients; workflow objects are reconstructed from the Rakefile in each process. - -The provider-neutral base uses logical task IDs and process-local environment exports. Automatic selection chooses GitHub when `GITHUB_ACTIONS=true`; explicit `provider:` overrides detection. GitHub owns Actions transport, refs, temporary storage, bot identity, masking, and OIDC. It supplies enclosing step IDs and prior observed results, keeping outcome and conclusion distinct. Absent steps are unknown, not skipped; run metadata excludes credentials and the event payload. +Each Actions step runs in a separate process, so every process rebuilds the workflow from the Rakefile. Callbacks receive a frozen context that is plain data, not a platform client, and domain operations receive only the immutable `Release`. See [execution contexts](docs/execution_context.md) and [tasks](docs/tasks.md). -Capture creates a unique private state file outside the checkout when provider storage is available. Atomic updates retain only semantic analysis and the completed next development version, with no format version or migrations. Regular and failure callback contexts read one validated snapshot, without caching across invocations. Without a file, tasks share process-local state. Corrupt state fails closed; failure callbacks omit unreadable metadata without hiding the original exception. - -Failure callbacks receive the failed phase, captured Ruby exception when available, and context whose release may be absent. Shell-only failures may lack exception details. See [execution contexts](docs/execution_context.md) and [tasks](docs/tasks.md). +Persisted state is deliberately minimal: a private file outside the checkout holds only the semantic decision and the next development version, with no format version or migrations. Corrupt state fails rather than being guessed at. ## Manual and Semantic Workflows -The manual workflow requires explicit version and changelog choices. Preparation honors an optional version selection; publication retains the initial version separately. After publication, the default bump increments patch, or the part selected by `next_version:`, prepares the next changelog section, commits, pushes, and records the next version. `changelog: nil` and `hosting: nil` disable only those components. - -Semantic releases are opt-in. Validation analyzes commits after the highest reachable stable release tag, records one immutable decision, and binds it to the captured head and explicit input. Later phases consume it without reanalysis. Versions do not derive from development versions; first release defaults to `1.0.0`, and explicit versions must exceed the last release. Generated notes reach the changelog and hosting unchanged. - -Semantic development bumps default off. Prereleases, maintenance branches, channels, alternate tag formats, and additional platform adapters remain outside scope. Provider contracts and upstream behavior references live in the [semantic guide](docs/workflow/semantic_ruby_gem.md). +The [manual workflow](docs/workflow/ruby_gem.md) requires explicit version and changelog objects, so nothing about a project's conventions is guessed. [Semantic releases](docs/workflow/semantic_ruby_gem.md) are opt-in. Validation records one immutable decision from the commits since the last stable release tag, and later processes reuse it instead of reanalyzing, so every step publishes the same version and notes. Prereleases, maintenance branches, channels, other tag formats, and other platform adapters are out of scope. ## Authentication -Authentication belongs to `release:publish`, through the destination's `authenticate!(provider:)` hook, not a registry-specific YAML step. RubyGems uses `Workflow::RubyGemsCredentials` when resolution selected automatic authentication; other destinations can retain preconfigured credentials. - -The helper obtains an audience-bound token through its execution provider, exchanges it with optional owner binding, masks tokens, and exports key variables. It makes no retries or credential-file writes. Custom callbacks inherit that environment; commands bypassing the publication task own authentication. See the [credential contract](docs/workflow/ruby_gems_credentials.md). +Authentication happens inside `release:publish`, through the destination's `authenticate!(provider:)` hook, not in a YAML step. This keeps both YAML interfaces registry-neutral and lets custom destinations change authentication without YAML changes. The RubyGems helper does not retry or write credential files. See the [credential contract](docs/workflow/ruby_gems_credentials.md). ## Testing -Source CI runs `rake spec:unit`; installed-gem CI runs `rake spec:integration`. The default local task runs both plus lint. Focused specs cover orchestration permutations, documented configurations, and YAML shell contracts without repeated Bundler startup. - -Real-process consumers retain success, failure/recovery, empty-release rejection, custom registry, and credential propagation. Portable consumers also verify environment transport, state, and installed-library loading without Actions variables. Git pushes use local bare repositories; publication boundaries are isolated and unexpected network requests fail. These tests do not validate live Actions authentication or artifact uploading. Profile harness changes rather than enforcing timing thresholds. - -Optional `ruby-gem-release/rspec` support exposes disposable Git fixtures, isolated Rake processes, a provider for cross-process exports, and local registry and hosting adapters without adding an RSpec runtime dependency. Projects exercise their real workflow configuration with explicit test adapters; the helper does not rewrite production tasks or sandbox arbitrary callbacks. The lifecycle-hook example shares its workflow builder between its Rakefile and complete consumer spec. +The optional `ruby-gem-release/rspec` helper lets projects test their real workflow configuration with local Git, registry, and hosting adapters, without an RSpec runtime dependency. It does not rewrite production tasks or sandbox callbacks. See [Testing Custom Workflows](docs/testing.md); this repository's own suites are described in [CONTRIBUTING.md](CONTRIBUTING.md#tests). ## Self-Release and Artwork -The manual `publish.yml` caller uses the root Rakefile and Ruby 4.0; merges and schedules do not publish. Every dispatch requires release authorization. Its project-local `ReleaseVersion` configures the decorator to update README and documentation pins during the next development iteration, after the release tag exists. See the [self-release walkthrough](examples/self_release/README.md). +This project releases itself with the manual `publish.yml` caller; see the [self-release walkthrough](examples/self_release/README.md). -`assets/logo.png` is an AI-generated faceted ruby with an upward release arrow, approved by the maintainer. It replaces the original AI-generated ruby rocket from [#5](https://github.com/dblock/ruby-gem-release/pull/5); neither image has an editable source. The arrow-above-gem composition follows the sibling [JavaScript package release](https://github.com/dblock/npm-package-release) and [Rust crate release](https://github.com/dblock/rust-crate-release) logos. Preserve this provenance and the 160-pixel README placement. Replacements should be centered, text-free red faceted rubies with an upward release motif and transparent background. Generation is not deterministic; inspect the full-size image and README rendering for clipping and legibility. +`assets/logo.png` is an AI-generated faceted ruby with an upward release arrow, approved by the maintainer. It replaces the original AI-generated ruby rocket from [#5](https://github.com/dblock/ruby-gem-release/pull/5). Neither image has an editable source. The arrow-above-gem layout matches the sibling [JavaScript package release](https://github.com/dblock/npm-package-release) and [Rust crate release](https://github.com/dblock/rust-crate-release) logos. Keep this provenance and the 160-pixel README placement. A replacement should be a centered, text-free, red faceted ruby with an upward release motif on a transparent background. Generation is not deterministic, so inspect the full-size image and README rendering for clipping and legibility. diff --git a/README.md b/README.md index 7af5b9b..3f66237 100644 --- a/README.md +++ b/README.md @@ -6,15 +6,23 @@ **Release your Ruby gem from GitHub Actions without maintaining custom release scripts or storing a RubyGems API key.** -Implements [Releases as Code](https://code.dblock.org/2026/11/12/releases-as-code.html) for Ruby gems. Release from GitHub Actions, run your project's tests, publish to RubyGems, optionally update the changelog, create a Git tag and GitHub Release, and prepare the next development iteration. Choose your version and changelog formats. See [npm-package-release](https://github.com/dblock/npm-package-release) and [rust-crate-release](https://github.com/dblock/rust-crate-release) for similar projects in the JavaScript and Rust ecosystems. +Implements [Releases as Code](https://code.dblock.org/2026/11/12/releases-as-code.html) for Ruby gems. You start a GitHub Actions workflow, and it: -The default setup below requires Ruby 3.3+, GitHub Actions, and RubyGems Trusted Publishing. +- runs your tests, +- publishes the gem to RubyGems, +- updates the changelog (optional), +- creates a Git tag and a GitHub Release, +- bumps the version for the next development iteration. + +See also [npm-package-release](https://github.com/dblock/npm-package-release) and [rust-crate-release](https://github.com/dblock/rust-crate-release). + +You need Ruby 3.3+, GitHub Actions, and RubyGems Trusted Publishing. ## Usage ### 1. Configure Your Gem -Add `ruby-gem-release` and `commonmarker ~> 2.10` to the development dependencies and install the standard workflow in your Rakefile. Commonmarker is optional for projects not using Markdown changelogs; the core has no native dependencies. Choose your version file and changelog format explicitly: +Add `ruby-gem-release` and `commonmarker ~> 2.10` (needed only for Markdown changelogs) to your development dependencies. Then install the release tasks in your Rakefile, naming your version file and changelog format: ```ruby require 'ruby-gem-release/workflow/ruby_gem' @@ -26,13 +34,20 @@ RubyGemRelease::Workflow::RubyGem.new( ).install_tasks ``` -These defaults select the gemspec and repository, reject empty pending notes, prepare the changelog, publish to RubyGems and GitHub Releases, and increment the patch version for the next development iteration; pass `next_version: :minor` or `:major` to [increment another part](docs/workflow/ruby_gem.md#next-version). Dates use UTC. +With these defaults, a release: -If the Rakefile also installs the Bundler gem tasks, disable their local `release` tasks so maintainers cannot publish around the workflow; see [Bundler Release Tasks](docs/usage.md#bundler-release-tasks). +- uses the only gemspec in the repository root, +- fails if the changelog has no pending notes, +- moves the pending notes under a new release heading, +- publishes to RubyGems and GitHub Releases, +- bumps the patch version afterwards (pass `next_version: :minor` or `:major` to [bump another part](docs/workflow/ruby_gem.md#next-version)), +- dates the release in UTC. + +If your Rakefile also installs the Bundler gem tasks, disable the local Bundler `release` tasks so nobody can publish around the workflow. See [Bundler Release Tasks](docs/usage.md#bundler-release-tasks). ### 2. Add the Release Workflow -Add `.github/workflows/release.yml` using the [sample workflow](examples/.github/workflows/release.yml), replacing the Ruby version with your project's value: +Copy the [sample workflow](examples/.github/workflows/release.yml) to `.github/workflows/release.yml` and set your Ruby version: ```yaml name: Release @@ -64,57 +79,56 @@ jobs: ### 3. Enable Trusted Publishing -In your GitHub repository, open **Settings → Environments** and create an environment named `release`. Alternatively, from your repository directory, use `gh`: - -```sh -gh api --method PUT repos/{owner}/{repo}/environments/release -``` +Trusted Publishing lets GitHub Actions publish to RubyGems without a stored API key. -For a new gem, open the [pending trusted publishers page](https://rubygems.org/profile/oidc/pending_trusted_publishers). For an existing gem, open your existing gem's **Trusted publishers** page (e.g. `https://rubygems.org/gems/example/trusted_publishers`). Create a [trusted publisher](https://guides.rubygems.org/trusted-publishing/#using-reusable-workflows). Set the repository fields to your gem's repository, the workflow filename to `release.yml`, and the environment to `release`. Set the separate workflow repository fields to `dblock` and `ruby-gem-release`; these identify the reusable workflow RubyGems verifies in the OIDC token. +1. In your GitHub repository, open **Settings → Environments** and create an environment named `release`. Or run `gh api --method PUT repos/{owner}/{repo}/environments/release` from your repository directory. +2. On RubyGems, open the [pending trusted publishers page](https://rubygems.org/profile/oidc/pending_trusted_publishers) for a new gem, or your gem's **Trusted publishers** page (for example `https://rubygems.org/gems/example/trusted_publishers`) for an existing gem. +3. Create a [trusted publisher](https://guides.rubygems.org/trusted-publishing/#using-reusable-workflows) with your gem's repository, workflow filename `release.yml`, and environment `release`. +4. Set the separate workflow repository fields to `dblock` and `ruby-gem-release`. This tells RubyGems to trust this project's reusable workflow. -To verify this setup without releasing, dispatch a [dry run](docs/actions/release.md#dry-run). +To check the setup without releasing, run a [dry run](docs/actions/release.md#dry-run). -Collaborators with write access can dispatch releases after this setup, without repository admin access or their own RubyGems credentials. Creating the environment alone does not restrict publication. Configure [required maintainer approval and deployment branches](RELEASING.md#maintainer-approved-publication) to control who approves publication. +Anyone with write access can now dispatch a release, without admin access or RubyGems credentials. The `release` environment alone restricts nothing. To require approval from a maintainer, configure [required reviewers and deployment branches](RELEASING.md#maintainer-approved-publication). ### 4. Make a Release -Your branch rules must permit release commits and tags to be pushed; see [branch permissions](RELEASING.md#one-time-setup). Each release checks this before publishing. Dispatching starts a publishing run; when required reviewers are configured, the release job waits for approval from a designated maintainer. Run your project's tests and build checks, review the changes, and dispatch from your default branch: Do not merge into the default branch while a release runs; see [recovery](docs/actions/release.md#default-branch-advanced-during-publication). +Your branch rules must allow the workflow to push release commits and tags ([branch permissions](RELEASING.md#one-time-setup)); each release checks this before publishing. Run your tests, review the changes, then dispatch from your default branch. Dispatching starts a real release; with required reviewers, it waits for approval. -**First release:** Pass the numeric RubyGems account ID shown on the Pending Trusted Publishers page as `rubygems-owner`. This declares the account that will own the gem on its first publication. Replace `YOUR_ACCOUNT_ID` below with that ID: +Do not merge into the default branch while a release runs. If that happens, see [recovery](docs/actions/release.md#default-branch-advanced-during-publication). + +**First release:** pass your numeric RubyGems account ID, shown on the Pending Trusted Publishers page, as `rubygems-owner`. This account will own the new gem: ```sh gh workflow run release.yml -f rubygems-owner=YOUR_ACCOUNT_ID ``` -**Subsequent releases:** Omit `rubygems-owner` once the gem exists. Its trusted publisher is still required, but the account ID is no longer needed: +**Later releases:** omit `rubygems-owner`. The trusted publisher is still required: ```sh gh workflow run release.yml ``` -To release a different version, select it in the dispatch form or pass `-f version=1.2.3`. The standard workflow updates the configured version file before preparing the changelog, then starts the next development iteration from the selected release version. +To release a different version, enter it in the dispatch form or pass `-f version=1.2.3`. The workflow writes it to your version file, and the next development version is bumped from it. -For a real-world example of adding release automation to an existing gem, see [ruby-link-checker #26](https://github.com/dblock/ruby-link-checker/pull/26). It adds the dependency, Rake tasks, reusable workflow, and release instructions while preserving the existing changelog format. +For a real-world example of adding this to an existing gem, see [ruby-link-checker #26](https://github.com/dblock/ruby-link-checker/pull/26). ## Extending the Workflow -Replace only what you need. The [standard workflow](docs/workflow/ruby_gem.md) preserves ordering; [Detailed Usage](docs/usage.md) provides file examples and complete manual callbacks. - -- **Project conventions:** Choose [version objects](docs/usage.md#version-objects) and [changelog formats](docs/usage.md#changelog-objects), including custom implementations. -- **Stage customization:** Add ordered [lifecycle hooks](docs/workflow/hooks.md) for validation, trusted preparation edits, publication observers, and notifications without replacing the pipeline. -- **Release decisions and callbacks:** Customize [validation, preparation, publication, and notifications](docs/tasks.md). Callbacks receive an [execution context](docs/execution_context.md) with release data, step history, and the configured workflow. -- **Semantic releases:** Opt into [Conventional Commits, release-history-based versions, and generated notes](docs/workflow/semantic_ruby_gem.md) without changing the execution platform or registry. -- **Packages and registries:** Override [package construction](docs/package/ruby_gem.md) or supply a [registry destination](docs/destination.md) independently of hosted releases. -- **Release hosting:** Replace or disable [GitHub Release creation](docs/workflow/ruby_gem.md#hosting) without changing package publication or Git operations. -- **Execution platforms:** Supply an [execution provider](docs/execution_provider.md) for environment transport, metadata, temporary storage, and authentication services. GitHub Actions is the only built-in external platform; another platform needs its own adapter and pipeline. -- **Actions integration:** Override commands, inputs, and timezone through the [Actions Reference](docs/actions/release.md), or use the [Composite Action](docs/actions/action.md) inside a caller-owned job. -- **Testing customizations:** Use optional [RSpec helpers and local publication adapters](docs/testing.md) to verify project-specific release behavior and catch regressions in release-managed files. +Replace only what you need. See the [standard workflow](docs/workflow/ruby_gem.md) and [Detailed Usage](docs/usage.md) for examples. -Execution platform, registry, and hosting are independent choices. +- **Project conventions:** choose [version objects](docs/usage.md#version-objects) and [changelog formats](docs/usage.md#changelog-objects), or write your own. +- **Extra steps:** add [lifecycle hooks](docs/workflow/hooks.md) for checks, file edits, publication observers, and notifications without replacing the pipeline. +- **Custom callbacks:** replace [validation, preparation, publication, and notifications](docs/tasks.md). Callbacks receive an [execution context](docs/execution_context.md) with release data, step history, and the workflow. +- **Semantic releases:** opt into [Conventional Commits, versions from release history, and generated notes](docs/workflow/semantic_ruby_gem.md). +- **Packages and registries:** override [how the gem is built](docs/package/ruby_gem.md) or [where it is published](docs/destination.md). +- **Release hosting:** replace or turn off [GitHub Release creation](docs/workflow/ruby_gem.md#hosting) without affecting gem publication or Git. +- **CI platforms:** choose the platform, registry, and hosting independently. Supply an [execution provider](docs/execution_provider.md) for environment variables, metadata, temporary storage, and authentication. GitHub Actions is the only built-in platform; others need their own adapter and pipeline. +- **Actions options:** override commands, inputs, and timezone through the [Actions Reference](docs/actions/release.md), or use the [Composite Action](docs/actions/action.md) as a step in your own job. +- **Testing:** use optional [RSpec helpers and local publishing stand-ins](docs/testing.md) to test your release customizations and the files they change. -For complete examples, see [releasing ruby-gem-release itself](examples/self_release/README.md) with small project-specific customizations, then [GitLab and semantic releases](examples/gitlab_semantic_release/README.md) for built-in semantic providers composed with placeholder GitLab adapters. +For complete examples, see [releasing ruby-gem-release itself](examples/self_release/README.md) and [GitLab and semantic releases](examples/gitlab_semantic_release/README.md). -The defaults retain [clean-checkout checks](docs/source_control/git.md), [duplicate-version checks](docs/destination/ruby_gems.md#check-version), and [verified recovery artifacts](docs/actions/release.md#recovery-artifacts). Custom publication callbacks must preserve the documented ordering and artifact checks. +The defaults include [clean-checkout checks](docs/source_control/git.md), [duplicate-version checks](docs/destination/ruby_gems.md#check-version), and [preserved recovery artifacts](docs/actions/release.md#recovery-artifacts). Custom publication callbacks must keep the documented order and artifact checks. ## Upgrading diff --git a/RELEASING.md b/RELEASING.md index 441cb93..61d6845 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -1,35 +1,33 @@ # Releasing -These instructions do not authorize publication. Upgrade the gem and pinned workflow or action together; see [UPGRADING.md](UPGRADING.md) for migrations. +These instructions do not authorize publication. Upgrade the gem and the pinned workflow or action together; see [UPGRADING.md](UPGRADING.md). ## One-Time Setup -Follow [README Usage](README.md#usage) to add a caller with `contents: write` and `id-token: write`, then create a GitHub environment named `release`. +1. Add a caller workflow, create the `release` environment, and configure a RubyGems trusted publisher, as described in [README Usage](README.md#usage). +2. Protect the environment as described in [Maintainer-Approved Publication](#maintainer-approved-publication). +3. Allow the Actions token to push fast-forward commits and tags. -Configure [RubyGems Trusted Publishing](https://guides.rubygems.org/trusted-publishing/) for the publishing repository, executing workflow `release.yml`, and environment `release`. When calling this repository's reusable workflow from another repository, set the separate workflow repository fields to `dblock` and `ruby-gem-release`. For this project's local caller, leave those fields blank: `publish.yml` dispatches the run, but `release.yml` executes the OIDC job. +For this project's own trusted publisher, leave the workflow repository fields blank: `publish.yml` starts the run, but the OIDC job runs in this repository's `release.yml`. Other repositories set them to `dblock` and `ruby-gem-release`. See [Permissions and Authentication](docs/actions/release.md#permissions-and-authentication) for first-release owner IDs and exported credentials. -For a gem's first publication, configure a pending trusted publisher and pass its numeric account ID as `rubygems-owner`. Existing gems normally omit that input. Authentication exports short-lived credentials without writing `~/.gem/credentials`; adding the workflow configures neither registry trust nor credentials. - -The Actions token must be allowed to push fast-forward commits and tags. A PR requirement may block it; a separately configured release App bypass can preserve PR enforcement. This repository instead permits direct pushes by all writers while blocking force pushes and deletion; ordinary development still uses PRs. Actions-token pushes do not trigger ordinary push workflows, so release validation must run the necessary checks. +A branch rule that requires PRs blocks the Actions token; a bypass for a separate release App keeps PR enforcement. This repository lets all writers push directly but blocks force pushes and deletion; ordinary development still uses PRs. Pushes by the Actions token do not trigger other push workflows, so the release run must run every check you need. ### Maintainer-Approved Publication -Creating an environment alone does not restrict publication. Under **Settings > Environments > release**, configure [environment protection](https://docs.github.com/en/actions/how-tos/deploy/configure-and-manage-deployments/manage-environments): +An environment alone does not restrict publication. Under **Settings > Environments > release**, configure [environment protection](https://docs.github.com/en/actions/how-tos/deploy/configure-and-manage-deployments/manage-environments): - **Required reviewers:** Select maintainers; any one can approve. -- **Prevent self-review:** Enable for two-person approval; disable to let a maintainer dispatch and approve. +- **Prevent self-review:** Enable to require a second person; disable to let a maintainer approve their own dispatch. - **Administrator bypass:** Disable if approval must always be required. -- **Deployment branches and tags:** Select only the actual default branch (`master` here), with no tag rules. +- **Deployment branches and tags:** Allow only the default branch (`master` here), with no tag rules. -Availability depends on visibility and plan; verify these controls before relying on them. Other writers can still dispatch, but the protected job waits for approval before running steps or obtaining credentials. Environment rules protect jobs, not the dispatch entry point. +Availability depends on visibility and plan, so confirm these controls exist. Any writer can still dispatch, but the job waits for approval before it runs or gets credentials. ## Prepare and Publish -Both interfaces require the default branch and a clean checkout after dependency installation. Ignore intentional dependency output such as `.bundle/config` or `vendor/bundle`; unexpected tracked, staged, or untracked non-ignored changes fail. Preparation stages trusted edits before testing; publication rejects subsequent changes rather than staging them. - -The default manual workflow releases the checked-in version, or honors an explicit `version` input, then increments patch afterward unless `next_version:` selects another part. Semantic workflows select from release history and default to no development bump. Custom commands own their operations and must retain the [documented ordering and guards](docs/usage.md#custom-callbacks). +Releases run from the default branch with a clean checkout; see [Execution](docs/actions/release.md#execution) for the checks and step order. The [manual workflow](docs/workflow/ruby_gem.md) releases the checked-in version or the `version` input, then bumps patch. The [semantic workflow](docs/workflow/semantic_ruby_gem.md) picks the version from release history and does not bump by default. Custom commands must keep the [documented ordering and guards](docs/usage.md#custom-callbacks). -Validate and build before authorizing a release: +Test and build before you authorize a release: ```sh bundle exec rake @@ -38,44 +36,47 @@ bundle exec rake build ### Releasing This Project -The manual **Release** caller is [`.github/workflows/publish.yml`](.github/workflows/publish.yml). Merges and schedules do not publish. It uses Ruby 4.0, the root Rakefile, and `America/New_York` for release dates and Git timestamp offsets. - -Verify the existing RubyGems trusted publisher before dispatch with a [dry run](docs/actions/release.md#dry-run), which exchanges credentials without releasing: `gh workflow run publish.yml --ref master -f dry-run=true`. The caller passes the non-secret `RUBYGEMS_OWNER_ID` repository variable when set; this identifies an account, not an API key. Pending publishers need it for first publication. +The manual **Release** workflow is [`.github/workflows/publish.yml`](.github/workflows/publish.yml); the [self-release walkthrough](examples/self_release/README.md) explains its configuration. Merges and schedules never publish. -Only after explicit authorization, successful validation, and confirmed setup: +1. Check the trusted publisher with a [dry run](docs/actions/release.md#dry-run), which exchanges credentials without releasing: `gh workflow run publish.yml --ref master -f dry-run=true`. +2. Only with explicit authorization, passing validation, and confirmed setup, dispatch the release. A required reviewer then approves the `release` environment. ```sh gh workflow run publish.yml --ref master ``` -Every dispatch requests publication; nothing to release is a validation error. Required environment reviewers approve before the job starts. After publication, the decorator configured by `ReleaseVersion` updates pins in README and every `docs/**/*.md` file to the released tag while incrementing the development version; these edits belong to the next-development commit, not the release tag. +Every dispatch tries to publish; nothing to release fails validation. The `RUBYGEMS_OWNER_ID` repository variable, when set, is passed as `rubygems-owner`. It is an account ID, not an API key, and only pending publishers need it. ### Releasing a Consumer Project -Use the [README setup](README.md#usage), dispatch its caller on the default branch, and approve the environment when required. For an explicit version, pass `-f version=1.2.3` to that caller's `gh workflow run` command. +Follow [Make a Release](README.md#4-make-a-release): dispatch the caller on the default branch and approve the environment if required. For a specific version, add `-f version=1.2.3` to `gh workflow run`. See [Actions inputs](docs/actions/release.md) for options. -The pipeline captures context, validates, prepares, resolves, and tests. A checkpoint commits, builds, tags locally, and creates a Git bundle for manual inspection; artifact preservation must succeed before external publication. Publication verifies or uploads the gem, pushes commit and tag atomically, then updates the hosted release. Finally, it optionally bumps. See [Actions inputs](docs/actions/release.md) and [Git preparation](docs/source_control/git.md#clean-checkout-and-preparation). - -Never invoke publication as a preview. Custom commands execute with release privileges and must be trusted; callers bypassing `release:publish` own authentication. +Never run publication as a preview. Custom commands run with release privileges and must be trusted. Callers that skip `release:publish` handle authentication themselves. ## Publish the Action to Marketplace -After an authorized release, confirm its tag contains root `action.yml` and matches the gem and GitHub Release. Never move an existing tag to add metadata. +Marketplace listing is manual and separate from the release. -The owner must accept the Marketplace Developer Agreement. Edit the new GitHub Release, select **Publish this Action to the GitHub Marketplace**, choose categories, and save. Follow [GitHub's requirements](https://docs.github.com/en/actions/how-tos/create-and-publish-actions/publish-in-github-marketplace); listing is separate from release creation and is not automated here. +1. Confirm the new tag contains root `action.yml` and matches the gem and GitHub Release. Never move a tag to add metadata. +2. Make sure the owner has accepted the Marketplace Developer Agreement. +3. Edit the GitHub Release, select **Publish this Action to the GitHub Marketplace**, choose categories, and save. -## Verify and Recover +See [GitHub's requirements](https://docs.github.com/en/actions/how-tos/create-and-publish-actions/publish-in-github-marketplace). -Verify the RubyGems version, tag commit, GitHub Release and attached archive, and next development commit when enabled. Never overwrite published versions or move release tags. +## Verify and Recover -Rerun with the same source commit and inputs, including the release date. Each task reconciles its own outputs; there are no recovery flags, artifact discovery, restored context, or completion journal. A newly queued workflow uses its current checkout and inputs, not an automatically selected older unfinished release. +Check the RubyGems version, the tag commit, the GitHub Release and its gem, and the next development commit if enabled. Never overwrite a published version or move a release tag. -Builds overwrite local artifacts reproducibly. Capture exports the committer timestamp of the source commit as `SOURCE_DATE_EPOCH`, unless explicitly supplied; it controls the gemspec date and archive timestamps. Generated release commits do not change it. Stable toolchains, gemspecs, generated files, and signing inputs remain the caller's responsibility. RubyGems accepts an existing version only when its SHA256 matches; a differing or unavailable checksum fails. +To recover, rerun with the same source commit and inputs, including the release date. Every release step is idempotent: it finishes only what is missing. There are no recovery flags, artifact discovery, restored state, or completion journal, and a new run never picks up an older unfinished release. On a rerun: -Git reuses matching release and development trees without moving tags or rewinding remote descendants. Development bumps calculate from the supplied release version, so repetition does not increment twice. GitHub replaces differing release metadata, notes read from the changelog, and assets; unspecified platform-generated notes are retained. +- **Build** produces the same gem. `SOURCE_DATE_EPOCH` defaults to the committer time of the source commit and sets the gemspec date and archive timestamps. You keep toolchains, gemspecs, generated files, and signing inputs stable. +- **RubyGems** accepts an existing version only if its SHA256 matches. +- **Git** reuses matching commits, never moves tags, and never rewinds newer remote commits. +- **Bump** calculates from the release version, so it never bumps twice. +- **GitHub Release** replaces differing metadata, changelog notes, and assets. GitHub-generated notes, used when there are no notes, are kept. -Actions preserves `release.gem`, its name/version/digest manifest `release.json`, and `release.bundle` before publication for 30 days. These are for manual inspection, not automatic restoration. Conflicting checksums or tags and unrelated branch advancement require investigation; do not overwrite immutable releases. If the default branch advanced during publication, follow [the manual recovery](docs/actions/release.md#default-branch-advanced-during-publication). +Before publishing, the workflow uploads [recovery artifacts](docs/actions/release.md#recovery-artifacts) for manual inspection; nothing restores them. Investigate conflicting checksums or tags and unexpected branch changes. If the default branch moved during publication, follow [the manual recovery](docs/actions/release.md#default-branch-advanced-during-publication). -All custom commands and callbacks must be idempotent too. Notifications need receiver-side readback or a stable key such as `"release/example/1.2.3/success"`, never a run ID. They may execute again; without receiver support, exactly-once delivery and automatic detection of an unfinished notification are impossible. Release reconciliation proves package, Git, hosting, and development completion, not arbitrary external callback completion. +Custom commands and callbacks must be idempotent too. Notifications need a receiver-side check or a stable key such as `"release/example/1.2.3/success"`, never a run ID; otherwise they may be sent twice. Reruns verify the gem, Git, hosting, and bump, not your callbacks. -To disable hosted releases intentionally, use `hosting: nil` or omit the hosting call in manual callbacks—not the entire publication callback. +To skip hosted releases, use `hosting: nil` or omit the hosting call in manual callbacks, not the whole publication callback. diff --git a/docs/actions/action.md b/docs/actions/action.md index fbe9eb4..1292608 100644 --- a/docs/actions/action.md +++ b/docs/actions/action.md @@ -1,12 +1,12 @@ # Composite Release Action -Reference for [`action.yml`](../../action.yml), a step-based alternative to the [reusable workflow](release.md). +Reference for [`action.yml`](../../action.yml), a step you add to your own job instead of calling the [reusable workflow](release.md). ## Setup -Install a `ruby-gem-release` gem release compatible with your pinned action release in the calling project's development dependencies and configure its Rakefile as shown in [Usage](../../README.md#1-configure-your-gem). Upgrade them together when adopting breaking changes. The action uses that project's `Gemfile`, callbacks, and shared release tasks; it does not install a separate release configuration. +Add a `ruby-gem-release` version that matches your pinned action version to your development dependencies, and configure the Rakefile as in [Usage](../../README.md#1-configure-your-gem). Upgrade both together. The action uses your `Gemfile`, callbacks, and release tasks. -Save the following as `.github/workflows/release.yml`. Unlike a reusable workflow, an action cannot set its caller's runner, permissions, environment, or concurrency. Keep those job-level settings in the calling workflow: +Save this as `.github/workflows/release.yml`. An action can't set the runner, permissions, environment, or concurrency, so your workflow sets them: ```yaml name: Release @@ -44,36 +44,35 @@ jobs: rubygems-owner: ${{ inputs.rubygems-owner }} ``` -The action checks out the calling repository with full history and sets up Ruby with Bundler caching. It configures inputs, captures context, validates, prepares, resolves, tests, checkpoints and preserves artifacts, publishes, and prepares the next development iteration. Commands always run and own their idempotence. Immutable conflicts and unrelated branch advancement fail before publication. Use a GitHub-hosted Ubuntu runner, matching the reusable workflow's supported execution environment. +The action checks out your repository with full history, sets up Ruby with Bundler caching, and runs the same steps as the [reusable workflow](release.md#execution): validate, prepare, test, checkpoint and preserve artifacts, publish, and bump. Each run uses only the current checkout and inputs, so commands must be safe to rerun. Conflicting tags and unrelated branch changes fail before publication. Use a GitHub-hosted Ubuntu runner, as the reusable workflow does. ## Inputs and Environment -Inputs, command defaults, callback semantics, and exported environment variables match the [workflow reference](release.md#inputs). Set them under the action step's `with:` mapping rather than under a reusable-workflow job. All action inputs are strings. `gemfile` defaults to empty, which keeps a `BUNDLE_GEMFILE` the calling job already sets; a nonempty value is exported for all later steps before Ruby setup. Dispatching the sample workflow requests publication; configured environment protection rules must pass before the job runs. +Inputs, defaults, callbacks, and environment variables match the [workflow reference](release.md#inputs), with these differences: -For [already-reviewed source and package collections](../workflow/reviewed_ruby_gem.md), configure `Workflow::ReviewedRubyGem` in the Rakefile. Optional `prepare-artifacts` prepares explicit input archives after Ruby setup, before loading release tasks for input configuration and capture; `artifacts` adds newline-separated paths to artifact preservation. Both default to empty. Caller-provided commands retain release privileges and must use reviewed inputs. +- Set inputs under the step's `with:`, not the job's. +- All inputs are strings, and there is no `dry-run` input. +- `gemfile` defaults to empty, which keeps any `BUNDLE_GEMFILE` your job already sets. A value is exported for all later steps before Ruby setup. +- Inputs are exported through `GITHUB_ENV`, so they stay set for later steps in your job. `release:workflow:configure` rejects line breaks before exporting anything. +- `timezone` exports `TZ`, which also affects your later steps. See [Timezone](release.md#timezone). +- `failure` only sees failures inside the action, not in your own steps. See [Success and Failure Callbacks](release.md#success-and-failure-callbacks). -Inputs are exported through `GITHUB_ENV` for subsequent steps in the job. `release:workflow:configure` rejects line breaks before exporting any values. Override commands execute with release privileges and must be trusted. +Dispatching the sample workflow starts a real release once environment protection rules pass. Command overrides run with release credentials and must be trusted. For `validate` and `version`, see [Release Validation](release.md#release-validation) and [Release Version](release.md#release-version). -`validate` checks preconditions before preparation and must exit nonzero on failure, including when there is nothing to release. Failure handling runs; downstream release operations do not. See [Release Validation](release.md#release-validation). - -The optional `version` input selects a release version in standard preparation. The configured version object's `set!` writes the selection; custom preparation commands and callbacks own their file updates and must honor the selection. An empty input releases the checked-in version. See [Release Version](release.md#release-version) for dispatch examples. - -The optional `timezone` input defaults to `UTC`; set `timezone: America/New_York` for Eastern Time, including daylight saving changes. The action validates the identifier and exports `TZ`, affecting subsequent release steps and any later steps in the caller's job. See [Timezone](release.md#timezone) for date capture and service timestamp behavior. - -The optional `success` and `failure` command inputs default to `bundle exec rake release:success` and `bundle exec rake release:failure`. Success runs after publication and the next development iteration succeed. Failure runs after a failed phase inside the composite action once Ruby setup has completed and receives a `RubyGemRelease::ReleaseFailure` with a captured Ruby exception when available. It cannot observe or handle failures in caller steps that run outside the action. See [Success and Failure Callbacks](release.md#success-and-failure-callbacks). +For [already-reviewed source and package collections](../workflow/reviewed_ruby_gem.md), configure `Workflow::ReviewedRubyGem` in the Rakefile. `prepare-artifacts` runs after Ruby setup, before the release tasks load, to prepare explicit input archives. `artifacts` adds paths to preserve, one per line. Both default to empty and must use reviewed inputs. ## Trusted Publishing -Register a RubyGems trusted publisher for the calling repository, its own workflow filename (`release.yml` above), and environment `release`. Leave the optional Workflow Repository fields blank: the composite action is a step in your workflow, not a reusable workflow from another repository. +Register a RubyGems trusted publisher with your repository, your workflow filename (`release.yml` above), and environment `release`. Leave the Workflow Repository fields blank: the action is a step in your workflow, not a reusable workflow from another repository. -For maintainer-only publication, protect the caller job's `release` environment using [Maintainer-Approved Publication](../../RELEASING.md#maintainer-approved-publication). Other repository writers can dispatch, but publication waits for a designated maintainer to approve. Environments do not restrict who can dispatch, and an environment without protection rules does not restrict release access. +For first publication, pass the numeric account ID from the pending trusted publisher as `rubygems-owner`; omit it later. `release:publish` logs in with the [credentials helper](../workflow/ruby_gems_credentials.md) without a stored API key or `~/.gem/credentials`. A `publish` override that skips that task must log in itself. -The action checks [release prerequisites](release.md#release-prerequisites), including the trusted publisher and the token's ability to push the release commit and tag, after context capture and before validation, edits, or publication. To check without releasing, run `bundle exec rake release:workflow:preflight` in a job of the same workflow file, in the `release` environment, with `id-token: write`. RubyGems matches the workflow file and environment, so a check from another workflow or environment does not prove the release job's configuration. The composite action has no dry-run input. +To require approval from a maintainer, protect the `release` environment with [Maintainer-Approved Publication](../../RELEASING.md#maintainer-approved-publication). Other writers can still dispatch, but publication waits for approval. Environments can't limit who dispatches, and one without protection rules restricts nothing. -For first publication, register a pending trusted publisher and supply its numeric account ID through `rubygems-owner`. Later publications can omit that input. The default `release:publish` task authenticates through the configured destination before invoking its publication callback; no separate YAML authentication step is needed. The RubyGems destination uses the [Ruby credentials helper](../workflow/ruby_gems_credentials.md) without a stored API key. It exports environment variables and does not create or modify `~/.gem/credentials`. Command overrides that bypass the task must own authentication as well as publication. +The action runs the [release prerequisites](release.md#release-prerequisites) check before any edit or publication. To check without releasing, run `bundle exec rake release:workflow:preflight` in a job in the same workflow file and `release` environment, with `id-token: write`. RubyGems matches the workflow file and environment, so a check from elsewhere proves nothing about the release job. ## Release and Recovery -With the sample, dispatch a first release using `gh workflow run release.yml -f rubygems-owner=YOUR_ACCOUNT_ID`, replacing `YOUR_ACCOUNT_ID` with your numeric account ID. For subsequent releases, omit `rubygems-owner`. Validate locally before authorizing publication. +Dispatch the first release with `gh workflow run release.yml -f rubygems-owner=YOUR_ACCOUNT_ID`, using your numeric account ID. For later releases, omit `rubygems-owner`. Validate locally before you approve publication. -Do not merge into the default branch while a release runs; see [recovery](release.md#default-branch-advanced-during-publication). Artifacts must be preserved before publication. Reruns use the supplied checkout and inputs, not restored context or automatically discovered unfinished releases. See [Verify and Recover](../../RELEASING.md#verify-and-recover). +Do not merge into the default branch while a release runs; see [recovery](release.md#default-branch-advanced-during-publication). Reruns never restore an earlier run or pick up unfinished releases. See [Verify and Recover](../../RELEASING.md#verify-and-recover). diff --git a/docs/actions/release.md b/docs/actions/release.md index 248dea4..90fe983 100644 --- a/docs/actions/release.md +++ b/docs/actions/release.md @@ -1,49 +1,51 @@ # GitHub Actions Release Workflow -Reference for [`.github/workflows/release.yml`](../../.github/workflows/release.yml), invoked with `workflow_call`. See [Usage](../../README.md#usage) for a caller example and [Detailed Usage](../usage.md#configuration) for customization. See [RELEASING.md](../../RELEASING.md#one-time-setup) for branch permissions. Trusted Publishing is required setup in [Usage](../../README.md#3-enable-trusted-publishing). +Reference for the reusable workflow [`.github/workflows/release.yml`](../../.github/workflows/release.yml). For setup, including required [Trusted Publishing](../../README.md#3-enable-trusted-publishing), see [Usage](../../README.md#usage). For customization, see [Detailed Usage](../usage.md#configuration); for branch permissions, see [RELEASING.md](../../RELEASING.md#one-time-setup). -For a step-based interface with caller-owned job settings, see the [Composite Action](action.md). Both interfaces invoke the same Ruby release tasks; the reusable workflow keeps its own runner, environment, permissions contract, and concurrency group. +To control the runner, environment, permissions, and concurrency yourself, use the [Composite Action](action.md). Both run the same Ruby release tasks. -Every action the workflow uses is pinned to a commit SHA. RubyGems Trusted Publishing accepts any ref of this repository, so pin the `uses:` line in your caller to the commit of a release tag, with the tag in a trailing comment, such as `dblock/ruby-gem-release/.github/workflows/release.yml@ # v0.8.0`. That fixes both this workflow and the actions it runs with release credentials. +This workflow pins every action it uses to a commit SHA. RubyGems Trusted Publishing accepts any ref of this repository, so pin your `uses:` line to a release tag's commit, with the tag in a comment, such as `dblock/ruby-gem-release/.github/workflows/release.yml@ # v0.8.0`. That locks both this workflow and the actions it runs with release credentials. ## Inputs -Set these under the calling job's `with:` mapping. Only `ruby-version` is required. - -| Input | Type | Default | Behavior | -| --- | --- | --- | --- | -| `ruby-version` | String | Required | Ruby version used for validation and building. | -| `version` | String | Empty | Selected numeric `MAJOR.MINOR.PATCH` release version, without leading zeros. Overrides the checked-in version in standard preparation. | -| `gemspec` | String | Empty | Specification path, defaulting to the only root gemspec. Missing or ambiguous specifications fail. | -| `gemfile` | String | `Gemfile` | Gemfile Bundler installs and every release step runs in, set as `BUNDLE_GEMFILE` before Ruby setup. See [Release Gemfile](#release-gemfile). | -| `rubygems-owner` | String | Empty | Numeric RubyGems account ID required for a new gem's pending trusted publisher to create it. | -| `timezone` | String | `UTC` | Installed timezone identifier for the release calendar date and Git timestamp offsets. | -| `prepare-artifacts` | String | Empty | Trusted command preparing explicitly selected input archives after setup, before capture. | -| `artifacts` | String | Empty | Additional newline-separated artifact paths preserved before publication, alongside default paths. | -| `validate` | String | `bundle exec rake release:validate` | Check release preconditions before edits; exit nonzero on failure. | -| `prepare` | String | `bundle exec rake release:prepare` | Prepare release files before version resolution and testing. | -| `test` | String | `bundle exec rake` | Test prepared release files before publication. | -| `publish` | String | `bundle exec rake release:publish` | Commit, build, tag, publish to RubyGems, push atomically, and create a GitHub Release through the configured callback. | -| `bump` | String | `bundle exec rake release:bump` | Prepare, commit, and push the next development iteration through the configured callback. | -| `success` | String | `bundle exec rake release:success` | Run after publication and the next development iteration succeed. | -| `failure` | String | `bundle exec rake release:failure` | Run after a release job failure, after Ruby setup. | -| `git-user-name` | String | `github-actions[bot]` | Checkout-local author name for release and next development iteration commits. | -| `git-user-email` | String | `github-actions[bot]@users.noreply.github.com` | Checkout-local author email for release and next development iteration commits. | -| `dry-run` | Boolean | `false` | Check release prerequisites, such as RubyGems Trusted Publishing, without editing files, pushing, or publishing. See [Dry Run](#dry-run). | - -Identity values must be nonempty and contain no line breaks. They change commit attribution, not authentication or push permissions. +Set these under `with:`. Only `ruby-version` is required. + +| Input | Type | Default | Behavior | +| --- | --- | --- | --- | +| `ruby-version` | String | Required | Ruby version used to validate and build. | +| `version` | String | Empty | Release version, as `MAJOR.MINOR.PATCH` without leading zeros. Overrides the checked-in version. See [Release Version](#release-version). | +| `gemspec` | String | Empty | Gemspec path. Defaults to the only gemspec in the root; fails if there are none or several. | +| `gemfile` | String | `Gemfile` | Gemfile for Bundler and every release step. See [Release Gemfile](#release-gemfile). | +| `rubygems-owner` | String | Empty | Your numeric RubyGems account ID. Required only for a gem's first release. | +| `timezone` | String | `UTC` | Timezone for the release date and Git timestamps. See [Timezone](#timezone). | +| `prepare-artifacts` | String | Empty | Trusted command that prepares explicitly chosen input archives after setup, before capture. | +| `artifacts` | String | Empty | Extra paths to preserve before publication, one per line, in addition to the defaults. | +| `validate` | String | `bundle exec rake release:validate` | Checks that a release can start, before any edits. Must exit nonzero on failure. | +| `prepare` | String | `bundle exec rake release:prepare` | Updates release files before tests. | +| `test` | String | `bundle exec rake` | Tests the prepared release before publication. | +| `publish` | String | `bundle exec rake release:publish` | Commits, builds, tags, publishes to RubyGems, pushes, and creates a GitHub Release. | +| `bump` | String | `bundle exec rake release:bump` | Prepares, commits, and pushes the next development version. | +| `success` | String | `bundle exec rake release:success` | Runs after publication and the version bump succeed. | +| `failure` | String | `bundle exec rake release:failure` | Runs after a failure, once Ruby is set up. | +| `git-user-name` | String | `github-actions[bot]` | Author name for release and version bump commits. | +| `git-user-email` | String | `github-actions[bot]@users.noreply.github.com` | Author email for release and version bump commits. | +| `dry-run` | Boolean | `false` | Only checks prerequisites. Edits, pushes, and publishes nothing. See [Dry Run](#dry-run). | + +"Capture" is the first release step. It records the checkout, gemspec, version, and date for later steps. The author name and email must be nonempty single lines; they affect commit authorship only, not authentication. ### Release Prerequisites -Every release runs `bundle exec rake release:workflow:preflight` after context capture, before validation, edits, or publication, so missing permissions fail before anything is pushed or published. The preflight requests the job's OIDC token and exchanges it at RubyGems exactly as publication does, passing `rubygems-owner` when set. Success proves that the caller granted `id-token: write` and that a trusted publisher matches the repository, workflow, and environment in the token. The job reports those claims and the credential's scopes; on failure, the error names the claims RubyGems rejected. The exchanged credential is masked, expires after 15 minutes, and is never exported or used; publication performs its own exchange. RubyGems does not report which gems a publisher is attached to, so the preflight cannot confirm that the publisher belongs to this gem, or that RubyGems would accept the package. +Every release first runs `bundle exec rake release:workflow:preflight`, so missing permissions fail before any edit, push, or publication. It checks: -On GitHub Actions, the preflight also checks that the job's token can push the release. `git push --dry-run` to the default branch fails without `contents: write`; GitHub requires push access to start a push, and a dry run sends no objects and changes no refs. It then reads the [repository rules](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/about-rulesets) that apply to the default branch and to the `vVERSION` release tag. Branch rules requiring pull requests, status checks, signed commits, deployments, a merge queue, or restricting updates, and tag rules restricting creation or requiring signatures, fail the preflight unless the ruleset reports that the token can bypass it. Classic branch protection rules are not readable without admin access, so a protected default branch produces a warning instead. +- **Trusted Publishing:** it exchanges the job's OIDC token at RubyGems exactly as publication does, with `rubygems-owner` when set. Success means the caller granted `id-token: write` and a trusted publisher matches the repository, workflow, and environment. The job prints the token claims and credential scopes, or the claims RubyGems rejected. The credential is masked, expires in 15 minutes, and is never used. +- **Push access:** `git push --dry-run` to the default branch fails without `contents: write`. It sends nothing. +- **Repository rules:** it reads the [rulesets](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/about-rulesets) for the default branch and the `vVERSION` tag. Branch rules that require pull requests, status checks, signed commits, deployments, or a merge queue, or that restrict updates, fail the check. So do tag rules that restrict creation or require signatures. Rules the token can bypass are fine. -### Dry Run +The check cannot confirm the publisher belongs to this gem, or that RubyGems will accept the package, because RubyGems doesn't expose that. Classic branch protection needs admin access to read, so it only produces a warning. -Set `dry-run: true` to run only the release prerequisites. A separate `preflight` job runs instead of the `release` job, in the same `release` environment, so required reviewers still approve it. It checks out the caller, installs the bundle, captures the release context, and runs the same [prerequisite checks](#release-prerequisites). It never edits files, commits, tags, pushes, builds, or publishes. +### Dry Run -To dispatch dry runs, add a boolean input to the caller and pass it through: +Set `dry-run: true` to run only the [prerequisite checks](#release-prerequisites). A separate `preflight` job replaces the `release` job, in the same `release` environment, so required reviewers still approve it. It never edits, commits, tags, pushes, builds, or publishes. To dispatch dry runs, add a boolean input: ```yaml on: @@ -66,23 +68,21 @@ Then run `gh workflow run release.yml -f dry-run=true`. ### Release Validation -Validation runs after context capture, before preparation edits. Empty pending notes fail unless the selected release already has a changelog heading, allowing repetition. Malformed content also fails. With no changelog, validation passes. Custom changelog objects implement `pending?` and `released?(version)` or supply a `validate:` callback. - -A custom `validate` command must exit nonzero on invalid state; normal completion succeeds. Ruby callbacks raise on failure, and returning `false` also fails. No output protocol is required. +Validation runs after capture, before any edits. It fails if the changelog is malformed, or has no pending notes and no heading for this version. An existing heading lets you rerun a release. Without a changelog, validation passes. Custom changelog classes implement `pending?` and `released?(version)`, or you supply a `validate:` callback. -A validation error fails the job, stops downstream release operations, and invokes failure handling after successful Ruby setup. +A custom `validate` command fails by exiting nonzero. A Ruby callback fails by raising or returning `false`. A failure skips all later steps and runs `failure` if Ruby is set up. ### Release Version -Set `version: '1.2.3'` under `with:` to select a release version instead of the one checked in. The standard workflow calls the configured version object's `set!` method before preparing the changelog; an empty input leaves the checked-in version unchanged. The release commit includes the version and changelog changes, and the next development iteration increments from the selected version. The initial gemspec version and captured date remain available to callbacks. +Set `version: '1.2.3'` to release that version instead of the checked-in one; empty keeps the checked-in version. The standard workflow writes it with the version object's `set!` before updating the changelog. The release commit includes both changes, and the next development version is bumped from it. Callbacks still see the original gemspec version and the captured date. -Expose a string `version` input in the caller's `workflow_dispatch` form and forward it with `version: ${{ inputs.version }}`. You can then choose it in GitHub's form or run `gh workflow run release.yml -f version=1.2.3`. No release is performed by adding this input. +To pick the version at dispatch time, add a string `version` input to `workflow_dispatch` and pass `version: ${{ inputs.version }}`. Then use the GitHub form or `gh workflow run release.yml -f version=1.2.3`. -Custom preparation commands and callbacks must honor the selection; resolution rejects a mismatched prepared gemspec before publication. Custom version objects must implement `read`, `set!`, and `increment!`. See [UPGRADING.md](../../UPGRADING.md) for migrations. +Custom `prepare` commands and callbacks must apply the selected version; a mismatched prepared gemspec fails before publication. Custom version objects implement `read`, `set!`, and `increment!`. See [UPGRADING.md](../../UPGRADING.md) for migrations. ### Release Gemfile -To keep `ruby-gem-release` and its optional dependencies out of every contributor's and CI variant's bundle, put them in a separate Gemfile that evaluates the main one, and pass it as `gemfile:`: +To keep `ruby-gem-release` out of your normal bundle, put it in a separate Gemfile that loads the main one, and pass it as `gemfile:`: ```ruby # gemfiles/release.gemfile @@ -92,49 +92,48 @@ gem 'commonmarker', '~> 2.10', require: false gem 'ruby-gem-release', '0.9.0', require: false ``` -The workflow sets `BUNDLE_GEMFILE` for the whole job before `ruby/setup-ruby` installs the bundle, so the built-in `bundle exec rake release:workflow:*` steps and the default commands, including the `test` command's full suite, run in that bundle. Commit or ignore the lockfile Bundler writes next to the selected Gemfile: capture rejects an untracked lockfile as an unclean checkout. Guard the release task setup in your Rakefile with `rescue LoadError` so the main bundle can still load it without the gem. +The workflow sets `BUNDLE_GEMFILE` for the whole job, so every step and default command, including the full `test` suite, uses this bundle. Commit or ignore the lockfile Bundler writes next to it; an untracked lockfile fails the clean-checkout check. In your Rakefile, wrap the release task setup in `rescue LoadError` so the main bundle works without the gem. ### Timezone -Set `timezone: America/New_York` under `with:` to use Eastern Time, including daylight saving changes. UTC remains the default. +Set `timezone: America/New_York` to use Eastern Time, including daylight saving. The default is UTC. -The interfaces set `TZ` and capture the local calendar date once as `RELEASE_DATE`, preserving it across callbacks even if the release crosses midnight. Git commits retain their actual creation times with offsets in the selected timezone. GitHub and RubyGems generate their own publication timestamps; this input does not change those service timestamps. +The workflow sets `TZ` and records the date once as `RELEASE_DATE`, so it doesn't change if the release runs past midnight. Git commit times are shown in this timezone. GitHub and RubyGems timestamps are not affected. -Identifiers must resolve to files under the runner's `/usr/share/zoneinfo` directory. Unknown identifiers, empty values, fixed-offset strings, and traversal paths fail before release preparation or publication. Use a named timezone rather than a fixed offset so daylight saving changes are handled correctly. - -To disable only GitHub Release creation, set `hosting: nil` in the standard workflow or omit `github.publish!` from manual callbacks rather than disabling `publish`. +Use a name from `/usr/share/zoneinfo`, not a fixed offset. Unknown names, empty values, fixed offsets, and paths fail before anything is prepared. ### Success and Failure Callbacks -The `success` command runs after the publication and next development iteration phases succeed. The `failure` command runs after a failed phase once Ruby setup has completed; its callback receives a `RubyGemRelease::ReleaseFailure` with the failed phase, an exception captured from a Ruby task when available, and an execution context whose release value is optional. Failures reported only by GitHub Actions have no exception object. Both default to optional Rake callbacks and are no-ops when none are registered. Failure before Ruby setup or a job blocked by environment protection cannot invoke the callback. +`success` runs after publication and the version bump succeed. `failure` runs after a failed step, once Ruby is set up. Its callback gets a `RubyGemRelease::ReleaseFailure` with the failed phase, the Ruby exception if there is one (failures reported only by GitHub Actions have none), and the execution context, whose release may be missing. Both do nothing unless you register callbacks. `failure` can't run if the job fails before Ruby setup or is blocked by environment protection. ## Permissions and Authentication -Once the repository and gem owners complete setup, collaborators with write access can [dispatch the release workflow](https://docs.github.com/en/actions/how-tos/manage-workflow-runs/manually-run-a-workflow), including in personal repositories. They do not need repository admin access, RubyGems ownership, or their own RubyGems API key. Dispatch permission is not publication approval: with [required maintainer reviewers](../../RELEASING.md#maintainer-approved-publication), publication remains blocked until a designated maintainer approves the `release` environment. - -Environments do not provide a workflow-dispatch allow list, and creating one without protection rules does not restrict release access. +The caller needs `contents: write` to push and create the GitHub Release, and `id-token: write` for Trusted Publishing. Set up the `release` environment and trusted publisher as in [Usage](../../README.md#3-enable-trusted-publishing). You don't store a RubyGems API key. -Authentication belongs to `release:publish`, which invokes the configured destination's authentication hook before its publication callback. Neither YAML interface contains a registry-specific authentication step or condition. The RubyGems destination uses [`RubyGemsCredentials`](../workflow/ruby_gems_credentials.md), requesting a GitHub OIDC token for audience `rubygems.org`, exchanging it, masking both credentials, and exporting the short-lived key for publication. For a brand-new gem, register a pending trusted publisher and set `rubygems-owner` to the numeric account ID shown on that page; the helper includes that owner assertion. For existing gems, omit the input and the exchange omits the owner field. +After setup, anyone with write access can [dispatch the workflow](https://docs.github.com/en/actions/how-tos/manage-workflow-runs/manually-run-a-workflow), even in personal repositories, without admin access, RubyGems ownership, or an API key. Dispatching is not approval: with [required reviewers](../../RELEASING.md#maintainer-approved-publication), publication waits for a maintainer to approve the `release` environment. Environments can't limit who dispatches, and one without protection rules restricts nothing. -Authentication exports `RUBYGEMS_API_KEY`, `BUNDLE_GEM__PUSH_KEY`, and `GEM_HOST_API_KEY`; it does not create or modify `~/.gem/credentials`. Custom publication commands must inherit these variables rather than assume a credentials file or named key exists. See the [custom publication contract](../workflow/ruby_gems_credentials.md#custom-publication-commands). +`release:publish` logs in to the registry just before publishing; there is no separate login step in YAML. For RubyGems, [`RubyGemsCredentials`](../workflow/ruby_gems_credentials.md) exchanges a GitHub OIDC token (audience `rubygems.org`) for a short-lived API key and masks both. It sends `rubygems-owner` for a new gem; leave it empty for an existing gem. -The caller needs `contents: write` for Git and hosting and `id-token: write` for RubyGems Trusted Publishing. Configure the `release` environment and publisher as described in [Usage](../../README.md#3-enable-trusted-publishing). No stored RubyGems API key is required. +The key is exported as `RUBYGEMS_API_KEY`, `BUNDLE_GEM__PUSH_KEY`, and `GEM_HOST_API_KEY`; `~/.gem/credentials` is not touched. Custom publication commands must use these variables. See the [custom publication contract](../workflow/ruby_gems_credentials.md#custom-publication-commands). -The base destination's authentication hook retains preconfigured credentials. Custom destinations can override it without adding or changing YAML steps. A `publish` command override that bypasses `release:publish` must own authentication as well as publication. See [Registry Destinations](../destination.md). +The base destination uses existing credentials, and custom destinations can override login without YAML changes. A `publish` override that skips `release:publish` must log in itself. See [Registry Destinations](../destination.md). -The workflow supplies `GH_TOKEN` during publication. Branch rules must permit fast-forward pushes while retaining force-push and deletion restrictions. +The workflow sets `GH_TOKEN` during publication. Branch rules must allow fast-forward pushes; force-push and deletion restrictions can stay. ## Execution -After `ruby/setup-ruby` installs dependencies, context capture requires a clean checkout before preparation: tracked/index changes and untracked non-ignored files fail with actionable paths. Ignored Bundler output is allowed; tracked dependency artifacts are not. Resolving the prepared version stages the trusted `prepare` command's outputs and records the index tree before testing. The publication callback refuses later working tree or index changes rather than staging unrelated files. Custom commands own their operations; wrap custom next development iteration edits in `git.stage_changes!` as shown in [Detailed Usage](../usage.md#custom-callbacks). +The job runs on `ubuntu-latest` in the `release` environment with a full checkout. Releases share one concurrency group per repository, so a new release waits rather than canceling a running one. -The job runs on `ubuntu-latest` in the `release` environment. After full checkout and Ruby setup, capture uses the current checkout and inputs. Commands always run and own their idempotence; there is no cross-run artifact discovery or state restoration. A checkpoint commits, builds, and tags locally; artifact preservation must succeed before `publish` and `bump`. Failures prevent later phases. +1. **Capture:** after Ruby setup, the checkout must be clean. Changed, staged, or untracked files fail with their paths. Ignored Bundler output is fine; tracked dependency files are not. +2. **Validate, prepare, test:** files changed by `prepare` are staged before tests. Publication rejects any later change instead of committing it. Custom bump callbacks wrap edits in `git.stage_changes!`, as in [Detailed Usage](../usage.md#custom-callbacks). +3. **Checkpoint:** the workflow commits, builds, and tags locally, then uploads [recovery artifacts](#recovery-artifacts). This must succeed before `publish` and `bump`. +4. **Publish, bump, notify:** any failure stops later steps. -New releases require the current default-branch commit. Reruns can reuse matching release commits and tags without rewinding remote descendants. Git rejects conflicting tags and unrelated advancement. Concurrency is grouped by repository without canceling a running release. +A new release must start from the latest default-branch commit. Each run uses only the current checkout and inputs; it never restores an earlier run, so commands must be safe to rerun. A rerun reuses a matching release commit and tag without rewinding later remote commits. Conflicting tags and unrelated branch changes fail. ## Command Environment -Commands run through `bash -euo pipefail`. Overrides replace the corresponding phase and must perform its required operations; callback registration alone does not cause an overridden command to invoke a task. +Commands run with `bash -euo pipefail`. An override replaces the whole step and must do its work; registered callbacks don't run unless your command calls them. To turn off only GitHub Releases, set `hosting: nil` (or drop `github.publish!` from custom callbacks) rather than overriding `publish`. | Variable | Availability | Meaning | | --- | --- | --- | @@ -160,17 +159,19 @@ Commands run through `bash -euo pipefail`. Overrides replace the corresponding p | `SOURCE_DATE_EPOCH` | After capture | Source commit timestamp for reproducible packages, unless explicitly supplied. | | `GH_TOKEN` | Publish | GitHub Actions token for hosted releases. | -GitHub also supplies standard variables such as `GITHUB_REPOSITORY` and `RUNNER_TEMP`. See [Execution Context](../execution_context.md) for step, run, and state semantics, [`Tasks`](../tasks.md) for callbacks, and [`Workflow::Environment`](../workflow/environment.md) for capture and resolution methods. +GitHub also sets variables such as `GITHUB_REPOSITORY` and `RUNNER_TEMP`. See [Execution Context](../execution_context.md), [`Tasks`](../tasks.md), and [`Workflow::Environment`](../workflow/environment.md). ## Recovery Artifacts -The workflow requires `release.gem`, its name/version/digest manifest `release.json`, and `release.bundle` to be uploaded before publication, retained for 30 days under `release-gem-VERSION-RUN_ID-RUN_ATTEMPT`. These support manual inspection, not automatic restoration. See [RELEASING.md](../../RELEASING.md#verify-and-recover) and [recovery when the default branch advances during publication](#default-branch-advanced-during-publication). +Before publishing, the workflow must upload `release.gem` (the built gem), `release.json` (its name, version, and digest), and `release.bundle` (the release commit and tag), kept 30 days as `release-gem-VERSION-RUN_ID-RUN_ATTEMPT`. They are for manual inspection; nothing restores them automatically. See [RELEASING.md](../../RELEASING.md#verify-and-recover). -For already-reviewed commits, stable branches, existing signed tags, and explicitly supplied package collections, use the [reviewed workflow](../workflow/reviewed_ruby_gem.md). It retains publication guards but makes no release preparation commits, new tags, Git pushes, or development bumps. `prepare-artifacts` and `artifacts` support explicit retained inputs without artifact discovery; both interfaces expose the same inputs. +To publish reviewed commits, stable branches, existing signed tags, or package collections, use the [reviewed workflow](../workflow/reviewed_ruby_gem.md). It keeps the publication checks but makes no commits, tags, pushes, or bumps. Its explicit inputs go in `prepare-artifacts` and `artifacts`; the workflow never searches for artifacts. ### Default Branch Advanced During Publication -Do not merge into the default branch while a release runs. The tag step fails before publication if the branch has moved since capture, but a merge after that check and before the release push leaves the gem published on RubyGems while the push fails with `Default branch advanced; start a new release`. The release tag, the release commit on the default branch, the GitHub Release, and the next development iteration are then missing. Rerunning does not recover: each run creates a new release commit, and tagging requires the branch to still be at the source commit. Recover manually from the preserved artifacts instead, replacing `1.2.3`, `example`, `RUN_ID`, and `ATTEMPT`: +Do not merge into the default branch while a release runs. If the branch moves before tagging, the release stops before publishing. If it moves after that, the gem is published but the push fails with `Default branch advanced; start a new release`, leaving no tag, release commit, GitHub Release, or next development version. + +Rerunning won't fix this: each run makes a new release commit, and tagging needs the branch at the source commit. Recover by hand from the artifacts, replacing `1.2.3`, `example`, `RUN_ID`, and `ATTEMPT`: **Step 1.** Download the failed run's artifacts and confirm RubyGems published the preserved archive: @@ -206,4 +207,4 @@ gh release create v1.2.3 --verify-tag --title v1.2.3 --notes-file NOTES.md examp **Step 5.** Start the next development iteration in a pull request that increments the version and adds the Next changelog section, as the bump would have. -Do not dispatch a new release of the same version. RubyGems accepts only the identical archive, and a rebuilt release commit would not match the pushed tag. +Do not dispatch the same version again. RubyGems only accepts the identical archive, and a rebuilt release commit would not match the pushed tag. diff --git a/docs/changelog/base.md b/docs/changelog/base.md index d73e9d0..dc3423b 100644 --- a/docs/changelog/base.md +++ b/docs/changelog/base.md @@ -1,6 +1,6 @@ # `RubyGemRelease::Changelog::Base` -Shared implementation for [`Intridea`](intridea.md) and [`KeepAChangelog`](keep_a_changelog.md). Use those concrete classes rather than constructing Base directly. +The shared parent of [`Intridea`](intridea.md) and [`KeepAChangelog`](keep_a_changelog.md). Use those classes, not `Base`. ## Path @@ -8,26 +8,30 @@ Shared implementation for [`Intridea`](intridea.md) and [`KeepAChangelog`](keep_ ## Pending Notes -`pending?` reads the current unreleased section without writing files. It returns `true` when actual notes exist and `false` for an empty or structural-only section, ignoring historical notes and the configured `Intridea` placeholder. Missing or duplicate release headings, invalid line endings, malformed comparison links, and missing or duplicate placeholders raise errors rather than reporting no changes. +`pending?` returns whether the unreleased section has real notes, without writing. Older releases and the `Intridea` placeholder do not count. A malformed file raises instead of returning `false`: missing or duplicate release headings or placeholders, bad comparison links, or invalid line endings. -Default validation requires an existing selected release or pending notes; otherwise it raises. +The standard workflow's validation raises unless the version already has a release heading or `pending?` is `true`. ## Release -`released?(version)` returns whether that version has a release heading; duplicates raise. `release!(release)` reuses an existing heading unchanged, or delegates the version and date to the concrete format implementation. +`released?(version)` returns whether that version has a release heading. Duplicates raise. -New releases require nonempty notes. Only the current section counts, ending at the next heading of equal or shallower depth. Blank lines, category headings, HTML comments or blocks, reference definitions, and the configured `Intridea` contribution placeholder are not notes. Text, lists, quotes, and code with content count. Errors identify the version and changelog path. +`release!(release)` turns the unreleased heading into a release heading with the version and date. If the version is already released, it changes nothing, so retries are safe. + +A new release needs real notes in the unreleased section, which ends at the next heading of the same or higher level. Text, lists, quotes, and nonempty code count. Blank lines, category headings, HTML, link definitions, and the `Intridea` placeholder do not. Errors name the version and changelog path. ## Notes -`notes(version)` returns the released section for that version, read without editing the file. It uses the format's own release heading, expands reference links inline, and drops link definitions trailing the section, as [read-only notes](notes.md) do with `expand_references: true`. Unreleased, missing, duplicate, or empty sections raise. The [standard workflow](../workflow/ruby_gem.md#hosting) passes the result to hosting. +`notes(version)` returns a released section's body without editing the file. Like [read-only notes](notes.md) with `expand_references: true`, it makes reference links inline and drops trailing link definitions. Unreleased, missing, duplicate, or empty sections raise. The [standard workflow](../workflow/ruby_gem.md#hosting) passes the result to hosting. ## Prepare Next -`prepare_next!(release)` delegates the released version and the version for the next development iteration to the concrete format implementation. +`prepare_next!(release)` adds an unreleased section for `release.next_version` above the `release.version` section. ## Source Preservation -Uses `Commonmarker` to identify top-level headings and exclude code, HTML, and quoted blocks. Updates edit the original source rather than rendering the parsed document again, preserving unrelated formatting. Unix and Windows line endings are supported; mixed line endings or standalone carriage returns are rejected. +Parsing uses `Commonmarker`. Only top-level headings count; headings in code, HTML, quotes, or other nested blocks are ignored. Edits change the original text in place, so other formatting is kept. -Hash-style release headings support depths 1 through 6, and their hash count is preserved. Headings inside nested blocks remain excluded. Multiple matching release headings are rejected even when their depths differ. +- Unix and Windows line endings work. Mixed endings or lone carriage returns raise. +- Release headings can use one to six `#`; edits keep the level. +- Two headings for one version raise, even at different levels. diff --git a/docs/changelog/intridea.md b/docs/changelog/intridea.md index 0f42634..49d8f5f 100644 --- a/docs/changelog/intridea.md +++ b/docs/changelog/intridea.md @@ -1,8 +1,6 @@ # `RubyGemRelease::Changelog::Intridea` -Updates changelog files with `## VERSION (Next)` and `## VERSION (YYYY/MM/DD)` headings, such as this project's [CHANGELOG.md](../../CHANGELOG.md). Inherits the shared source handling from [Base](base.md). - -Release headings can use any Markdown depth from `#` through `######`, including `### VERSION (Next)`. Both phases preserve the matched heading's depth; no configuration or changelog reformatting is required. Deeper subsection headings stay inside the release section, which ends at the next heading of equal or shallower depth. +Updates a changelog with `## VERSION (Next)` and `## VERSION (YYYY/MM/DD)` headings, like this project's [CHANGELOG.md](../../CHANGELOG.md). Shared behavior is in [Base](base.md). ```ruby require 'ruby-gem-release/changelog' @@ -10,32 +8,34 @@ require 'ruby-gem-release/changelog' changelog = RubyGemRelease::Changelog::Intridea.new(path: 'CHANGELOG.md') ``` +Headings can use any level from `#` to `######`; edits keep it. Deeper headings belong to the release section. + ## Path -`path:` defaults to `'CHANGELOG.md'`. The class owns file reading and writing. +`path:` defaults to `'CHANGELOG.md'`. ## Placeholder -`placeholder:` defaults to `'- Your contribution here.'`. Set `placeholder: '* Your contribution here.'` for the alternative bullet. It must be a single nonempty line, configured identically for both phases. The placeholder is optional in a Next section that has release notes; contributors may replace it. A line with the placeholder's text under a different list marker, such as `* Your contribution here.` when `- Your contribution here.` is configured, fails rather than being published as a note. +`placeholder:` defaults to `'- Your contribution here.'`; use `'* Your contribution here.'` for the other bullet. It must be one nonempty line, and the same when releasing and preparing the next section. Contributors may delete it once there are notes. The same text with a different bullet raises rather than being published. ## Date -`date_format:` formats the date in the release heading. It defaults to `'%Y/%m/%d'`. Pass a `strftime` string, such as `date_format: '%Y-%m-%d'` for `## 1.0.0 (2026-11-07)`, or a callable that receives the release `Date` and returns a String for the text inside the parentheses. The formatted text must fit on one line and contain at least one digit, so headings such as `(Next)` cannot be written as releases. Otherwise `release!` raises before writing the file. Release headings written in any format are recognized as released, so changing the format does not duplicate existing releases; a parenthesized heading without a digit, such as `(TBD)`, is not. +`date_format:` sets the date inside the parentheses. It defaults to `'%Y/%m/%d'`. Pass a `strftime` string, such as `'%Y-%m-%d'` for `## 1.0.0 (2026-11-07)`, or a callable that takes the `Date` and returns a String. The result must be one line with at least one digit, or `release!` raises before writing; so `(Next)` can never become a release. + +Any parenthesized heading with a digit counts as released, so changing the format does not duplicate old releases. `(TBD)` does not count. ## Sections -When the released section has headings one level below its release heading, `prepare_next!` carries those headings into the new Next section and adds the configured placeholder under each one. With no subsections, it creates the usual single placeholder. Old subsection notes are not copied. +By default, `prepare_next!` copies the last release's subsection headings (one level down) into the new Next section, each with a placeholder. Notes are not copied, and empty subsections stay in the release. -Pass `sections:`, such as `sections: %w[Features Fixes]`, to name the subsections every Next section starts with. `release!` then removes subsection headings left without notes, so a fixes-only release has no empty `#### Features`, and `prepare_next!` always adds every configured section, including ones the previous release dropped. Names must be unique, nonempty, and on one line, and the release heading must be shallower than level six. Without `sections:`, empty subsections stay in the release and are carried forward as before. +With `sections:`, such as `%w[Features Fixes]`, every Next section starts with those subsections. `release!` removes the empty ones, so a fixes-only release has no empty `#### Features`. Names must be unique, nonempty, and one line, and the release heading must be level five or shallower. ## Release -During `release:validate`, placeholder-only or structural-only notes fail unless the selected release already has a heading. Invalid headings and placeholders marked differently from the configured one also fail; multiple matching placeholders are allowed. - -`changelog.release!(release)` replaces the Next heading with the [Release](../release.md) version and date, removing every matching placeholder from that section. Missing or duplicate headings, a mismatched placeholder, or an existing release heading fail without writing the file. +`changelog.release!(release)` replaces the Next heading with the [Release](../release.md) version and date and removes placeholder lines. Without writing, it raises on a missing or duplicate Next heading, a placeholder with the wrong bullet, or a section with no real notes (only placeholders, headings, comments, or link definitions). Add notes and retry; older releases do not count and there is no empty-release option. See [Release Notes](base.md#release). -Placeholder-only sections and sections containing only headings, comments, or reference definitions also fail without writing. Add actual release notes to the Next section before retrying; older releases do not count. There is no empty-release opt-out. See [Release Notes](base.md#release) for what counts as content. +`release:validate` runs the same checks without writing. Placeholder-only notes fail unless the version is already released. Several placeholders are allowed. ## Prepare Next -`changelog.prepare_next!(release)` inserts a Next section using `release.next_version` and the configured placeholder above the section for `release.version`. It requires exactly one matching release section and reuses an existing matching Next section. `release!` likewise reuses the selected version's existing release heading. +`changelog.prepare_next!(release)` adds a Next section for `release.next_version`, with the placeholder, above the `release.version` section. Exactly one section must match `release.version`; a Next section for another version raises. It reuses a matching Next section, and `release!` reuses an existing release heading, so both are safe to retry. diff --git a/docs/changelog/keep_a_changelog.md b/docs/changelog/keep_a_changelog.md index 5c209aa..6fa2d2e 100644 --- a/docs/changelog/keep_a_changelog.md +++ b/docs/changelog/keep_a_changelog.md @@ -1,8 +1,6 @@ # `RubyGemRelease::Changelog::KeepAChangelog` -Updates [Keep a Changelog](https://keepachangelog.com/) files with `## [Unreleased]` and `## [VERSION] - YYYY-MM-DD` headings. See the [sample changelog](../../examples/keep_a_changelog/CHANGELOG.md) and [Rakefile](../../examples/keep_a_changelog/Rakefile). Inherits shared source handling from [Base](base.md). - -Release headings can use any Markdown depth from `#` through `######`. Both phases preserve the matched heading's depth. By default, category headings and history are unchanged; optional contribution templates clean empty categories and restore the configured template. +Updates a [Keep a Changelog](https://keepachangelog.com/) file with `## [Unreleased]` and `## [VERSION] - YYYY-MM-DD` headings. See the [sample changelog](../../examples/keep_a_changelog/CHANGELOG.md) and [Rakefile](../../examples/keep_a_changelog/Rakefile). Shared behavior is in [Base](base.md). ```ruby require 'ruby-gem-release/changelog' @@ -10,13 +8,15 @@ require 'ruby-gem-release/changelog' changelog = RubyGemRelease::Changelog::KeepAChangelog.new(path: 'CHANGELOG.md') ``` +Headings can use any level from `#` to `######`; edits keep it. By default, category headings and older releases are left alone. + ## Path -`path:` defaults to `'CHANGELOG.md'`. The class owns file reading and writing. +`path:` defaults to `'CHANGELOG.md'`. ## Contribution Templates -Set `placeholder:` to ignore a project's contribution prompt during validation and remove matching lines when releasing. Set `sections:` to restore a complete category template for the next release, including categories that had no changes: +If your Unreleased section has a prompt line or a fixed category list, set `placeholder:` and `sections:`: ```ruby changelog = RubyGemRelease::Changelog::KeepAChangelog.new( @@ -25,24 +25,22 @@ changelog = RubyGemRelease::Changelog::KeepAChangelog.new( ) ``` -With either option enabled, releasing removes empty category headings while preserving real notes, code examples, history, and comparison references. Validation uses the same cleanup in memory; placeholder-only notes are not a release. Next-section preparation adds each configured category in order with the configured placeholder, if any. Categories are one heading level below the release heading. +With either set, `release!` removes placeholder lines and empty categories, keeping real notes, code, older releases, and links. Validation ignores placeholders the same way. `prepare_next!` adds each category in order, one level below the release heading, with the placeholder if set. -Both options are optional: `placeholder:` defaults to `nil` and `sections:` to `[]`, retaining the existing unmodified-note behavior and empty next section. A placeholder must be one nonempty line, and section names must be unique nonempty lines. Existing next sections are reused rather than overwritten. +`placeholder:` defaults to `nil` and must be one nonempty line. `sections:` defaults to `[]`; names must be unique, nonempty, and one line. With the defaults, notes are untouched and new Unreleased sections are empty. ## Release -During `release:validate`, empty or structural-only notes fail unless the selected release already has a heading. Invalid headings or comparison references also fail. - -`changelog.release!(release)` replaces the single Unreleased heading using the [Release](../release.md) version and date. Missing or duplicate headings, or an existing release heading, fail without writing the file. +`changelog.release!(release)` replaces the `[Unreleased]` heading with the [Release](../release.md) version and date. Before writing anything, it raises on a missing or duplicate Unreleased heading, an invalid comparison link, or a section with no real notes (only categories, comments, or links). Add notes and retry; older releases do not count and there is no empty-release option. See [Release Notes](base.md#release). -An empty Unreleased section, including category headings, comments, or comparison links without notes, fails before any file or reference update is written. Add actual release notes before retrying; older releases do not count. There is no empty-release opt-out. See [Release Notes](base.md#release) for what counts as content. +`release:validate` runs the same checks without writing. Empty notes fail unless the version is already released. ## Prepare Next -`changelog.prepare_next!(release)` inserts an Unreleased section above the section for `release.version`. It requires a valid `release.next_version` and exactly one matching release section, and reuses an existing Unreleased section. `release!` likewise reuses the selected version's existing release heading. +`changelog.prepare_next!(release)` adds an Unreleased section above the `release.version` section. It needs a valid `release.next_version` and exactly one matching section. It reuses an existing Unreleased section, and `release!` reuses an existing release heading, so both are safe to retry. ## Reference Links -An optional `[Unreleased]: https://github.com/owner/repo/compare/v1.0.0...HEAD` definition is updated to compare the new release against the development branch. A released-version comparison definition is added, preserving the URL, tag prefix, branch, historical links, and unrelated references. +An optional `[Unreleased]: https://github.com/owner/repo/compare/v1.0.0...HEAD` link is updated to compare the new release with the branch, and a link for the new version is added. URL, tag prefix, branch, older links, and other references are kept. -Comparison definitions must use a single `http://` or `https://` URL ending in `VERSION...BRANCH`, with an optional tag prefix before the numeric version. Unsupported URLs, duplicate Unreleased references, or existing references for the new release fail without writing the file. Next-section preparation verifies that the Unreleased comparison starts at the released version. Use custom callback code for other link formats. +Links must be one `http://` or `https://` URL ending in `VERSION...BRANCH`, with an optional tag prefix such as `v`. Other formats, duplicate `[Unreleased]` links, or an existing link for the new version raise without writing. `prepare_next!` checks that `[Unreleased]` starts at the released version. Handle other link formats in your own callback. diff --git a/docs/changelog/notes.md b/docs/changelog/notes.md index b786497..07073ef 100644 --- a/docs/changelog/notes.md +++ b/docs/changelog/notes.md @@ -1,6 +1,6 @@ # Read-Only Release Notes -`Changelog::Notes` reads an already-reviewed release section without editing it. The default matches Intridea date headings. Supply a callable returning an anchored regular expression to match a different project format: +`Changelog::Notes` reads one released section of a changelog, without editing it, for use as hosted release notes. ```ruby require 'ruby-gem-release/changelog/notes' @@ -12,6 +12,10 @@ notes = RubyGemRelease::Changelog::Notes.new( ).read('8.0.0') ``` -Parsing requires the optional Commonmarker dependency. Exactly one real Markdown heading must match; fenced examples do not count. Extraction stops at the next heading of the same or higher level and rejects empty notes. Original line endings and subsection formatting are retained; surrounding whitespace is stripped. +`path:` defaults to `'CHANGELOG.md'`. `heading:` defaults to Intridea date headings; for other formats, pass a callable returning an anchored regular expression. It needs the optional `commonmarker` gem. -With `expand_references: true`, resolved reference links and images become inline links, including definitions elsewhere in the source. Code, unresolved references, and existing inline links remain unchanged. Link reference definitions trailing the section, such as Keep a Changelog comparison links at the end of the file, are dropped. The source file is never written. Pass the resulting string as the release's `notes:` for hosted publication. +`read(version)` returns the section body. Exactly one real heading must match; code examples do not count. The section ends at the next heading of the same or higher level. Empty notes raise. Line endings and formatting are kept, and outer whitespace is stripped. + +With `expand_references: true` (default `false`), resolved reference links and images become inline, even if defined elsewhere. Code, unresolved references, and inline links are unchanged. Trailing link definitions, such as Keep a Changelog comparison links, are dropped. + +Pass the result as the release's `notes:`. diff --git a/docs/destination.md b/docs/destination.md index 41b0a3f..edde4c4 100644 --- a/docs/destination.md +++ b/docs/destination.md @@ -1,27 +1,27 @@ # `RubyGemRelease::Destination` -The base for package registry destinations. A destination owns registry authentication, version checks, and publication, not package construction, Git pushes, or hosted releases. [`Destination::RubyGems`](destination/ruby_gems.md) is the default and only built-in implementation. +The base class for package registries. A destination logs in, checks for an existing version, and uploads. It does not build packages, push to Git, or create hosted releases. [`Destination::RubyGems`](destination/ruby_gems.md) is the default and only built-in one. ## Contract -Implement read-only `published?(release, package:)`: return true only when the registry proves that the exact archive is present, false only for confirmed absence, and raise on mismatches or unverifiable responses. The base raises rather than assuming success. +`published?(release, package:)` must not change anything. Return `true` only when the registry proves the exact archive is there, `false` only when it confirms absence, and raise on mismatches or unverifiable responses. The base raises. -Implement `publish!(release, package:)` to verify existing publication first, skip an exact match, and upload only a confirmed missing artifact through `package.artifact(release)`. Never rebuild, overwrite, or blindly retry an ambiguous upload. +`publish!(release, package:)` must check first, skip an exact match, and upload `package.artifact(release)` only when it is confirmed missing. Never rebuild, overwrite, or blindly retry an upload with an unknown result. -The standard workflow commits, builds reproducibly, tags locally, verifies or publishes to the registry, pushes commit and tag atomically, and updates the optional hosted release. A destination failure stops before the Git push and hosted release; artifacts remain available for manual inspection. +The standard workflow commits, builds, and tags locally; checks or publishes to the registry; pushes the commit and tag together; then updates the optional hosted release. A destination error stops before the push, and the archives stay available for inspection. ## Authentication -`release:publish` calls the configured destination's `authenticate!(provider:)` before invoking its publication callback. The base hook does nothing, retaining preconfigured credentials. Override it to authenticate another registry through the supplied execution provider; no YAML authentication step or registry condition is needed. +`release:publish` calls `authenticate!(provider:)` before the publish callback. The base does nothing, keeping existing credentials. Override it to log in to another registry using the given execution provider; no YAML step is needed. -`authentication` remains the built-in authentication identifier exported as `RELEASE_AUTH_MODE` during prepared-version resolution. It defaults to `nil`; the RubyGems implementation returns `rubygems` and its hook performs Trusted Publishing when that identifier is selected. Other built-in identifiers are rejected until implemented. Custom destinations can keep `nil` and supply their own hook without RubyGems requests. +`authentication` names a built-in login method, exported as `RELEASE_AUTH_MODE` when the prepared version is resolved. The base returns `nil`; `RubyGems` returns `'rubygems'` and then uses Trusted Publishing. Other values raise. A custom destination can return `nil` and log in its own way. -Authentication failures stop the publication callback and are captured as publication failures. A missing publication callback invokes no authentication. +An authentication error stops the publish callback and counts as a publication failure. Without a publish callback, no authentication runs. ## Configuration -Pass `destination:` to [`Workflow::RubyGem`](workflow/ruby_gem.md). It is available through `ctx.workflow.destination` alongside the configured package and other components. +Pass `destination:` to [`Workflow::RubyGem`](workflow/ruby_gem.md); callbacks read it as `ctx.workflow.destination`. -For manual callbacks, pass the same `package:` and `destination:` objects to `Tasks.install` and use them in your publication callback, as shown in [Detailed Usage](usage.md#custom-callbacks). This also routes prepared-version checks and authentication selection through that destination. +For manual callbacks, pass the same `package:` and `destination:` to `Tasks.install` and use them in your publish callback, as in [Detailed Usage](usage.md#custom-callbacks). Version checks and authentication then use that destination. -Only one registry destination is selected per workflow. [`Hosting::GitHubRelease`](hosting/github_release.md) remains separate because it creates a hosted release after the tag exists remotely. +A workflow has one registry destination. [`Hosting::GitHubRelease`](hosting/github_release.md) is separate because it runs after the tag is pushed. diff --git a/docs/destination/ruby_gems.md b/docs/destination/ruby_gems.md index bdb5e21..355b32e 100644 --- a/docs/destination/ruby_gems.md +++ b/docs/destination/ruby_gems.md @@ -1,17 +1,17 @@ # `RubyGemRelease::Destination::RubyGems` -Extends [`Destination`](../destination.md) for publication to public `rubygems.org`. Package building and verification remain in [`Package::RubyGem`](../package/ruby_gem.md). +The default [`Destination`](../destination.md): publishes to `rubygems.org`. Building and checking the archive is done by [`Package::RubyGem`](../package/ruby_gem.md). -## Publish +## Check Version -`published?(release, package:)` reads the built artifact's name and version and compares RubyGems' `sha` with its SHA256 digest. HTTP 404 returns false; an exact match returns true. Missing checksums, different archives, malformed responses, and other HTTP statuses fail. +`published?(release, package:)` looks up the built gem's name and version on RubyGems and compares the registry's `sha` with the archive's SHA256. HTTP 404 returns `false` and a match returns `true`. A missing or different checksum, a malformed response, or any other status raises. Lookups use HTTPS, a 10-second connect timeout, a 30-second read timeout, no retries, and no credentials. -Readback requests use HTTPS, a 10-second connection timeout, a 30-second read timeout, and no automatic retries. No credentials are needed for readback. +## Publish -`publish!(release, package:)` skips an exact existing publication or invokes `gem push` only for confirmed absence. It does not rebuild or consult a subsequently edited gemspec. +`publish!(release, package:)` does nothing if the exact archive is already published; otherwise it runs `gem push`. If the push fails, it succeeds only when a recheck finds the exact archive. It never rebuilds or rereads an edited gemspec. -Configure credentials before calling `publish!` directly. The `release:publish` task calls this destination's `authenticate!(provider:)` first; when prepared-version resolution has selected `rubygems` authentication, it invokes [`RubyGemsCredentials`](../workflow/ruby_gems_credentials.md), with an optional owner-bound exchange for a pending publisher. Without that selection, preconfigured credentials are retained. The helper exports credentials without writing a local credentials file. +Set up credentials before calling `publish!` directly. The `release:publish` task first calls `authenticate!(provider:)`. When the workflow selected `rubygems` authentication, this uses [`RubyGemsCredentials`](../workflow/ruby_gems_credentials.md) for Trusted Publishing, optionally bound to an owner for a pending publisher. Credentials go into the environment, not a file. Otherwise, existing credentials are kept. ## Errors -Changed artifacts, identity mismatches, failed lookups, and upload failures raise without automatic retries. A later workflow reconciles an ambiguously accepted upload; see [recovery instructions](../../RELEASING.md#verify-and-recover). +Changed archives, identity mismatches, failed lookups, and failed uploads raise without retries. A later run reconciles an upload that may have been accepted; see [recovery instructions](../../RELEASING.md#verify-and-recover). diff --git a/docs/execution_context.md b/docs/execution_context.md index 173c75b..1b04655 100644 --- a/docs/execution_context.md +++ b/docs/execution_context.md @@ -1,8 +1,6 @@ # `RubyGemRelease::ExecutionContext` -Validation, preparation, publication, next development iteration, and success callbacks receive an execution context. Failure callbacks receive a `ReleaseFailure` whose `context` has the same interface. This provider-neutral base owns release data, workflow access, and explicit state recording. It is a frozen snapshot, not a workflow runner or a general-purpose mutable data store. - -The configured [execution provider](execution_provider.md) constructs contexts. Automatic selection uses [`ExecutionContext::GitHub`](execution_context/github.md) on Actions and this base elsewhere; explicit provider injection overrides detection. The base does not read GitHub environment values or interpret Actions statuses. Provider-specific metadata and step details belong to subclasses; platform I/O belongs to execution providers. +The `ctx` passed to validation, preparation, publication, next development iteration, and success callbacks. Failure callbacks get a `ReleaseFailure` whose `context` works the same way. It gives access to release data, the workflow, and recorded state. It is a frozen snapshot, not a runner or a general data store. ```ruby tasks.prepare do |ctx| @@ -11,42 +9,40 @@ tasks.prepare do |ctx| end ``` +The [execution provider](execution_provider.md) creates contexts: [`ExecutionContext::GitHub`](execution_context/github.md) on Actions, this base class elsewhere, unless you pass a provider. The base knows nothing about GitHub; subclasses add platform details and providers do platform I/O. + ## Release -`ctx.release` is the immutable [`Release`](release.md) value used by changelog, package, Git, and hosting operations. It can be `nil` in a failure callback when release capture did not complete, or in a before-capture hook. Other callbacks require valid release data. +`ctx.release` is the frozen [`Release`](release.md) used by changelog, package, Git, and hosting operations. It is `nil` in a failure callback if capture did not finish, and in hooks before capture. Other callbacks always have it. ## Lifecycle Stage -[Lifecycle hooks](workflow/hooks.md) also expose the stage, timing, and hook position as `ctx.stage`, `ctx.hook`, and `ctx.hook_index`. Failure hooks expose the original error as `ctx.failure`; ordinary callback contexts leave these fields `nil`. +[Lifecycle hooks](workflow/hooks.md) get `ctx.stage`, `ctx.hook`, and `ctx.hook_index` (the stage, timing, and position). Failure hooks get the error as `ctx.failure`. Ordinary callbacks see `nil`. ## Step -The base exposes a frozen step with the logical task ID, such as `release:prepare`. Its `steps` hash is empty because direct Rake invocation has no external execution history. Provider subclasses supply their current step and observed step snapshots; [GitHub](execution_context/github.md#steps) exposes Actions outcome and conclusion separately. +In the base, `ctx.step.id` is the task name, such as `release:prepare`, and `ctx.steps` is empty because plain Rake has no step history. Subclasses supply real steps; [GitHub](execution_context/github.md#steps) reports outcome and conclusion separately. -Execution history is a snapshot, not a record of operations inside a callback. Commit, build, tag, upload, and push remain operations inside publication, not separate tracked steps. +Steps are a snapshot. Commit, build, tag, upload, and push inside publication are not separate steps. ## Workflow -`ctx.workflow` is the configured [`Workflow::RubyGem`](workflow/ruby_gem.md) instance, with readers for `version`, `changelog`, `package`, `destination`, `git`, and `hosting`. These are the actual configured objects, not frozen or serialized copies. Each process constructs them normally through its Rakefile. - -Manual `Tasks.install` leaves the workflow `nil` unless supplied explicitly with `workflow:`. The workflow reference describes Ruby configuration, not the Actions run or YAML. +`ctx.workflow` is the configured [`Workflow::RubyGem`](workflow/ruby_gem.md), with readers for `version`, `changelog`, `package`, `destination`, `git`, and `hosting`. These are the real objects, not copies; each process builds them from its Rakefile. With manual `Tasks.install` it is `nil` unless you pass `workflow:`. It is your Ruby configuration, not the Actions run or YAML. ## Run -`ctx.run` is `nil` in the base. Provider subclasses own their run metadata; see [GitHub Run](execution_context/github.md#run). Domain operations do not depend on a hosting provider or its environment. +`ctx.run` is `nil` in the base; see [GitHub Run](execution_context/github.md#run). Release operations never depend on the hosting platform. ## State -`ctx.record_next_version!(version)` explicitly records the next development version for later callbacks. Earlier snapshots are unchanged. Standard next development iteration preparation records it only after committing and pushing successfully. Custom callbacks must record it themselves after their operations succeed. +`ctx.record_next_version!(version)` saves the next development version for later callbacks, without changing earlier snapshots. The standard workflow records it only after the next-version commit is pushed; custom callbacks must record it themselves after success. -In Actions, environment capture creates a unique private state file in `RUNNER_TEMP` and exports its path as `RELEASE_STATE_FILE`. It contains only `next_version` and an optional [semantic release decision](workflow/semantic_ruby_gem.md#state-and-callbacks) under `analysis`. Arbitrary data and Ruby objects cannot be persisted. Writes are atomic and invalid versions, missing files, corrupt state, and unexpected or missing fields fail rather than being silently reset. Separate captures create separate files, including repeated action invocations in one job. Failure reporting uses one coherent snapshot, warning and omitting unreadable state while preserving the original exception and available execution metadata. +`ctx.analysis` is a frozen decision or `nil`. `ctx.record_analysis!(decision)` saves a validated `SemanticRelease::Decision` once. Standard semantic validation does this; manual workflows leave it unset. Recording `next_version` keeps the analysis. -`ctx.analysis` is an immutable decision snapshot or `nil`. `ctx.record_analysis!(decision)` records a validated `SemanticRelease::Decision` exactly once for later tasks without changing existing snapshots. Standard semantic validation owns this operation; manual workflows leave analysis absent. Recording `next_version` does not replace analysis. +On Actions, capture creates a private state file in `RUNNER_TEMP` and exports its path as `RELEASE_STATE_FILE`. It holds only `next_version` and an optional [semantic release decision](workflow/semantic_ruby_gem.md#state-and-callbacks) under `analysis`. Writes are atomic. Invalid versions, a missing or corrupt file, and unexpected or missing fields raise instead of resetting. Each capture gets its own file, even twice in one job. Failure reporting reads one snapshot; unreadable state is left out with a warning, keeping the original error. -Without a state file, callbacks installed by the same `Tasks` instance share in-memory state within that Ruby process. Separate local processes do not share state automatically. Shell command overrides must preserve `RELEASE_STATE_FILE` and invoke the recording API if they need this propagation. +Without a state file, callbacks of one `Tasks` object share state in memory within one process; separate processes do not. Custom shell commands must keep `RELEASE_STATE_FILE` and call the recording methods to pass values on. ## Failure -`failure.phase` identifies the failed step, while `failure.context.step.id` identifies the currently executing failure callback. `failure.error` retains the captured exception interface. Release data may be absent, but execution metadata remains available after an early failure. Failure callbacks cannot run before Ruby setup completes. - -Captured workflow errors also expose `stage`, `hook`, and `hook_index`, identifying the built-in stage or particular failing hook across processes. These are absent when failure occurred outside an observed lifecycle stage. +`failure.phase` names the failed step; `failure.context.step.id` names the running failure callback. `failure.error` is the captured exception, and its `stage`, `hook`, and `hook_index` name the failing stage or hook across processes, or are `nil` outside a lifecycle stage. Release data may be missing after an early failure, but step details remain. Failure callbacks cannot run before Ruby setup. diff --git a/docs/execution_context/github.md b/docs/execution_context/github.md index fc1c32b..ffe7cee 100644 --- a/docs/execution_context/github.md +++ b/docs/execution_context/github.md @@ -1,14 +1,14 @@ # `RubyGemRelease::ExecutionContext::GitHub` -Extends the provider-neutral [`ExecutionContext`](../execution_context.md) with GitHub Actions step snapshots and run metadata. The [GitHub execution provider](../execution_provider/github.md) constructs this subclass, including for failure callbacks. The inherited release, workflow, and state interface is unchanged. +The `ctx` on GitHub Actions. It adds step results and run details to the base [`ExecutionContext`](../execution_context.md); release, workflow, and state work the same. The [GitHub execution provider](../execution_provider/github.md) creates it, including for failure callbacks. ## Steps -`ctx.step.id` identifies the enclosing Actions step, supplied explicitly through `RELEASE_STEP_ID`. A custom command invoking several Rake tasks retains that enclosing step identity. If the ID is unavailable, the logical task name is used instead. The current step has no final outcome or conclusion while it is executing. +`ctx.step.id` is the running Actions step, from `RELEASE_STEP_ID`, or the task name if unset. Several Rake tasks in one custom command share it. The running step has no outcome yet. -`ctx.steps` is a frozen hash keyed by observed Actions step IDs. GitHub step objects expose `id`, `outcome`, and `conclusion`. Outcome is the original result; conclusion reflects `continue-on-error`. Statuses are `success`, `failure`, `cancelled`, or `skipped`; missing values are `nil`. Missing entries mean unobserved, not skipped. +`ctx.steps` is a frozen hash of steps by ID, each with `id`, `outcome` (the original result), and `conclusion` (after `continue-on-error`). Values are `success`, `failure`, `cancelled`, `skipped`, or `nil`. A missing entry means not seen, not skipped. -Both Actions interfaces supply a snapshot through `RELEASE_STEPS_JSON` before each configurable command. The snapshot is not live history, does not include future results, and may include other visible caller steps. If unavailable, it defaults to an empty hash. Invalid snapshots raise rather than inventing history. Action outputs and credentials are not retained. +Both Actions interfaces pass a snapshot in `RELEASE_STEPS_JSON` before each configurable command. It is not live, has no later results, and may include other caller steps. Without it, `ctx.steps` is empty; invalid JSON raises. Outputs and credentials are not kept. ```ruby tasks.prepare do |ctx| @@ -19,6 +19,4 @@ end ## Run -`ctx.run` exposes frozen copies of selected GitHub environment values: `repository`, `ref`, `sha`, `run_id`, `run_attempt`, `job_id`, `workflow_name`, and `workflow_ref`. Values remain strings; unavailable values are `nil`. `sha` identifies the triggering commit, not necessarily the checkout HEAD after release commits. No tokens or full GitHub event payloads are copied. - -GitHub-specific environment parsing, run fields, and status semantics live in this subclass and its step and run objects, not the shared base. +`ctx.run` has frozen strings, or `nil` when unset, for `repository`, `ref`, `sha`, `run_id`, `run_attempt`, `job_id`, `workflow_name`, and `workflow_ref`. `sha` is the triggering commit, not necessarily `HEAD` after release commits. Tokens and event payloads are never copied. diff --git a/docs/execution_provider.md b/docs/execution_provider.md index df3cc1a..953ee7b 100644 --- a/docs/execution_provider.md +++ b/docs/execution_provider.md @@ -1,21 +1,27 @@ # `RubyGemRelease::ExecutionProvider` -Separates execution-platform services from release operations. Pass `provider:` to [`Workflow::RubyGem`](workflow/ruby_gem.md), [`Tasks.install`](tasks.md), or [`Workflow::Environment`](workflow/environment.md). The configured workflow exposes its provider through `ctx.workflow.provider`. Execution providers, registry destinations, and hosted-release implementations are independent choices. +Connects release tasks to the platform they run on: inputs, exports to later steps, callback contexts, and identity tokens. Pass `provider:` to [`Workflow::RubyGem`](workflow/ruby_gem.md), [`Tasks.install`](tasks.md), or [`Workflow::Environment`](workflow/environment.md); callbacks read it as `ctx.workflow.provider`. Providers, registry destinations, and hosted releases are independent choices. -`ExecutionProvider.current` selects [`ExecutionProvider::GitHub`](execution_provider/github.md) when `GITHUB_ACTIONS=true`; otherwise it selects the base. Explicit injection overrides detection. No GitLab implementation or pipeline is provided. +`ExecutionProvider.current` returns [`ExecutionProvider::GitHub`](execution_provider/github.md) when `GITHUB_ACTIONS=true`, and the base otherwise. An explicit provider wins. No GitLab provider is included. ## Base Behavior -The base reads release inputs through `fetch(name, *defaults)` from its `environment:` argument, defaulting to `ENV`. `ref` reads a full Git ref from `SOURCE_REF`, and `directory` reads optional `RELEASE_DATA_DIR`. Git identity defaults to `ruby-gem-release` and `ruby-gem-release@localhost`, with `GIT_USER_NAME` and `GIT_USER_EMAIL` overrides. +The base reads from its `environment:` argument, default `ENV`: -`export(values)` validates names and single-line string values before updating the current environment. An external execution provider must implement its own transport for subsequent steps. Separate processes must share the exported release values and artifact directory. - -`context(**attributes)` creates an immutable provider-neutral execution context; `step_id(task)` uses the logical Rake task ID, and `failed_steps` returns no external history. A provider with execution metadata overrides these methods rather than putting platform I/O in the context. +- `fetch(name, *defaults)` reads a value. +- `ref` reads a full Git ref from `SOURCE_REF`. +- `directory` reads an optional `RELEASE_DATA_DIR`. +- Git identity defaults to `ruby-gem-release` and `ruby-gem-release@localhost`, overridden by `GIT_USER_NAME` and `GIT_USER_EMAIL`. +- `export(values)` checks names and single-line string values, then updates the current environment only. +- `context(**attributes)` creates a frozen base context, `step_id(task)` returns the task name, and `failed_steps` returns `[]`. +- `oidc_token(audience:)` raises `NotImplementedError`, and `mask(value)` does nothing. ## Provider Contract -Provider subclasses supply their current ref, temporary directory, environment transport, context construction, step identity, and observed failed step IDs. Environment exports must remain readable through `fetch` in the current process as well as being available to subsequent steps. The pipeline owns setup, concurrency, release authorization, conditional step execution, summaries, and recovery-artifact uploading. +A subclass supplies its ref, temporary directory, export transport, context, step IDs, and failed step IDs. Exported values must be readable through `fetch` in the current process and reach later steps; separate processes must share them and the artifact directory. Put platform I/O in the provider, not the context. + +Implement `oidc_token(audience:)` to get an identity token and `mask(value)` to hide a secret in logs. The RubyGems exchange uses them, so it needs no platform code. Custom registries can keep using preconfigured credentials. -`oidc_token(audience:)` acquires an identity token for the requested audience and raises `NotImplementedError` in the base. `mask(value)` registers a secret with the execution platform; the base logs nothing. The RubyGems exchange uses these operations without implementing platform-specific token acquisition or logging commands. Custom registries may continue using preconfigured credentials. +The pipeline still owns setup, concurrency, release approval, conditional steps, summaries, and recovery-artifact uploads. -Switching execution providers does not change hosting automatically. Supply the desired `hosting:` object or `hosting: nil` separately; the standard workflow still defaults to GitHub Releases. +Changing the provider does not change hosting. Pass `hosting:` or `hosting: nil` yourself; the standard workflow defaults to GitHub Releases. diff --git a/docs/execution_provider/github.md b/docs/execution_provider/github.md index 7cb9f9a..0378bbe 100644 --- a/docs/execution_provider/github.md +++ b/docs/execution_provider/github.md @@ -1,11 +1,11 @@ # `RubyGemRelease::ExecutionProvider::GitHub` -Implements [`ExecutionProvider`](../execution_provider.md) for GitHub Actions. It reads `GITHUB_REF` and `RUNNER_TEMP`, retains the GitHub bot identity defaults, and supplies [`ExecutionContext::GitHub`](../execution_context/github.md) snapshots and original failed-step outcomes. +The [`ExecutionProvider`](../execution_provider.md) for GitHub Actions. It reads `GITHUB_REF` and `RUNNER_TEMP`, defaults the Git identity to the GitHub bot, and creates [`ExecutionContext::GitHub`](../execution_context/github.md) contexts with step results and failed-step outcomes. -Environment exports append to `GITHUB_ENV` and update the current process environment. Names and values are validated before writing files. Capture exports the runner directory as the provider-neutral `RELEASE_DATA_DIR` used by Git and package operations. +`export(values)` validates names and values, appends them to `GITHUB_ENV` for later steps, and sets them in the current process. Capture exports the runner directory as `RELEASE_DATA_DIR` for Git and package operations. -`oidc_token(audience:)` requests an identity token through the public Actions OIDC endpoint, replacing any previous audience without discarding other query parameters. It requires HTTPS, bounds request timeouts, disables retries, and rejects malformed responses without including their bodies in errors. The caller must grant `id-token: write`. +`oidc_token(audience:)` requests an OpenID Connect identity token from the Actions token endpoint, replacing any audience in the URL but keeping other parameters. It requires HTTPS, bounds timeouts, does not retry, and raises on malformed responses without including the body. The workflow must grant `id-token: write`. -`mask(value)` emits the Actions secret-masking command with escaped control characters. [`Workflow::RubyGemsCredentials`](../workflow/ruby_gems_credentials.md) requests the `rubygems.org` audience and performs the separate registry exchange, optionally bound to an owner for first publication. +`mask(value)` hides a secret in Actions logs, escaping control characters. [`Workflow::RubyGemsCredentials`](../workflow/ruby_gems_credentials.md) uses both to get a `rubygems.org` token and exchange it for credentials, optionally bound to an owner for a first release. -The reusable workflow and composite action remain Actions-specific orchestration. This adapter does not replace checkout, Ruby setup, environment protection, concurrency, summaries, or artifact-upload steps. +The reusable workflow and composite action still handle checkout, Ruby setup, environment protection, concurrency, summaries, and artifact uploads. diff --git a/docs/hosting/github_release.md b/docs/hosting/github_release.md index 1efe7cb..7c7a8d6 100644 --- a/docs/hosting/github_release.md +++ b/docs/hosting/github_release.md @@ -1,6 +1,6 @@ # `RubyGemRelease::Hosting::GitHubRelease` -Creates a GitHub Release using the installed `gh` command after the gem is published and its commit and tag are pushed. +Creates a GitHub Release with the `gh` command, after the gem is published and the commit and tag are pushed. ```ruby require 'ruby-gem-release/hosting/github_release' @@ -11,30 +11,30 @@ github.publish!(release, package: package) ## Repository -The optional `repository:` argument identifies the target as `'OWNER/REPO'`. It defaults to `GITHUB_REPOSITORY`; outside Actions, `gh` infers the repository from the checkout. +`repository:` is the target as `'OWNER/REPO'`. It defaults to `GITHUB_REPOSITORY`; outside Actions, `gh` uses the current checkout. ## Publish -Pass `latest: true` or `latest: false` to the constructor to set the latest-release policy during creation and metadata updates. Existing releases are compared with GitHub's latest release before changing that status. The default `nil` retains GitHub's automatic selection and does not change matching existing releases. Use `latest: false` for maintenance branches to avoid temporarily promoting an older release. +`latest:` sets whether the release is marked latest when created or updated: `true`, `false`, or `nil` (default) to let GitHub decide and leave existing releases alone. Use `latest: false` on maintenance branches so an older release is never promoted, even briefly. Existing releases are compared with GitHub's current latest first. -`publish!(release, package: nil, artifacts: [])` creates a release with tag and title `vVERSION`, using the numeric version from the [Release](../release.md) context. It verifies that the tag exists remotely and never creates a tag automatically. With `release.notes`, it supplies that nonempty body through a private temporary `--notes-file` and removes the file afterward; otherwise it retains GitHub's `--generate-notes`. The standard workflow supplies the released changelog section when the changelog can read it. It returns the release URL printed by `gh`. +`publish!(release, package: nil, artifacts: [])` creates a release with tag and title `vVERSION` from the [Release](../release.md) version. The tag must already exist on GitHub; it is never created here. With `release.notes`, the nonempty notes are passed in a private temporary `--notes-file` that is then deleted; otherwise GitHub generates notes. The standard workflow passes the released changelog section when it can read it. It returns the release URL printed by `gh`. ## Package -`publish!` verifies existing metadata and every expected asset, updates differing titles, release status, and explicit notes, and uploads missing or changed assets with `--clobber`; matching outputs are no-ops. Unspecified platform-generated notes are retained. Assets without a server digest are downloaded and hashed. Invalid responses and duplicate asset names fail rather than being guessed. +Reruns are safe. For an existing release, `publish!` checks metadata and assets, updates a differing title, latest status, or explicit notes, and uploads missing or changed assets with `--clobber`. Matching output is left alone, and generated notes are kept when none were passed. Assets without a server digest are downloaded and hashed. Invalid responses and duplicate asset names raise. -`package:` attaches the exact archive returned by [`Package::RubyGem#artifact`](../package/ruby_gem.md#artifact), with its package filename and verified digest, without rebuilding or manual copying. +`package:` attaches the exact archives from [`Package::RubyGem#artifact`](../package/ruby_gem.md#artifact), with their filenames and checked digests, without rebuilding. ## Artifacts -Without `package:`, `artifacts:` accepts existing file paths, defaulting to no attachments. Paths containing spaces are supported; line breaks and `#` are rejected because `gh` interprets `#` as an asset label. +Without `package:`, `artifacts:` takes existing file paths and defaults to none. Spaces are fine; line breaks and `#` raise, because `gh` reads `#` as an asset label. ## Authentication and Errors -Install `gh` and authenticate using `GH_TOKEN` or its existing credentials. The workflow supplies the GitHub Actions token and requires the caller's `contents: write` permission. +Install `gh` and log in with `GH_TOKEN` or existing credentials. The workflow passes the Actions token, which needs `contents: write`. -Failed commands raise without automatic retries. Reruns verify existing outputs and reconcile missing or changed hosted metadata and assets; see [Verify and Recover](../../RELEASING.md#verify-and-recover). +Failed commands raise without retries. A rerun checks what exists and fixes missing or changed details and assets; see [Verify and Recover](../../RELEASING.md#verify-and-recover). ## Workflow Command -The `publish` workflow input defaults to `bundle exec rake release:publish`. Configure that callback to invoke this class after `git.push!`. Set `hosting: nil` in [`Workflow::RubyGem`](../workflow/ruby_gem.md) or omit only `github.publish!` from manual callbacks to disable GitHub Release creation; omitting the whole callback disables package publication too. +The `publish` workflow input defaults to `bundle exec rake release:publish`; call this class from it after `git.push!`. To skip GitHub Releases, set `hosting: nil` in [`Workflow::RubyGem`](../workflow/ruby_gem.md) or remove only `github.publish!` from manual callbacks. Removing the whole callback also stops gem publishing. diff --git a/docs/markdown.md b/docs/markdown.md index f7dd4b7..84ec952 100644 --- a/docs/markdown.md +++ b/docs/markdown.md @@ -1,6 +1,6 @@ # Updating Markdown Sections -Use `RubyGemRelease::Markdown::Section` to replace a section's body while keeping project-specific wording and version links in your hooks: +`RubyGemRelease::Markdown::Section` edits the body of one Markdown section, so hooks can keep your own wording and version links current: ```ruby require 'ruby-gem-release/markdown/section' @@ -15,16 +15,16 @@ workflow.after(:prepare_release) do |ctx| end ``` -`heading:` is the complete, exact heading line, with one to six leading `#` characters. There must be exactly one matching top-level Markdown heading; headings inside code, quotes, and HTML examples do not count. Missing or duplicate headings raise before writing. +`heading:` is the exact, full heading line, with one to six `#`. Exactly one top-level heading must match; headings in code, quotes, and HTML do not count. Missing or duplicate headings raise before writing; `validate!` checks only. -`replace!` replaces everything after that heading through the next equal-or-shallower heading, including nested subsections. It preserves surrounding source, normalizes the replacement's line endings to the file, and accepts repeated replacement. Mixed or unsupported line endings are rejected. +`replace!(body)` replaces everything after the heading up to the next heading of the same or higher level, including subsections. The rest of the file is kept, `body` line endings are converted to the file's, and repeating it is safe. Mixed or unsupported line endings raise. -Use `gsub!(pattern, replacement)` to replace matching text without replacing the whole body: +`gsub!(pattern, replacement)` replaces matching text in the body only: ```ruby stable.gsub!(/version \d+\.\d+\.\d+/, 'version 0.2.0') ``` -Like `String#gsub!`, the pattern can be a string or regular expression, and replacement strings support capture references. All matches within the body are replaced, including matches in nested subsections and code examples; the heading and surrounding sections remain unchanged. Existing formatting and the final newline are preserved, and inserted line endings follow the file's style. With no matches, it returns `nil` without writing. Missing or duplicate section headings still raise. +It works like `String#gsub!`: a string or regular expression, with capture references in the replacement. All matches in the body are replaced, including subsections and code; the heading and other sections are unchanged. Formatting and the final newline are kept. With no match it returns `nil` and writes nothing. -The [lifecycle-hooks example](../examples/lifecycle_hooks/release_notes.rb) uses this helper for its stable and development README text. Keep assertions about that wording and the project's release behavior in the project's [custom workflow specs](testing.md). +The [lifecycle hooks example](../examples/lifecycle_hooks/release_notes.rb) uses this for its stable and development README text. Test that wording and your release behavior in your own [custom workflow specs](testing.md). diff --git a/docs/package/collection.md b/docs/package/collection.md index 84bd911..18fa55b 100644 --- a/docs/package/collection.md +++ b/docs/package/collection.md @@ -1,6 +1,6 @@ # Package Collections and Prebuilt Archives -`Package::Collection` implements the normal build, version, and verification interface for an explicit, nonempty array of packages. All packages must have the same release version, with unique gem identities and attachment filenames. Give each built package its own artifact directory. +`Package::Collection` releases several gems together, such as ruby and Java builds of one version. It has the usual package methods, so use it anywhere a package goes. `Package::Prebuilt` wraps an archive that was already built. ```ruby require 'ruby-gem-release/package/collection' @@ -16,11 +16,13 @@ packages = RubyGemRelease::Package::Collection.new( ) ``` -Prebuilt packages verify the supplied checksum, expected name/version/platform, filename, and optional `audit:` every time. `build!` verifies rather than rebuilding or replacing them. Supply the reviewed digest explicitly from the original build; the API does not discover artifacts, restore state, or trust a digest calculated from an unknown input during publication. +`packages:` must be a nonempty array. Members must share one version and have unique gem identities and filenames. Give each built package its own directory. + +A prebuilt package checks its SHA256, name, version, platform, filename, and optional `audit:` every time it is used. `build!` only checks; it never rebuilds. Pass the reviewed digest from the original build. The library never searches for archives, restores state, or trusts a digest computed from an unknown file. ## Build Manifests -Load an original `Package::RubyGem` manifest with an explicit expected identity: +Load a manifest (`release.json`) from an original `Package::RubyGem` build, stating the expected identity: ```ruby package = RubyGemRelease::Package::Prebuilt.from_manifest( @@ -32,10 +34,10 @@ package = RubyGemRelease::Package::Prebuilt.from_manifest( ) ``` -The loader requires matching manifest metadata, reads its original SHA256, and resolves the canonical archive filename beside the manifest. `platform:` defaults to `ruby`; `audit:` is optional. Missing archives fail without discovery or rebuilding. Subsequent verification uses the captured digest, not later manifest edits. Use only a trusted original manifest; never regenerate expected digests from downloaded archives. +The manifest must match the given identity. The digest comes from the manifest, read once, and the archive must sit beside it under its standard filename; a missing archive raises. `platform:` defaults to `ruby`; `audit:` is optional. Use only a trusted original manifest, never digests from downloaded archives. ## Publication -Use the collection as the standard workflow's `package:`, or pass it to `Destination::RubyGems#publish!` and `Hosting::GitHubRelease#publish!`. Hosting attaches all verified archives. RubyGems verifies every local artifact and checks every registry identity before the first upload, rejecting conflicting published bytes even for later members. Uploads remain sequential and cannot be atomic; on repetition, exact existing publications are accepted and only missing members are uploaded. +Use the collection as the workflow's `package:`, or pass it to `Destination::RubyGems#publish!` and `Hosting::GitHubRelease#publish!`. Hosting attaches every archive. RubyGems checks every local archive and registry entry before the first upload, and raises if any published gem has different bytes. Uploads are sequential, not atomic; a retry accepts exact existing gems and uploads only missing ones. -Custom destinations receiving a collection must implement equivalent all-member verification and publication. `artifacts(release)` exposes the verified paths; `packages` exposes the frozen member list. A collection deliberately has no singular `artifact` or `gemspec`. +A custom destination must check and publish every member the same way. `artifacts(release)` returns the checked paths; `packages` returns the frozen member list. A collection has no single `artifact` or `gemspec`. diff --git a/docs/package/ruby_gem.md b/docs/package/ruby_gem.md index 42cf2be..a1d2e58 100644 --- a/docs/package/ruby_gem.md +++ b/docs/package/ruby_gem.md @@ -1,38 +1,34 @@ # `RubyGemRelease::Package::RubyGem` -Owns gem metadata, building, and artifact verification independently of the publication destination. Commands use argument arrays rather than shell interpolation. Registry operations belong to [`Destination`](../destination.md). +Builds and checks a `.gem` archive from your gemspec. Publishing is done by a [`Destination`](../destination.md). Commands use argument arrays, not a shell. ## Gemspec -`RubyGem.new(gemspec: 'example.gemspec')` selects an explicit specification; otherwise it uses `GEMSPEC_PATH` or the only root gemspec. Missing or ambiguous selections fail. The standard workflow uses this package during capture and resolution, exporting its absolute `gemspec` path. +`RubyGem.new(gemspec: 'example.gemspec')` uses that gemspec. Otherwise it uses `GEMSPEC_PATH` or the only gemspec in the root; none or several raise. `gemspec` returns the absolute path, which the standard workflow exports. ## Directory -The optional `directory:` defaults to a nonempty `RELEASE_DATA_DIR` or a new temporary directory, created when first used. The standard workflow supplies the execution provider's directory explicitly; Actions capture also exports it for manual callbacks and subsequent processes. `directory` returns this location. Keep it outside the working tree so build artifacts do not enter release commits. +`directory:` is where build output goes. It defaults to a nonempty `RELEASE_DATA_DIR` or a new temporary directory, created on first use, and `directory` returns it. The standard workflow passes the execution provider's directory, which Actions also exports for later steps. Keep it outside the working tree so build output stays out of release commits. ## Version -`version` reads the gemspec version in a fresh Ruby process so callback edits are visible even if the specification was previously loaded. +`version` reads the gemspec version in a new Ruby process, so it sees callback edits. ## Build -`build!(release)` overwrites `release.gem`, checks its version, and records its name, version, and checksum in `release.json`. It returns the package filename. Call it after the release commit and before tagging; `Git#tag!` rejects build mutations in the checkout. +`build!(release)` overwrites `release.gem`, checks its version, writes its name, version, platform, and checksum to `release.json`, and returns the [artifact](#artifact) path. Call it after the release commit and before tagging; `Git#tag!` raises if the build changed the checkout. `built?(release)` checks existing output without building. -Builds use `SOURCE_DATE_EPOCH` for the gemspec date and archive timestamps. Workflow capture supplies the committer timestamp of the original source commit, not the generated release commit; an explicit value takes precedence. Direct builds without capture or an override retain RubyGems' fixed default `1980-01-02T00:00:00Z`. +Builds are reproducible. `SOURCE_DATE_EPOCH` sets the gemspec date and archive timestamps. Workflow capture sets it to the committer time of the original source commit, not the release commit; an explicit value wins. Without either, RubyGems uses `1980-01-02T00:00:00Z`. -Reproduce a release from the same source commit: equivalent files in another commit can have a different timestamp. Toolchains, generated files, gemspecs, and signing inputs must also remain stable. No previous archive is needed; partial output is overwritten. `built?(release)` verifies an existing archive and manifest without building. - -The standard Actions workflow builds at checkpoint and again during publication. Each build writes the same reproducible archive and digest manifest; direct builds overwrite prior output. +To rebuild a release, use the same source commit (the same files in another commit get another timestamp) and keep toolchains, generated files, gemspecs, and signing inputs the same. The old archive is not needed. The Actions workflow builds at the checkpoint and again at publication, producing the same archive both times. ## Artifact -`artifact(release)` verifies the built name, version, platform, and digest and returns a copy named `NAME-VERSION.gem` for the ruby platform or `NAME-VERSION-PLATFORM.gem` otherwise. Registry destinations and hosted releases use those exact bytes. Digest manifests record the platform; older manifests without one are accepted only for ruby-platform archives. - -Verification checks the retained archive against the manifest and validates its gem metadata before publication. `artifact(release)` copies the verified canonical archive to its name-and-version path. +`artifact(release)` checks the archive against the manifest (name, version, platform, digest, and gem metadata), copies it to `NAME-VERSION.gem` (or `NAME-VERSION-PLATFORM.gem` for non-ruby platforms), and returns that path. Registries and hosted releases publish these exact bytes. Older manifests without a platform work only for ruby-platform gems. ## Content Audit -An optional `audit:` verifies archive contents during every build and artifact read, including reopened archives. Use project-owned expectations independent of file selection in the gemspec: +`audit:` checks the files in the archive on every build and artifact read, including reopened archives. List expected files yourself, not from the gemspec: ```ruby require 'ruby-gem-release/package/content_audit' @@ -46,10 +42,13 @@ audit = RubyGemRelease::Package::ContentAudit.new( package = RubyGemRelease::Package::RubyGem.new(audit: audit) ``` -The expected list must exactly match the archive: both omitted runtime files and accidentally included developer files fail. Relative paths must be safe and unique; archive entries must be regular files. Each file not listed as generated must match its Git blob byte for byte. `source:` resolves to a commit on each verification; supply an explicit commit hash when auditing retained artifacts from an earlier checkout. `root:` selects the Git checkout and defaults to the current directory. +- `expected_files:` must match the archive exactly, so missing runtime files and stray developer files both raise. Paths must be safe and unique, and entries must be regular files. +- Every file not in `generated:` must match its Git version byte for byte. +- `source:` (default `'HEAD'`) resolves to a commit on each check; pass a commit SHA to audit a kept archive from an earlier checkout. +- `root:` is the Git checkout and defaults to the current directory. -Generated files must appear in both `expected_files:` and `generated:`; only their source-byte comparison is waived. They remain subject to package checksums and exact file-list validation. Generated bytes require project-specific compilation and consumer checks. Never derive expectations from the archive itself or reuse an unchecked gemspec file list. +Generated files must be in both `expected_files:` and `generated:`. Only the Git comparison is skipped; checksums and the file list still apply. Test generated bytes with your own build and consumer checks. Never derive expectations from the archive or an unchecked gemspec file list. ## Errors -Build failures, version mismatches, and changed artifacts raise. The package does not contact a registry or upload files; see [`Destination::RubyGems`](../destination/ruby_gems.md) for publication and duplicate-version safeguards. +Build failures, version mismatches, and changed archives raise. The package never contacts a registry; see [`Destination::RubyGems`](../destination/ruby_gems.md) for publishing and duplicate-version checks. diff --git a/docs/release.md b/docs/release.md index a0734f5..7d4004e 100644 --- a/docs/release.md +++ b/docs/release.md @@ -1,33 +1,33 @@ # `RubyGemRelease::Release` -An immutable version and date value available through [callback execution contexts](execution_context.md) as `ctx.release` and passed directly to release operations. Strings and the date are copied and frozen along with the object. +A frozen value holding the version, date, and notes of the release in progress. Callbacks read it as `ctx.release` from their [execution context](execution_context.md), and release operations take it as an argument. Strings and the date are copied and frozen; the `with_*` methods return copies. ## Version -`release.version` is the selected version before preparation, or the initial gemspec version when no version is selected. Later phases use the prepared gemspec version. `release.gemspec_version` retains the initial version independently. The required constructor argument `version:` is a string. +`release.version` is the version being released: before preparation, the selected version or else the initial gemspec version; later, the prepared gemspec version. The constructor requires `version:` as a string. ## Gemspec Version -`release.gemspec_version` retains the gemspec version captured at workflow start, before any version override or preparation. It can equal `release.version`; it does not identify the last published release. The required constructor argument `gemspec_version:` is a string. +`release.gemspec_version` is the gemspec version when the workflow started, before any selected version or preparation. It can equal `release.version`, and it is not the last published version. The constructor requires `gemspec_version:` as a string. ## Next Development Iteration -`release.next_version` holds the version for the next development iteration and starts as `nil`. The optional constructor argument `next_version:` accepts a string. +`release.next_version` is the version for development after the release. It starts as `nil`; the optional `next_version:` takes a string. -The standard workflow records it after the next development iteration is committed and pushed, making it available to the success callback. Custom callbacks must call `ctx.record_next_version!(version)` explicitly; creating a release copy alone does not persist data across tasks. +The standard workflow sets it after the next-version commit is pushed, so the success callback can read it. Custom callbacks must call `ctx.record_next_version!(version)`; a new release copy alone does not reach later tasks. ## Date -`release.date` is a Ruby `Date`. The workflow captures it once in the configured `timezone` and retains it across both phases. UTC is the default; `America/New_York` uses Eastern Time with daylight saving changes. The constructor requires `date:` and does not perform timezone conversion. +`release.date` is a Ruby `Date`, required as `date:`. The workflow captures it once in the configured `timezone` (default UTC; `America/New_York` follows Eastern daylight saving time) and uses it in every phase. The constructor does no time zone conversion. ## Notes -`release.notes` is an optional copied, frozen Markdown string supplied through `notes:`. [Semantic workflows](workflow/semantic_ruby_gem.md) persist generated notes and pass the same body to changelog and hosting operations. Manual workflows leave it `nil`, retaining platform-generated hosted-release notes. Version copies preserve it. +`release.notes` is optional Markdown passed as `notes:`. [Semantic workflows](workflow/semantic_ruby_gem.md) save generated notes and pass them to the changelog and hosting. Manual workflows leave it `nil`, so GitHub generates hosted notes. Copies keep it; `release.with_notes(notes)` replaces it. ## With Version -`release.with_version(version.read)` returns a new context containing the supplied version string, preserving every other field and leaving the original unchanged. +`release.with_version(version.read)` returns a copy with the given version, leaving the original unchanged. ## With Next Development Iteration -`release.with_next_version(version.increment!(from: release.version))` returns a new context containing the next development version, preserving every other field and leaving the original unchanged. +`release.with_next_version(version.increment!(from: release.version))` returns a copy with the given next development version, leaving the original unchanged. diff --git a/docs/source_control/git.md b/docs/source_control/git.md index d3c5492..fe13a06 100644 --- a/docs/source_control/git.md +++ b/docs/source_control/git.md @@ -1,47 +1,47 @@ # `RubyGemRelease::SourceControl::Git` -Owns local release commits and tags, branch checks, Git bundles, and remote pushes. +Handles the Git side of a release: clean and current checks, staging, the release commit and tag, a Git bundle (a one-file copy of the release for inspection), and pushes. ## Branch and Remote -`Git.new(branch: nil, remote: 'origin', directory: nil)` uses `DEFAULT_BRANCH` or the remote's default-branch reference. The optional directory selects the Git bundle and preparation index snapshot location; it defaults to a nonempty `RELEASE_DATA_DIR` or a new temporary directory, created when first used. Separate Ruby processes must share this directory, as both Actions interfaces do through their execution provider. +`Git.new(branch: nil, remote: 'origin', directory: nil)` uses `DEFAULT_BRANCH` or the remote's default branch. `directory:` holds the bundle and the staged-tree snapshot; it defaults to a nonempty `RELEASE_DATA_DIR` or a new temporary directory, created on first use. Separate Ruby processes must share it, as both Actions interfaces do through their execution provider. ## Configure -`configure!(name:, email:)` sets checkout-local identity. Direct-call defaults are `ruby-gem-release` and `ruby-gem-release@localhost`; blank values or line breaks fail. Context capture supplies the execution provider's identity, retaining the existing GitHub bot defaults on Actions. +`configure!(name:, email:)` sets the commit identity for this checkout only. Direct calls default to `ruby-gem-release` and `ruby-gem-release@localhost`; blank values or line breaks raise. The workflow passes the execution provider's identity, the GitHub bot on Actions. ## Head -`head` returns the current commit. `timestamp(commit)` reads the committer timestamp of a selected commit as Unix seconds; capture uses it for reproducible package timestamps. +`head` returns the current commit. `timestamp(commit)` returns its committer time in Unix seconds, used for reproducible package timestamps. ## Check Current -`check_current!(expected: head, allow_ancestor: false)` fetches the remote branch and tags and rejects an advanced branch before new publication or pushing. Capture permits an ancestor checkout so reruns can use the original source commit after its release has advanced the branch. +`check_current!(expected: head, allow_ancestor: false)` fetches the remote branch and tags and raises if the branch moved. Capture allows an ancestor, so a rerun can use the original source commit after its release advanced the branch. ## Commit -`commit!(release)` commits previously staged preparation changes if needed; it never stages files. It rejects unexpected unstaged, untracked non-ignored, or index changes by comparing the index with the saved preparation tree. It retains the source checkout commit for subsequent concurrency checks; the workflow supplies `SOURCE_COMMIT`. +`commit!(release)` commits staged preparation changes, if any; it never stages. Unstaged changes, untracked files that are not ignored, or an index that differs from the saved preparation raise. It keeps the source commit (`SOURCE_COMMIT` in the workflow) for later checks. An existing release tag is reused only when its whole tree matches. ## Clean Checkout and Preparation -`check_clean!` rejects any tracked changes, including staged changes, and any untracked non-ignored files. Diagnostics list escaped status paths, limit large listings, and suggest removing generated files, restoring unexpected changes, or intentionally ignoring dependency artifacts. Both Actions interfaces call it after dependency installation and before loading the gemspec or preparing release files. Existing ignore rules are honored, but tracked artifacts are never exempt. +`check_clean!` raises on any tracked change, staged or not, and any untracked file that is not ignored. Ignore rules apply, but tracked files are never exempt. The error lists the paths and suggests deleting generated files, restoring changes, or ignoring dependency output. Both Actions interfaces call it after installing dependencies and before loading the gemspec or editing files. -`stage_changes! { ... }` requires a clean checkout, runs trusted preparation code, and stages the resulting paths with literal, argument-based Git invocation. This supports custom version, changelog, README, added, renamed, and deleted files without guessing conventions. Without a block, it stages current preparation outputs; the workflow uses this at the end of the configurable `prepare` command, before testing. It saves the exact index tree in `prepared-tree`, so even unrelated files staged later cannot silently enter publication. A failing block does not stage or commit its edits. Do not call this method from publication to accept unexpected test output. +`stage_changes! { ... }` requires a clean checkout, runs your trusted preparation block, and stages every changed path, including added, renamed, and deleted files, with literal Git arguments. Without a block, it stages current changes; the workflow does this after the `prepare` command, before tests. It saves the staged tree as `prepared-tree`, so files staged later cannot slip into the release. If the block raises, nothing is staged. Do not call it during publication to accept unexpected test output. ## Tag -`tag!(release)` rejects build mutations and concurrent advancement, reuses only a tag pointing at the exact release commit, and writes `release.bundle`. Conflicting tags fail. +`tag!(release)` raises if the build changed the checkout or the branch moved, reuses a tag only when it points at the release commit, and writes `release.bundle`. A tag on another commit raises. ## Commit Next -`commit_next!(release)` commits staged edits with a nonempty `next_version`; for `0.5.1`, the message is `Prepare next development iteration, 0.5.1`. Repetition reuses an existing direct child of the release only when its version and full prepared tree match. Otherwise, missing changes or conflicting state fail. +`commit_next!(release)` commits staged edits for a nonempty `next_version`, as `Prepare next development iteration, 0.5.1` for `0.5.1`. There must be changes. A rerun reuses a commit right after the release only when its version and full tree match; anything else raises. ## Push -`push!(release)` checks the remote branch again, then atomically pushes the release commit and tag. After `commit_next!`, `push!` uses the retained release context and pushes only the next development iteration commit. Pushes never force or move existing tags. +`push!(release)` rechecks the remote branch, then pushes the release commit and tag in one atomic push. After `commit_next!`, it pushes only the next-version commit. It never force-pushes or moves tags. -Matching remote refs are no-ops; a remote branch already containing the release is never rewound. `commit!` can reuse an existing release tag only when its entire tree matches the intended preparation. `commit_next!` likewise compares the full development tree. Readback uses `tag_commit(version)` and `next_iteration(release)`; no workflow state or artifact is restored. Unrelated advancement still fails before publication. +Reruns are safe: matching remote refs are skipped and a branch that already contains the release is never rewound. `tag_commit(version)` and `next_iteration(release)` read back existing commits; no state or artifact is restored. Unrelated new commits still raise before publication. ## Errors -Failed commands raise without retries. Publish the gem before the atomic push, as in [Usage](../../README.md#usage); this preserves the package-before-tag ordering but leaves a recovery window if pushing fails. +Failed commands raise without retries. Publish the gem before the atomic push, as in [Usage](../../README.md#usage): the gem then always exists before its tag, but a failed push needs recovery. diff --git a/docs/tasks.md b/docs/tasks.md index cb5ddcc..11662f8 100644 --- a/docs/tasks.md +++ b/docs/tasks.md @@ -1,24 +1,33 @@ # `RubyGemRelease::Tasks` -Registers optional validation, preparation, publication, next development iteration, success, and failure callbacks in the Rakefile. `Tasks.install` accepts optional `workflow:`, `package:`, `destination:`, and `provider:` objects and yields the configuration object; it registers no version tasks and requires no version strategy. The package is resolved lazily when omitted, the destination defaults to RubyGems, and the [execution provider](execution_provider.md) is selected automatically. Pass the same package and destination used by manual publication callbacks so prepared-version checks and authentication agree. See [Detailed Usage](usage.md#custom-callbacks) for manual configuration or [the standard workflow](workflow/ruby_gem.md) to install the usual sequence. +`Tasks` registers release callbacks as Rake tasks: validation, preparation, publication, next development version, success, and failure. [The standard workflow](workflow/ruby_gem.md) sets these up for you; use `Tasks` directly only to write your own callbacks, as in [Detailed Usage](usage.md#custom-callbacks). + +`Tasks.install` yields a configuration object and takes these optional arguments: + +- `workflow:`: the configured workflow. Required for Actions; see [Install](#install). +- `package:`: found automatically when omitted. +- `destination:`: RubyGems by default. +- `provider:`: the [execution provider](execution_provider.md), detected automatically. + +It needs no version strategy. Pass the same package and destination your publication callbacks use, so version checks and authentication agree. ## Install -Call `RubyGemRelease::Tasks.install` with a block to register callbacks. Without a block, validation proceeds and the other five callback tasks do nothing. Workflow tasks include `capture`, `resolve`, `checkpoint`, and `failure_phase`. Actions configurations must pass a configured `workflow:`: its checkpoint creates the archive, digest manifest, commit, and tag before artifact preservation and publication. +Register callbacks in the `RubyGemRelease::Tasks.install` block. Without a block, validation passes and the other five callback tasks do nothing. Workflow tasks include `capture`, `resolve`, `checkpoint`, and `failure_phase`. Actions setups must pass a configured `workflow:`, whose checkpoint creates the archive, digest manifest, commit, and tag before artifacts are saved and published. -The composite action first invokes `release:workflow:configure` to validate and export its input environment for later steps. The reusable workflow supplies the same values through its job environment. +The composite action first runs `release:workflow:configure` to check its inputs and export them for later steps. The reusable workflow sets the same values in its job environment. -The provider constructs callback contexts: by default, the provider-neutral `ExecutionContext` locally or its [`GitHub`](execution_context/github.md) subclass on Actions. Explicit `provider:` injection overrides automatic detection. GitHub-specific step statuses and run fields are not part of the local context. +The provider builds callback contexts: an `ExecutionContext` locally, or its [`GitHub`](execution_context/github.md) subclass on Actions. Passing `provider:` overrides detection. Step statuses and run details exist only on Actions. -Standard workflows provide additive [lifecycle hooks](workflow/hooks.md) for checks and project edits. Manual callbacks replace task behavior and do not automatically get the standard workflow's inner hooks. +Standard workflows also support [lifecycle hooks](workflow/hooks.md) for checks and file edits. Manual callbacks replace task behavior and do not get those hooks. ## Validate -`tasks.validate` checks release preconditions after context capture and before preparation edits. It receives an [ExecutionContext](execution_context.md) containing the same initial or explicitly selected release value as `prepare`. Raise on invalid state; normal completion, including `nil`, succeeds. Returning `false` also fails rather than skipping. Without a callback, validation passes. +`tasks.validate` checks release preconditions after capture and before any files are edited. It receives an [ExecutionContext](execution_context.md) with the same release version that `prepare` will get. Raise to fail. Returning normally, even `nil`, passes, but returning `false` fails. Without a callback, validation passes. -Validation errors reach the failure callback with phase `validate_release`. Both Actions interfaces stop downstream release operations through normal failure handling; there is no decision output or successful skip. Separately invoked Rake tasks remain independent. +A validation error reaches the failure callback with phase `validate_release` and stops the release in both Actions interfaces. There is no "skip" result. Each Rake task you run by hand is independent. -Every invocation runs the configured callbacks; there are no recovery flags or restored context. Default validation accepts the selected version's existing changelog section or pending notes; custom commands must provide equivalent idempotence: +Every run calls your callbacks again, with no recovery flags or restored context. Default validation accepts an existing changelog section for the version or pending notes, so reruns work; your callbacks must also be safe to rerun: ```ruby RubyGemRelease::Tasks.install do |tasks| @@ -28,40 +37,59 @@ end ## Prepare -`tasks.prepare` prepares files after release validation and before testing and publication. The callback receives an [ExecutionContext](execution_context.md); `ctx.release` is an immutable [Release](release.md). Its `version` contains the explicitly selected `INPUT_VERSION`, or the initial gemspec version when that input is empty. `gemspec_version` always retains the initial gemspec version, and `next_version` is `nil`. Custom callbacks own file updates; use your version object's `set!` method to honor a selection and attach the prepared version with `ctx.release.with_version(version.read)` before updating a changelog. +`tasks.prepare` edits files after validation and before tests and publication. It receives an [ExecutionContext](execution_context.md) whose `ctx.release` is an immutable [Release](release.md): -The default `prepare` command invokes `bundle exec rake release:prepare`. The task reads optional `INPUT_VERSION`, `GEMSPEC_VERSION`, and `RELEASE_DATE` from the environment. It validates the selected version before invoking the callback, but does not itself write a version file; the standard workflow callback does that through its configured object. +- `version` is `INPUT_VERSION` if set, otherwise the starting gemspec version. +- `gemspec_version` is always the starting gemspec version. +- `next_version` is `nil`. + +Your callback makes the file changes. Apply a chosen version with your version object's `set!`, then pass `ctx.release.with_version(version.read)` to the changelog. + +The default `prepare` command runs `bundle exec rake release:prepare`, which reads optional `INPUT_VERSION`, `GEMSPEC_VERSION`, and `RELEASE_DATE`. It checks the selected version before calling your callback, but never writes a version file itself. ## Bump -`tasks.bump` prepares the next development iteration after publication. In `ctx.release`, `version` contains the published version and `gemspec_version` retains the initial version. Use `next_release = ctx.release.with_next_version(version.increment!(from: ctx.release.version))` before preparing the next changelog section, so repetition writes the same version rather than incrementing twice. +`tasks.bump` prepares the next development version after publication. `ctx.release.version` is the published version, and `gemspec_version` is the starting version. Compute the next version from the published one, so a rerun writes the same value instead of incrementing twice: -The default `bump` command invokes `bundle exec rake release:bump`. The task reads `RELEASE_VERSION`, `GEMSPEC_VERSION`, and `RELEASE_DATE` from the environment. Neither callback task changes versions implicitly. Configure `git.commit_next!(next_release)` and `git.push!` after your version and changelog edits; the commit context must include the incremented `next_version`. +```ruby +next_release = ctx.release.with_next_version(version.increment!(from: ctx.release.version)) +``` + +Then update the changelog and call `git.commit_next!(next_release)` and `git.push!`; the commit needs the new `next_version`. When those succeed, call `ctx.record_next_version!(next_release.next_version)` so later callbacks see it. The standard workflow does all of this. -After those operations succeed, call `ctx.record_next_version!(next_release.next_version)` to make the value available to later callbacks. The standard workflow does this automatically. +The default `bump` command runs `bundle exec rake release:bump`, which reads `RELEASE_VERSION`, `GEMSPEC_VERSION`, and `RELEASE_DATE`. Neither task changes versions on its own. ## Success and Failure -`tasks.success` runs only after publication and the next development iteration have succeeded. It receives an [ExecutionContext](execution_context.md) with the published release and recorded next development version. Use it for success notifications after the release commits are pushed. +`tasks.success` runs only after publication and the next development version succeed. It receives an [ExecutionContext](execution_context.md) with the published release and recorded next version. Use it for notifications. + +The Actions interfaces call `tasks.failure` when the release fails after Ruby and Bundler are set up. It receives a `RubyGemRelease::ReleaseFailure` with: -The Actions interfaces invoke `tasks.failure` when release processing fails after Ruby and Bundler setup. It receives a `RubyGemRelease::ReleaseFailure` object with `phase`, `error`, and `context` properties. `context` is an execution context whose `release` can be `nil` after an early failure. `error` is a reconstructed `RubyGemRelease::ReleaseFailure::CapturedError` with the original exception class name, message, and stack trace when a Ruby task captured it; failures reported only by GitHub Actions have `error: nil`. The original job remains failed if the failure callback also raises. +- `phase`: the ID of the failed Actions step, such as `publish_release`, or `unknown`. This differs from `failure.context.step.id`, which is the failure callback's own step. When several steps fail, the one with a Ruby exception is reported; otherwise any failed step may be reported. +- `error`: a `RubyGemRelease::ReleaseFailure::CapturedError` with the original exception class name, message, and stack trace when a Ruby task caught it, or `nil` when only GitHub Actions reported the failure. +- `context`: an execution context. Its `release` can be `nil` after an early failure. -`phase` is the failed GitHub Actions step ID, such as `publish_release`, or `unknown` when unavailable. It is distinct from `failure.context.step.id`, which identifies the failure callback itself. When multiple steps fail, the step with a captured Ruby exception is preferred; otherwise, one of the failed steps is reported without assuming execution order. +If the failure callback raises, the job still fails. -The reusable workflow and composite action run `bundle exec rake release:success` after a successful release and next development iteration, or `bundle exec rake release:failure` after a failed phase. Override the `success` or `failure` command input when a different command is needed. A failure before Ruby setup completes, or environment protection preventing the job from starting, cannot invoke the failure callback. +The reusable workflow and composite action run `bundle exec rake release:success` or `bundle exec rake release:failure`; override the `success` or `failure` input to change them. The failure callback cannot run if the job fails before Ruby setup completes or environment protection stops it from starting. ## Errors -Each registered callback requires a block and can be registered only once. Exceptions fail the task. Custom code executes with release privileges and must be trusted. Required environment values must contain numeric versions and a date in `YYYY-MM-DD` format; missing values fail rather than guessing a version or date. +Each callback needs a block and can be registered only once. An exception fails the task. Callbacks run with release permissions, so use only trusted code. Required environment values must hold numeric versions and a `YYYY-MM-DD` date; missing values fail rather than being guessed. ## Publish -`tasks.publish` registers publication before `bump`. The default invokes `bundle exec rake release:publish` with the saved release context. It authenticates through the destination only when the workflow cannot verify an exact existing publication. Authentication exceptions are captured as publication failures; absent callbacks do not authenticate. +`tasks.publish` registers publication, which runs before `bump`. The default command runs `bundle exec rake release:publish`. It authenticates through the destination unless the exact package is already published, and reports authentication errors as publication failures. Without a callback, nothing is authenticated or published. -The [Detailed Usage example](usage.md#custom-callbacks) commits, builds, tags, publishes to RubyGems, pushes atomically, and creates a GitHub Release. Without a callback, the task does nothing, including no package publication. To disable only GitHub Release creation, omit `github.publish!` while retaining the other operations. +The [Detailed Usage example](usage.md#custom-callbacks) commits, builds, tags, publishes to RubyGems, pushes commit and tag together, and creates a GitHub Release. To skip only the GitHub Release, leave out `github.publish!`. ## Workflow Credentials -`release:workflow:preflight` checks release prerequisites without editing files, pushing, or publishing. With a RubyGems destination it verifies Trusted Publishing through [`Workflow::RubyGemsCredentials#check!`](workflow/ruby_gems_credentials.md#check) with optional `RUBYGEMS_OWNER_ID`; other destinations skip that check. On GitHub Actions it also checks that the token can push to `DEFAULT_BRANCH` and that no repository rules it cannot bypass would reject the release commit or `vVERSION` tag, using `INPUT_VERSION` or the captured `GEMSPEC_VERSION`; elsewhere it skips that check. Both Actions interfaces run it in every release after context capture, and the reusable workflow runs only it for [dry runs](actions/release.md#dry-run). +`release:workflow:preflight` checks prerequisites without editing, pushing, or publishing: + +- With a RubyGems destination, it checks Trusted Publishing through [`Workflow::RubyGemsCredentials#check!`](workflow/ruby_gems_credentials.md#check), using optional `RUBYGEMS_OWNER_ID`. Other destinations skip this check. +- On GitHub Actions, it checks that the token can push to `DEFAULT_BRANCH` and that no repository rule it cannot bypass would reject the release commit or the `vVERSION` tag. The version is `INPUT_VERSION` or the captured `GEMSPEC_VERSION`. Elsewhere this check is skipped. + +Both Actions interfaces run preflight after capture; [dry runs](actions/release.md#dry-run) of the reusable workflow run only preflight. -`release:workflow:credentials` directly invokes [`Workflow::RubyGemsCredentials`](workflow/ruby_gems_credentials.md) with optional `RUBYGEMS_OWNER_ID`. It remains available for custom RubyGems commands, but neither Actions interface calls a separate authentication task. Normal authentication belongs to `release:publish` through the configured destination. +`release:workflow:credentials` runs [`Workflow::RubyGemsCredentials`](workflow/ruby_gems_credentials.md) with optional `RUBYGEMS_OWNER_ID`, for custom RubyGems commands. The Actions interfaces do not call it; normal authentication happens in `release:publish`. diff --git a/docs/testing.md b/docs/testing.md index 49a6251..a252221 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -1,10 +1,10 @@ # Testing Custom Workflows -Tests for a project's `ruby-gem-release` configuration should exercise the installed gem and the project's own release tasks. A focused test can verify a custom version object or callback, while a disposable consumer test can catch integration regressions across the workflow. +Test your release setup by running your real release tasks against the installed gem. A focused spec can check one custom object or callback; a throwaway project catches problems across the whole release. ## Isolate the Release -Load the optional `ruby-gem-release/rspec` helper and include `RubyGemRelease::RSpec` in an example group. It does not add an RSpec runtime dependency or change production release tasks. +Require the optional `ruby-gem-release/rspec` helper and include `RubyGemRelease::RSpec`. It adds no runtime dependency and does not change your release tasks. ```ruby require 'ruby-gem-release/rspec' @@ -26,17 +26,21 @@ RSpec.describe 'My release configuration' do end ``` -See the [complete spec](../examples/lifecycle_hooks/spec/release_spec.rb) for all fixture files. It exercises the [same workflow builder](../examples/lifecycle_hooks/release_workflow.rb) as the example's production Rakefile, so deleting a hook breaks the spec instead of leaving a separate test configuration working. +The [complete spec](../examples/lifecycle_hooks/spec/release_spec.rb) uses the [same workflow builder](../examples/lifecycle_hooks/release_workflow.rb) as the example's real Rakefile, so removing a hook breaks it. -`with_release_project` creates a temporary checkout, local bare `origin`, and private artifact directory, then cleans them up even if the spec fails. `project.write(path, content)` creates files; `commit!` commits and pushes fixture edits to that local remote. No files or commits are changed in your working checkout. +`with_release_project` creates a temporary checkout, a local bare `origin`, and a private artifact directory, and deletes them afterwards even if the spec fails. Your own checkout is never touched. -`release!` runs capture, validation, preparation, resolution, checkpoint, publication, development bump, and success in separate Rake processes. Pass `test_task: 'verify_release'` to run a fixture-specific check after resolution; the default skips the project's test suite to avoid recursively running this spec. Use `run_task('release:prepare')` for individual tasks and `git(...)` or `remote_file(ref, path)` to inspect results. +- `project.write(path, content)` creates a file. +- `project.commit!` commits fixture changes and pushes them to the local `origin`. +- `project.release!` runs every release step, from capture to success, each in its own Rake process. It skips your test suite so the spec does not run itself; pass `test_task: 'verify_release'` to run a fixture check after resolution. +- `project.run_task('release:prepare')` runs one task. +- `project.git(...)` and `project.remote_file(ref, path)` inspect the result. -The child processes retain Ruby/Bundler paths but do not inherit Actions variables, credentials, Git overrides, or outer release state. `project.environment` lets you add explicit fixture inputs. The helper uses the currently loaded release gem and parent bundle. +Child processes keep Ruby and Bundler paths but not Actions variables, credentials, Git overrides, or outer release state. Add inputs with `project.environment`. The helper uses the currently loaded release gem and bundle. ## Copy Fixture Files -Copy real project files instead of duplicating their contents in the spec. `path:` is the source directory; `files:` accepts a single relative path or glob, or an array mixing both: +Copy real project files instead of repeating them in the spec. `path:` is the source directory; `files:` takes a relative path, a glob, or an array of both: ```ruby source_root = File.expand_path('..', __dir__) @@ -49,17 +53,27 @@ project.copy_files(path: source_root, files: '**/*.{js,md}') project.copy_files(path: source_root, files: ['README.md', 'lib/**/*.rb', 'bin/*']) ``` -Omitting `files:` or passing `nil` copies all files recursively. An empty array copies nothing. Existing exact paths take precedence over glob syntax, so a file named `[notes].md` is copied literally. Overlapping selectors copy each relative file only once. +- Omitting `files:` or passing `nil` copies everything; an empty array copies nothing. +- An existing exact path wins over glob syntax, so `[notes].md` is copied literally. +- Each file is copied once, even if several selectors match. +- `.git` is always skipped; paths or patterns that name it are rejected. +- Git ignore rules do not apply, so select only what you need to avoid copying dependencies and build outputs. +- Empty directories are not copied. -Globs are matched relative to `path:`, not the current directory. Supported patterns include `*`, `?`, character classes such as `[ab]` or `[a-z]`, brace alternatives such as `*.{rb,md}`, and recursive `**/`. A leading `./` is accepted. `*` does not cross directory separators; use `**/*` for all nested files. Hidden files and hidden directories participate in matching, including with `**/*`. Git ignore rules are not applied, so select only the files needed by your fixture to avoid copying dependency directories and build outputs. +Globs match relative to `path:` and support `*`, `?`, `[ab]` or `[a-z]`, `*.{rb,md}`, recursive `**/`, and a leading `./`. `*` stays within one directory; use `**/*` for nested files. Hidden files match too. Globs select files, not directories, and never follow symbolic-link directories. A matched symbolic link must point to a regular file inside the source root; its contents are copied. -Whole-project copying and glob expansion skip `.git` files and directories at every level to preserve the fixture's isolated repository. Explicit paths or patterns containing a `.git` component are rejected. Glob expansion selects files rather than ordinary directories and never traverses symbolic-link directories. A matched symbolic link must resolve to a regular file inside the source root; its contents are copied, not the link itself. +Copying keeps relative paths, content, and file modes, and overwrites existing destination files. These fail: -Copying preserves relative paths, binary content, and file modes, and replaces selected destination files. Missing literal files, patterns matching no files, explicit directory entries, absolute paths, Git metadata, and paths or symbolic links that escape either root are rejected. Every selector must match at least one file. All selected sources and destinations are checked before any copying, so a bad selector or escaping destination link cannot leave a partially copied fixture. Empty directories are not copied. +- missing files, or patterns that match nothing (every selector must match at least one file); +- directories named explicitly; +- absolute paths; +- paths or symbolic links that leave either root. + +Everything is checked before copying starts, so a failure never leaves a half-copied fixture. ## Local Publication -Keep the project's real version object, changelog, and hooks. For a project exposing `GrapeRelease.workflow` in `tasks/release.rb`, configure the fixture after copying that file and its dependencies: +Keep your real version object, changelog, and hooks. For a project that builds its workflow with `GrapeRelease.workflow` in `tasks/release.rb`, copy that file and its dependencies, then: ```ruby project.configure_workflow( @@ -68,11 +82,11 @@ project.configure_workflow( ) ``` -`configure_workflow` writes only the fixture's Rakefile. It requires `ruby-gem-release/rspec`, loads the copied Ruby file, calls the builder with the existing local `Provider`, `Destination`, and `Hosting` adapters, and invokes `install_tasks`. Production configuration is unchanged; `release!` and `run_task` still execute the same release tasks in separate processes. +`configure_workflow` writes only the fixture's Rakefile. It loads your file, calls your builder with the helper's local `Provider`, `Destination`, and `Hosting` adapters, and calls `install_tasks`. `release!` and `run_task` still run the real tasks. -`require:` is a path inside the checkout, with or without `.rb`. Absolute paths, Git metadata, and paths or symbolic links escaping the checkout are rejected. The path is encoded as a Ruby string literal. `builder:` must be a constant path and method, such as `MyProject::Release.workflow`, not an arbitrary Ruby expression. Invalid arguments are rejected before replacing the Rakefile. +`require:` is a path inside the checkout, with or without `.rb`; absolute paths, Git metadata, and paths that leave the checkout are rejected. `builder:` must be a constant and method, such as `MyProject::Release.workflow`, not arbitrary Ruby. Invalid arguments fail before the Rakefile changes. -For custom setup or adapter options, keep using `project.write('Rakefile', ...)`. For example: +For custom setup or adapter options, write the Rakefile yourself: ```ruby project.write('Rakefile', <<~RUBY) @@ -87,14 +101,18 @@ project.write('Rakefile', <<~RUBY) RUBY ``` -The provider transports exported values and failed-task information between fixture processes. The destination and hosting adapters copy the exact built archive to `registry/VERSION.gem` and `hosting/VERSION.gem` under `RELEASE_DATA_DIR`, without authentication or network publication. Repetition accepts identical archives and rejects checksum conflicts. Set `failure: 'Publication rejected'` on either adapter to exercise a failure. +- `Provider` passes exported values and failed-task details between fixture processes. +- `Destination` and `Hosting` copy the exact built gem to `registry/VERSION.gem` and `hosting/VERSION.gem` under `RELEASE_DATA_DIR`, without authentication or network calls. A repeat accepts an identical gem and rejects a different checksum. +- Pass `failure: 'Publication rejected'` to either adapter to simulate a failure. -These are explicit replacements, not a sandbox: custom callbacks can still make external calls. Keep all Git remotes local, replace every external publication boundary, and never dispatch a publishing Actions workflow from these specs. +These adapters are not a sandbox; custom callbacks can still reach the network. Keep all Git remotes local, replace every external publication step, and never trigger a publishing Actions workflow from these specs. ## Check Project-Specific Behavior -Test the behavior your project added, not only that release tasks are registered. Assert the exact README content in both the release tag and the next development commit. This catches a later change that removes the README update even though the gem's standard release still succeeds. +Test what your project adds, not just that the tasks exist. For example, check the exact README text in both the release tag and the next development commit, which catches a change that silently drops the README update. Where relevant, also test that: -Also cover failures and reruns where they matter to the customization: assert that rejected publication leaves the remote release ref unchanged, expected recovery artifacts remain available, and repeating a successful operation does not move immutable release tags or change already-prepared files. +- a rejected publication leaves the remote release ref unchanged; +- recovery artifacts remain available; +- repeating a successful step does not move tags or change prepared files. -The [self-release example](../examples/self_release/README.md) also has a [focused version spec](../spec/release_version_spec.rb) covering README and documentation pins. The [portable integration specs](../spec/integration/consumer/portable_release_spec.rb) reuse the helper for more extensive cross-process and failure coverage. +See also the [self-release example](../examples/self_release/README.md) and its [version spec](../spec/release_version_spec.rb), and the [portable integration specs](../spec/integration/consumer/portable_release_spec.rb) for broader cross-process and failure coverage. diff --git a/docs/usage.md b/docs/usage.md index aa03fc4..add5528 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -1,8 +1,8 @@ # Detailed Usage -Use the [standard workflow](workflow/ruby_gem.md), or configure callbacks for a different sequence. Both use the same release objects and [Actions interface](actions/release.md); install tasks only once. +Use the [standard workflow](workflow/ruby_gem.md), or [custom callbacks](#custom-callbacks) for different release steps. Both use the same [Actions interface](actions/release.md). Install the tasks only once. -If preparation is already reviewed and merged, use the [reviewed workflow](workflow/reviewed_ruby_gem.md) to publish an existing signed tag without new commits, tags, pushes, or development bumps, including explicit stable branches and package collections. +To publish an existing signed tag whose changes are already reviewed and merged, use the [reviewed workflow](workflow/reviewed_ruby_gem.md). It makes no commits, tags, pushes, or version bumps, and supports stable branches and package collections. ## Project Files @@ -16,11 +16,11 @@ module Example end ``` -Choose the matching changelog strategy: [`KeepAChangelog`](changelog/keep_a_changelog.md) for [this sample](../examples/keep_a_changelog/CHANGELOG.md), or [`Intridea`](changelog/intridea.md) for Next headings. Version files and changelog formats are never guessed. +Pick the changelog class that matches your format: [`KeepAChangelog`](changelog/keep_a_changelog.md) for [this sample](../examples/keep_a_changelog/CHANGELOG.md), or [`Intridea`](changelog/intridea.md) for `Next` headings. Neither is guessed. ## Standard Workflow -Add `ruby-gem-release` and `commonmarker ~> 2.10` to the development dependencies and configure the Rakefile. Commonmarker is only needed for Markdown changelogs; packaging, publication, and custom callbacks do not require it. On JRuby, use `changelog: nil` or a project-provided changelog implementation: +Add `ruby-gem-release` and `commonmarker ~> 2.10` (only needed for Markdown changelogs) to your development dependencies. On JRuby, use `changelog: nil` or your own changelog class: ```ruby require 'ruby-gem-release/workflow/ruby_gem' @@ -32,23 +32,23 @@ RubyGemRelease::Workflow::RubyGem.new( ).install_tasks ``` -This validates and prepares the release, publishes the verified gem, pushes the release commit and tag, creates the hosted release, and prepares the next patch version, or the part selected by [`next_version:`](workflow/ruby_gem.md#next-version). +A release validates, updates the version file and changelog, publishes the gem, pushes the release commit and tag, creates the GitHub Release, and bumps the patch version (or the part set by [`next_version:`](workflow/ruby_gem.md#next-version)). -The default releases the checked-in version; optional `version` selects another through the version object's `set!`. The initial version remains in the context. Custom preparation callbacks own their file updates. +It releases the checked-in version unless you pass the optional `version` input, which is written with the version object's `set!`. The context keeps the original version. Custom preparation callbacks must update files themselves. -Configure optional `success:` and `failure:` lambdas on `Workflow::RubyGem.new` for notifications; success receives an execution context after the next development iteration succeeds, while failure receives a `RubyGemRelease::ReleaseFailure` with a phase, captured error when available, and execution context. +**Validation.** Before any edits, `release:validate` fails unless the changelog has pending notes or already has a heading for this version, even with an explicit version. To replace it, pass a `validate:` lambda that raises (or returns `false`) on failure. Without a changelog, validation passes. -Before edits, `release:validate` requires pending notes or an existing heading for the selected release. Otherwise it raises, even with an explicit version. Override with a `validate:` lambda that raises on failure; returning `false` also fails. Without a changelog, validation passes. +**Notifications.** Pass optional `success:` and `failure:` lambdas to `Workflow::RubyGem.new`. `success` gets the execution context after the next development version is pushed. `failure` gets a `RubyGemRelease::ReleaseFailure` with the failed phase, the error when available, and the execution context. -Use [lifecycle hooks](workflow/hooks.md) to add checks or project edits without replacing callbacks. Preparation hooks run inside trusted Git staging; see the [example](../examples/lifecycle_hooks/Rakefile). +**Hooks.** Use [lifecycle hooks](workflow/hooks.md) to add checks or file edits. Edits made by preparation hooks go into the release commit; see the [example](../examples/lifecycle_hooks/Rakefile). -The package uses `GEMSPEC_PATH` or the only root gemspec. Repository, branch, and artifact directory use the existing checkout and workflow defaults. Missing or ambiguous selections fail instead of guessing. +**Defaults.** The gem is built from `GEMSPEC_PATH` or the only gemspec in the root. The repository, branch, and artifact directory come from the checkout and workflow. Missing or ambiguous choices fail. -When adding project-specific release customizations, use optional `ruby-gem-release/rspec` helpers to test the real workflow in a disposable consumer repository and inspect its commits and release-managed files; see [Testing Custom Workflows](testing.md). +**Testing.** The optional `ruby-gem-release/rspec` helpers run the real workflow in a throwaway repository, so you can check the commits and files your customizations produce. See [Testing Custom Workflows](testing.md). ### Bundler Release Tasks -Projects that load `bundler/gem_tasks` or call `Bundler::GemHelper.install_tasks` keep the Bundler `rake release` task, which builds, tags, and pushes locally, then publishes with the RubyGems credentials of whoever runs it. The `release:rubygem_push` and `release:source_control_push` tasks it depends on share the `release:` prefix with these tasks and can be run directly. To make the workflow the only release path, replace all three after Bundler installs them: +`bundler/gem_tasks` and `Bundler::GemHelper.install_tasks` add a `rake release` task that builds, tags, pushes, and publishes from your machine with your own RubyGems credentials. Its helpers `release:rubygem_push` and `release:source_control_push` can also be run directly. To make the workflow the only way to release, replace all three after Bundler installs them: ```ruby %w[release release:rubygem_push release:source_control_push].each do |name| @@ -57,11 +57,11 @@ Projects that load `bundler/gem_tasks` or call `Bundler::GemHelper.install_tasks end ``` -`clear` also removes their prerequisites, so nothing is built or tagged before the task aborts. The Bundler `build` and `install` tasks remain available, and ruby-gem-release's `release:*` tasks are unaffected. +`clear` also removes their prerequisites, so nothing is built or tagged before the task aborts. The Bundler `build` and `install` tasks still work, and this gem's `release:*` tasks are unaffected. ## Object Overrides -Override `package:`, `destination:`, `git:`, `hosting:`, or `provider:` without changing the sequence. For example, disable hosted releases while retaining RubyGems publication: +You can replace `package:`, `destination:`, `git:`, `hosting:`, or `provider:` and keep the same steps. For example, turn off GitHub Releases but keep publishing to RubyGems: ```ruby RubyGemRelease::Workflow::RubyGem.new( @@ -71,11 +71,11 @@ RubyGemRelease::Workflow::RubyGem.new( ).install_tasks ``` -Set `changelog: nil` for projects without a changelog; version incrementing and publication still run. Version and changelog choices are required constructor arguments, even when the changelog is explicitly disabled. +Without a changelog, set `changelog: nil`; version bumps and publication still run. Both `version:` and `changelog:` are required, even when the changelog is `nil`. ## Custom Callbacks -For a genuinely different sequence, configure replacement callbacks explicitly. Individual project customizations should use lifecycle hooks instead. Keep this ordering to preserve artifact identity, concurrency checks, and package-before-tag publication: +Write callbacks only when you need different release steps; for smaller changes, use lifecycle hooks. Keep this order: it ensures the published gem is the one that was built and checked, catches concurrent changes, and publishes the gem before the tag: ```ruby require 'ruby-gem-release/workflow/ruby_gem' @@ -130,82 +130,84 @@ RubyGemRelease::Tasks.install(workflow: workflow, package: package, destination: end ``` -Callbacks receive an [`ExecutionContext`](execution_context.md) containing an immutable [`Release`](release.md); version changes return copies. [`Tasks`](tasks.md) does not edit files. Record the next development version only after its operations succeed. - -Wrap trusted preparation edits in `git.stage_changes!`. Resolution also stages custom `prepare` command outputs before testing. Publication never stages: later working-tree or index changes fail rather than entering the release commit. - -Pass the configured `workflow:` so `release:workflow:checkpoint` can build and preserve artifacts before publication. Each publishing task enforces its own postcondition; an already accepted exact archive succeeds only on matching checksum. See [reruns](../RELEASING.md#verify-and-recover). +- Callbacks receive an [`ExecutionContext`](execution_context.md) with an immutable [`Release`](release.md); version changes return a copy. +- [`Tasks`](tasks.md) does not edit files; your callbacks do. +- Call `record_next_version!` only after the next-version commit is pushed. +- Wrap preparation edits in `git.stage_changes!`. Files changed by a custom `prepare` command are staged before tests run. +- Publication never stages files; later changes fail the release instead of entering the commit. +- Pass `workflow:` so `release:workflow:checkpoint` can build and preserve artifacts before publication. +- Each publishing task checks its own result. On a rerun, an existing gem counts as published only if its checksum matches. See [reruns](../RELEASING.md#verify-and-recover). ## Actions Setup -Follow [Usage](../README.md#usage) to add the caller workflow, enable Trusted Publishing, and dispatch a release. Command overrides and all input defaults are documented in the [workflow reference](actions/release.md). +Follow [Usage](../README.md#usage) to set up and dispatch a release. The [workflow reference](actions/release.md) lists every input, default, and command override. -Both approaches publish when dispatched unless validation fails. All custom commands must be idempotent for the current checkout and inputs and preserve the [rerun contract](../RELEASING.md#verify-and-recover); never overwrite an immutable registry version or move a release tag. +Dispatching publishes unless validation fails. Custom commands must be safe to rerun with the same checkout and inputs ([reruns](../RELEASING.md#verify-and-recover)). Never overwrite a published version or move a release tag. ## Configuration ### GitHub Actions Workflow -Use `with:` inputs for the gemspec, version, runtime, commands, and commit identity. Pin a reviewed release or commit, not `master`. +Set the gemspec, version, Ruby version, commands, and commit author under `with:`. Pin a release or commit, not `master`. - [Release Workflow](actions/release.md): All inputs, defaults, permissions, commands, and recovery artifacts. -- [`Workflow::Environment`](workflow/environment.md): Ruby environment capture and prepared-version checks used by the action workflow. -- [`Workflow::RubyGemsCredentials`](workflow/ruby_gems_credentials.md): RubyGems OIDC authentication, with an optional owner assertion for first publication with a pending trusted publisher. +- [`Workflow::Environment`](workflow/environment.md): Records release settings at the start and checks the prepared version. +- [`Workflow::RubyGemsCredentials`](workflow/ruby_gems_credentials.md): RubyGems Trusted Publishing login, with an optional owner ID for a gem's first release. ### Standard Workflows -Standard workflows wire the usual release sequence using your explicitly chosen version and changelog objects. Override package, Git, or hosting objects when needed; use custom callbacks for a different sequence. +Standard workflows run the usual steps with your version and changelog objects. You can swap the package, Git, or hosting objects. -- [`Workflow::RubyGem`](workflow/ruby_gem.md): Gem release preparation, publication, and next development iteration callbacks with conservative defaults. -- [`Workflow::SemanticRubyGem`](workflow/semantic_ruby_gem.md): Commit-driven decisions, release-history-based versions, and generated notes. +- [`Workflow::RubyGem`](workflow/ruby_gem.md): Prepares, publishes, and bumps the version, with safe defaults. +- [`Workflow::SemanticRubyGem`](workflow/semantic_ruby_gem.md): Picks versions and writes notes from Conventional Commits and past releases. ### Version Objects -Version objects read, set, and increment the version stored in project files. Construct them locally in your callbacks; use your own objects implementing `read`, `set!(value)`, and `increment!(from:)` for other file formats. +Version objects read, set, and bump the version in your project files. For other formats, write your own object with `read`, `set!(value)`, and `increment!(from:)`. -- [`Version::RubyConstant`](version/ruby_constant.md): Numeric Ruby constant versions, updated without evaluating the file. -- [`Version::PlainText`](version/plain_text.md): Numeric versions in a plain text file, such as `VERSION`. -- [`Version::References`](version/references.md): Decorates a version object to update selected release references during the next development bump. +- [`Version::RubyConstant`](version/ruby_constant.md): A numeric version in a Ruby constant, updated without running the file. +- [`Version::PlainText`](version/plain_text.md): A numeric version in a plain text file, such as `VERSION`. +- [`Version::References`](version/references.md): Wraps another version object and also updates version references in other files, such as README pins, to the released version during the next development bump. ### Release Callbacks -Callbacks define project-specific preparation, publication, and next development iteration work. The standard workflow installs them for you; [Detailed Usage](#custom-callbacks) shows manual configuration. Unregistered callbacks do nothing; exceptions fail the task. Custom callback code executes with release privileges and must be trusted. +Callbacks do the release work. The standard workflow installs them; [Custom Callbacks](#custom-callbacks) shows how to set them up by hand. An unregistered callback does nothing, and an exception fails the task. Callback code runs with release credentials, so it must be trusted. -- [`Tasks`](tasks.md): Registers preparation, publication, next-development-iteration, success, and failure callbacks and their Rake tasks. -- [`ExecutionContext`](execution_context.md): Release data, current step, observed steps, configured workflow, and run metadata. -- [`ExecutionProvider`](execution_provider.md): Execution-platform services, with a GitHub Actions implementation and a provider-neutral base. -- [`Release`](release.md): Immutable version and date value used by release operations. +- [`Tasks`](tasks.md): Registers callbacks and their Rake tasks. +- [`ExecutionContext`](execution_context.md): Release data, current and previous steps, the workflow, and run details. +- [`ExecutionProvider`](execution_provider.md): Access to the CI platform, with a GitHub Actions implementation and a generic base. +- [`Release`](release.md): The immutable version and date of a release. ### Changelog Objects -Changelog objects prepare release headings and open the next development section while preserving unrelated Markdown. Choose the strategy matching your changelog format or use custom callbacks for other formats. +Changelog objects add the release heading and open a section for the next version, leaving the rest of the file unchanged. - [`Changelog::KeepAChangelog`](changelog/keep_a_changelog.md): Unreleased sections and version comparison references. - [`Changelog::Intridea`](changelog/intridea.md): Next sections and a configured contribution placeholder. -- [`Changelog::Base`](changelog/base.md): Shared source-preserving implementation for concrete strategies. -- [`Changelog::Generated`](workflow/semantic_ruby_gem.md#notes-and-changelog): Dated sections from persisted semantic notes. +- [`Changelog::Base`](changelog/base.md): Shared base class for the formats above. +- [`Changelog::Generated`](workflow/semantic_ruby_gem.md#notes-and-changelog): Dated sections from notes generated by semantic releases. ### Package Objects -Package objects build and verify artifacts; destinations publish them. +Package objects build and verify the gem; destinations publish it. -- [`Package::RubyGem`](package/ruby_gem.md): Gem metadata, construction, and artifact verification. +- [`Package::RubyGem`](package/ruby_gem.md): Reads gem metadata, builds the gem, and verifies it. ### Registry Destinations -Registry destinations publish built packages independently of package construction and hosted releases. The default destination is RubyGems; custom destinations supply their own registry checks, uploads, and preconfigured credentials. +Destinations publish the built gem to a registry. The default is RubyGems. A custom destination brings its own version checks, uploads, and credentials. -- [`Destination`](destination.md): Shared registry publication contract and authentication selection. -- [`Destination::RubyGems`](destination/ruby_gems.md): Public RubyGems version checks and exact-artifact publication. +- [`Destination`](destination.md): The base class for registries, including how they log in. +- [`Destination::RubyGems`](destination/ruby_gems.md): Checks whether a version exists on RubyGems and publishes the exact built gem. ### Source Control Objects -Source control objects manage release history independently of the repository's hosting provider. +Source control objects create release commits and tags, whatever service hosts the repository. -- [`SourceControl::Git`](source_control/git.md): Release and next development iteration commits, tags, recovery bundles, branch checks, and atomic release pushes. +- [`SourceControl::Git`](source_control/git.md): Release and next-version commits, tags, recovery bundles, branch checks, and all-or-nothing pushes. ### Hosting Objects -Hosting objects publish release notes and attach package artifacts after the release tag is pushed. Set `hosting: nil` in the standard workflow, or omit the hosting publication call in custom callbacks, to disable hosted releases without disabling package publication. +Hosting objects create a release page with notes and the gem after the tag is pushed. To turn this off, set `hosting: nil`, or leave out the hosting call in custom callbacks. -- [`Hosting::GitHubRelease`](hosting/github_release.md): GitHub Releases with changelog or generated notes and the exact gem attached. +- [`Hosting::GitHubRelease`](hosting/github_release.md): A GitHub Release with changelog or generated notes and the exact gem attached. diff --git a/docs/version/plain_text.md b/docs/version/plain_text.md index 00eb9d5..c3e6458 100644 --- a/docs/version/plain_text.md +++ b/docs/version/plain_text.md @@ -1,6 +1,6 @@ # `RubyGemRelease::Version::PlainText` -Reads and updates a file containing a numeric `MAJOR.MINOR.PATCH` version, such as `VERSION`. The file must contain only the version and an optional final Unix or Windows line ending, which updates preserve. Prereleases and `VERSION.yml` are not supported. +Reads and updates a file, such as `VERSION`, that holds only a `MAJOR.MINOR.PATCH` version and an optional final line ending, which updates keep. Prereleases and `VERSION.yml` are not supported. ```ruby require 'ruby-gem-release/version/plain_text' @@ -11,6 +11,6 @@ version.set!('1.2.3') version.increment!(from: '1.2.3') ``` -`path:` defaults to `VERSION`. `increment!` writes the next patch version, or a major or minor version when passed `part: :major` or `part: :minor`. Pass the release version as `from:` for repeatable retries. Invalid current or requested versions fail without writing. +`path:` defaults to `VERSION`. `set!` and `increment!` write and return the new version. `increment!` bumps the patch, or `part: :major` or `part: :minor`. Pass the release version as `from:` so retries write the same result. Invalid versions raise without writing. -Wrap the version in [`References`](references.md) to update selected release references during the next development bump. +Wrap it in [`References`](references.md) to update version references in other files during the next development bump. diff --git a/docs/version/references.md b/docs/version/references.md index 6df426d..f0a68c5 100644 --- a/docs/version/references.md +++ b/docs/version/references.md @@ -1,6 +1,6 @@ # `RubyGemRelease::Version::References` -Decorates a version object to update explicitly selected files and patterns to the released version during `increment!`. Each regular expression must capture the version to replace as `version`: +Wraps a version object so that `increment!` also updates chosen version references, such as install snippets in a README, to the released version. Each regular expression must capture the version as `version`: ```ruby require 'ruby-gem-release/version/ruby_constant' @@ -17,14 +17,14 @@ version = RubyGemRelease::Version::References.new( ## Version -The required `version:` argument is the wrapped object: [`RubyConstant`](ruby_constant.md), [`PlainText`](plain_text.md), or a custom object with `read`, `set!(value)`, and `increment!(from:)`. Objects missing any of them fail at construction. The decorator exposes only those three methods; `read` and `set!` delegate without updating references. Other methods of the wrapped object, such as `next_version`, are not exposed. +`version:` is required: a [`RubyConstant`](ruby_constant.md), [`PlainText`](plain_text.md), or your own object with `read`, `set!(value)`, and `increment!(from:)`. A missing method raises at construction. The wrapper has only those three methods; `read` and `set!` pass through without touching references, and others such as `next_version` are not available. ## References -The required `references:` argument maps literal file paths or Ruby `Dir.glob` patterns to arrays of patterns, expanded when `increment!` runs. Globs select files, exclude hidden names by default, and may match nothing; missing literal files raise an error. When selectors overlap, all their patterns apply in mapping order before the file is written. Each file receives only the patterns from selectors that match it. Configure only your project's references, and do not select the version value itself. +`references:` is required. It maps file paths or `Dir.glob` patterns to arrays of regular expressions, expanded when `increment!` runs. Globs skip hidden files and may match nothing; a missing literal path raises. A file matched by several selectors gets all their patterns, in order. List only your project's references, not the version value itself. ## Increment -`increment!` forwards `from:` and any additional keywords, such as `part:`, to the wrapped object. The wrapped version advances to the next development version, while matching references use `from:` (the released version), including on retries. +`increment!` passes `from:` and other keywords, such as `part:`, to the wrapped object, which moves to the next development version. References are set to `from:`, the released version, including on retries. -Reference files are read and their patterns applied before the wrapped increment, so unreadable files and invalid captures fail before the version changes, and no references are written if the wrapped increment rejects the input. Reference edits are then applied to each file's current content, so a selector that also matches the version file, such as a release comment in `version.rb`, preserves the new version. A file write failure after the increment can leave partial changes; retry using the same `from:` value. +It reads all reference files and applies the patterns before the version changes, so unreadable files and unmatched captures raise first, and nothing is written if the wrapped `increment!` raises. Edits apply to each file's current content, so a pattern that also matches the version file keeps the new version. A write error after that can leave partial changes; retry with the same `from:`. diff --git a/docs/version/ruby_constant.md b/docs/version/ruby_constant.md index e1a29ae..3196827 100644 --- a/docs/version/ruby_constant.md +++ b/docs/version/ruby_constant.md @@ -1,6 +1,6 @@ # `RubyGemRelease::Version::RubyConstant` -Reads and updates numeric `MAJOR.MINOR.PATCH` versions without evaluating the version file. Version objects are local to your configuration; [Tasks](../tasks.md) requires no version strategy. +Reads and updates a numeric `MAJOR.MINOR.PATCH` version assigned to a Ruby constant, without running the file. You only need a version object for your own configuration; [Tasks](../tasks.md) does not require one. ```ruby require 'ruby-gem-release/version/ruby_constant' @@ -10,26 +10,26 @@ version = RubyGemRelease::Version::RubyConstant.new(path: 'lib/example/version.r ## Path -The required `path:` argument identifies the version file. +`path:` is required: the version file. ## Constant -The required `constant:` argument names the Ruby constant, such as `'VERSION'`. The file must contain exactly one quoted assignment to that constant. +`constant:` is required, such as `'VERSION'`. The file must have exactly one quoted assignment to it. ## Read -`version.read` returns the current version string. +`version.read` returns the version string. ## Set -`version.set!('1.2.3')` writes and returns the supplied version, preserving surrounding file content. Invalid versions or ambiguous assignments fail without writing the file. +`version.set!('1.2.3')` writes and returns the version, leaving the rest of the file unchanged. An invalid version or ambiguous assignment raises without writing. ## Increment -`version.increment!` writes and returns the next patch version. Use `part: :minor` or `part: :major` to increment those components and reset lower ones. +`version.increment!` writes and returns the next patch version. `part: :minor` or `part: :major` bumps those and resets lower parts. -Pass `from: release.version` to `increment!` to write the same development version on every attempt instead of incrementing the current file twice. `next_version(part: :patch, from: read)` computes that value without editing files. +Pass `from: release.version` so retries write the same version instead of bumping twice. `next_version(part: :patch, from: read)` computes it without writing. ## Release References -Wrap the version in [`References`](references.md) to update selected release references during the next development bump. +Wrap it in [`References`](references.md) to update version references in other files during the next development bump. diff --git a/docs/workflow/environment.md b/docs/workflow/environment.md index 9c31f07..8d329eb 100644 --- a/docs/workflow/environment.md +++ b/docs/workflow/environment.md @@ -1,25 +1,32 @@ # `RubyGemRelease::Workflow::Environment` -Supplies release context checks, invoked through [Tasks](../tasks.md). `Environment.new(provider:)` delegates execution-platform reads and exports to an [ExecutionProvider](../execution_provider.md), selected automatically when omitted. Setup, validation, authentication, artifact uploading, and callback invocation remain pipeline responsibilities. For Actions inputs and defaults, see the [workflow reference](../actions/release.md). +`Environment` checks the release context and exports values for later steps; [Tasks](../tasks.md) call it for you. It works through an [ExecutionProvider](../execution_provider.md), chosen automatically unless you pass `Environment.new(provider:)`. It does not handle setup, validation, authentication, artifact uploads, or callbacks. For Actions inputs and defaults, see the [workflow reference](../actions/release.md). ## Configure -`configure!` exports the composite action's input environment, including `TZ`, through the provider. On Actions this writes `GITHUB_ENV`. It validates the timezone and rejects line breaks in all values before writing any of them. The reusable workflow supplies the same values through its job environment and does not need this method. +`configure!` exports the composite action's inputs, including `TZ`, to `GITHUB_ENV` on Actions. It checks the timezone and rejects line breaks in all values before writing any. The reusable workflow sets these values in its job environment instead. ## Capture -`capture!(package:)` checks the ref and timezone, configures local Git identity, rejects a dirty checkout, reads the initial package version, and checks remote advancement. Tasks supply the configured package; direct calls default to the selected Ruby gem. It exports `TZ`, `GEMSPEC_PATH`, `RELEASE_DATA_DIR`, `GEMSPEC_VERSION`, `RELEASE_DATE`, `SOURCE_COMMIT`, and `SOURCE_DATE_EPOCH`. `GEMSPEC_PATH` is the package's selected path when available, otherwise empty. The release date is captured once in `TZ`, defaulting to UTC. +`capture!(package:)` records the starting point of a release. It checks the ref and timezone, sets the local Git identity, fails on a dirty checkout, reads the current package version, and fails if the remote branch has diverged from your checkout. Tasks pass the configured package; direct calls default to the selected Ruby gem. -`SOURCE_COMMIT` is the checkout commit hash captured before release preparation, not necessarily the later commit tagged for publication. `SOURCE_DATE_EPOCH` is its committer timestamp in Unix seconds, unless an explicit value was supplied. It controls package timestamps independently of generated release commits and the release calendar date. +It exports: -When the provider supplies a directory, capture also creates a unique private state file and exports `RELEASE_STATE_FILE`; otherwise it exports an empty path and callbacks use process-local state. See [Execution Context](../execution_context.md#state). +- `TZ`: the timezone, `UTC` by default. +- `GEMSPEC_PATH`: the package's gemspec path, or empty. +- `RELEASE_DATA_DIR`: the provider's directory for release data. +- `GEMSPEC_VERSION`: the version before release. It never changes. +- `RELEASE_DATE`: today's date in `TZ`, computed once. +- `SOURCE_COMMIT`: the checkout commit before preparation, not the commit that is later tagged. +- `SOURCE_DATE_EPOCH`: the committer time of `SOURCE_COMMIT` in Unix seconds, unless you set it. It sets package timestamps. +- `RELEASE_STATE_FILE`: a new private state file when the provider has a directory; otherwise empty, and state stays in memory. See [Execution Context](../execution_context.md#state). ## Resolve -`resolve!(package:, destination:)` reads the prepared version, validates optional `INPUT_VERSION`, stages trusted preparation outputs, and saves the index tree before testing. It exports `RELEASE_VERSION` and `RELEASE_AUTH_MODE` through the provider. Tasks supply configured objects; direct calls default to the selected Ruby gem and RubyGems destination. Publishing tasks enforce checksum and Git-ref postconditions; resolution does not reject an existing publication. Later working tree or index changes are rejected rather than staged automatically. +`resolve!(package:, destination:)` runs after preparation and before tests. It reads the prepared version and fails if it differs from `INPUT_VERSION` or the saved semantic decision. It then stages the prepared files, saves a snapshot of the Git index, and exports `RELEASE_VERSION` and `RELEASE_AUTH_MODE`. Direct calls default to the selected Ruby gem and RubyGems. -Standard preparation honors optional `version` through `set!`; custom callbacks must honor it themselves. Resolution rejects a prepared version that differs from the explicit or persisted semantic selection. `GEMSPEC_VERSION` always retains the initial package version. +Later changes to the working tree or index are rejected, never staged. An existing publication does not fail resolution; publishing tasks check checksums and Git refs. Standard preparation applies an explicit `version` with `set!`; custom callbacks must apply it themselves. ## Environment -Inputs are `INPUT_GEMSPEC_PATH`, `INPUT_VERSION`, `GIT_USER_NAME`, `GIT_USER_EMAIL`, `DEFAULT_BRANCH`, and optional `TZ`, read through the provider. The provider supplies the ref and export mechanism. Timezone identifiers must resolve under `/usr/share/zoneinfo`, as on the supported Ubuntu runners. Configuration also exports `RUBYGEMS_OWNER_ID` for authentication. See the [reusable workflow](../../.github/workflows/release.yml) and [composite action](../../action.yml) for defaults. +The provider supplies the ref, the export mechanism, and these inputs: `INPUT_GEMSPEC_PATH`, `INPUT_VERSION`, `GIT_USER_NAME`, `GIT_USER_EMAIL`, `DEFAULT_BRANCH`, and optional `TZ`. The timezone must exist under `/usr/share/zoneinfo`, as on the supported Ubuntu runners. `configure!` also exports `RUBYGEMS_OWNER_ID` for authentication. See the [reusable workflow](../../.github/workflows/release.yml) and [composite action](../../action.yml) for defaults. diff --git a/docs/workflow/hooks.md b/docs/workflow/hooks.md index ae758e7..fe59670 100644 --- a/docs/workflow/hooks.md +++ b/docs/workflow/hooks.md @@ -1,6 +1,6 @@ # Lifecycle Hooks -The [standard](ruby_gem.md), [semantic](semantic_ruby_gem.md), and [reviewed](reviewed_ruby_gem.md) workflows support ordered `before` and `after` hooks for the stages they run. Register them before `install_tasks`: +Hooks run your code before or after a release stage in the [standard](ruby_gem.md), [semantic](semantic_ruby_gem.md), and [reviewed](reviewed_ruby_gem.md) workflows. Register them before `install_tasks`: ```ruby workflow.before(:validate) { |ctx| validate_project_notes(ctx) } @@ -10,40 +10,50 @@ workflow.after(:prepare_next) { |ctx| update_development_readme(ctx) } workflow.install_tasks ``` -For each stage, before hooks run in registration order, then the built-in operation, then after hooks in registration order if it succeeded. Hooks add behavior; they do not replace versioning, changelog, publication, Git, hosting, or validation. +Each stage runs its before hooks, the built-in step, then its after hooks, each in registration order. After hooks run only if the step succeeded. Hooks add behavior; they never replace versioning, changelog, publication, Git, hosting, or validation. -Use the built-in [changelog contribution template options](../changelog/keep_a_changelog.md#contribution-templates) for placeholder removal and category restoration rather than implementing those operations as hooks. - -For README updates, use the [Markdown section helper](../markdown.md) to validate and replace one heading's body while keeping project-specific wording in the hook. +To remove changelog placeholders or restore categories, use the [changelog contribution template options](../changelog/keep_a_changelog.md#contribution-templates) instead of a hook. To update a README section, use the [Markdown section helper](../markdown.md) in your hook. ## Context -Hooks receive an immutable execution context with the configured `ctx.workflow` and current `ctx.release`. `ctx.stage`, `ctx.hook`, and `ctx.hook_index` identify the stage, timing, and one-based position. Before capture, `ctx.release` is `nil`; semantic hooks see `ctx.analysis` and the selected version after validation. Next-version hooks see `ctx.release.next_version` after development preparation. +Hooks receive a read-only context: + +- `ctx.workflow` is the configured workflow. +- `ctx.release` is the current release. It is `nil` before `capture`. +- `ctx.stage`, `ctx.hook` (`:before` or `:after`), and `ctx.hook_index` (from 1) identify the hook. +- In semantic workflows, `ctx.analysis` and the selected version are available after `validate`. +- `ctx.release.next_version` is set after `prepare_next`. ## Order -All stages below support both hook timings. This is the Actions sequence; a direct Rake task runs only its own stages. +Every stage below supports both timings. This is the Actions order; a Rake task run directly runs only its own stages. -- Setup: `capture` → `validate` → `prepare_release` → `resolve_version`. The prepared-release `test` command follows; it is not a hook stage. -- Checkpoint: `checkpoint` wraps `commit_release` → `build_package` → `tag_release`. -- Publication: Actions preserve artifacts, then run `authenticate` → `commit_release` → `build_package` → `tag_release` → `publish_registry` → `push_release` → `publish_hosted_release` (if hosting is enabled). -- Next development: `prepare_next` → `commit_next` → `push_next` → `success`. -- Failure: `failure` runs through the existing failure-reporting task. +1. Setup: `capture`, `validate`, `prepare_release`, `resolve_version`. The `test` command runs next; it is not a hook stage. +2. Checkpoint: `checkpoint`, which wraps `commit_release`, `build_package`, and `tag_release`. +3. Publication: Actions saves artifacts, then runs `authenticate`, `commit_release`, `build_package`, `tag_release`, `publish_registry`, `push_release`, and `publish_hosted_release` (when hosting is enabled). +4. Next development version: `prepare_next`, `commit_next`, `push_next`, `success`. +5. On failure: `failure`, inside the failure-reporting task. -Actions run the checkpoint before publication, so `commit_release`, `build_package`, and `tag_release` hooks run twice. Standalone `release:publish` authenticates and runs those three stages once. `push_release` pushes the release commit and tag; `push_next` pushes only the development commit. Artifact preservation and authentication are not part of the checkpoint. +In Actions, `commit_release`, `build_package`, and `tag_release` hooks run twice: in the checkpoint and again in publication. `release:publish` run on its own authenticates and runs them once. `push_release` pushes the release commit and tag; `push_next` pushes only the development commit. ## Safe Edits and Retries -Only `prepare_release` and `prepare_next` are file-editing stages. Both hook timings run inside `git.stage_changes!`, before the release or next-development commit. If a hook raises, later hooks and that stage's after hooks do not run; the release stops, but partial working files are not rolled back. +Edit files only in `prepare_release` and `prepare_next` hooks. These hooks run inside `git.stage_changes!`, so their edits go into the release or next-development commit. If a hook raises, later hooks and the stage's after hooks are skipped and the release stops. Changed files are not rolled back. + +Use other hooks only to check or observe. Publication rebuilds the package, so edits to built files may be lost. If you replace a workflow operation, keep its publication order and concurrency checks. + +Retried tasks and jobs run hooks again, so make them safe to repeat. Some hooks are skipped: -Use other hooks to validate or observe. Publication rebuilds the package after the Actions checkpoint, so edits to generated artifacts may be replaced. Preserve existing publication ordering and concurrency checks when replacing workflow operations. +- `authenticate` hooks, when the destination shows the version is already published; +- hosting hooks, when hosting is disabled; +- semantic development hooks, when `bump: false`. -Hooks may run again when a task or Actions job is retried; make them idempotent. Authentication hooks are skipped when the destination confirms publication, hosting hooks are skipped when hosting is disabled, and semantic development hooks are skipped when `bump: false`. Each Actions process reloads the Rakefile and registers hooks again; callbacks are not serialized. +Each Actions step reloads the Rakefile and registers hooks again; nothing is saved between steps. ## Callbacks and Failures -Existing `success:` and `failure:` callbacks run inside their stages, between before and after hooks. Use `before(:validate)` or `after(:validate)` to add checks; the existing `validate:` option still replaces validation. +`success:` and `failure:` callbacks run inside their stages, between before and after hooks. To add checks, use `before(:validate)` or `after(:validate)`; the `validate:` option replaces validation entirely. -Hook exceptions keep their original class and message and are recorded as `failure.error.stage`, `.hook`, and `.hook_index`. Built-in failures have no hook timing or index. `failure.phase` remains the enclosing task or Actions step. +A hook exception keeps its class and message, and the failure records `failure.error.stage`, `.hook`, and `.hook_index`. Built-in failures have no hook or index. `failure.phase` is the task or Actions step that failed. -See the [consumer example](../../examples/lifecycle_hooks/Rakefile) for project-local edits using the standard workflow, its [complete release spec](../../examples/lifecycle_hooks/spec/release_spec.rb), and [testing helpers](../testing.md). +For a full example, see the [consumer Rakefile](../../examples/lifecycle_hooks/Rakefile), its [release spec](../../examples/lifecycle_hooks/spec/release_spec.rb), and the [testing helpers](../testing.md). diff --git a/docs/workflow/reviewed_ruby_gem.md b/docs/workflow/reviewed_ruby_gem.md index 642e145..476d4dc 100644 --- a/docs/workflow/reviewed_ruby_gem.md +++ b/docs/workflow/reviewed_ruby_gem.md @@ -1,6 +1,6 @@ # Reviewed Ruby Gem Workflow -Use `Workflow::ReviewedRubyGem` when release preparation is already merged and a trusted signed tag already exists remotely. It runs the normal validation, testing, artifact preservation, publication, and notification tasks without editing release files, making commits, creating tags, pushing Git refs, or preparing a development version. +Use `Workflow::ReviewedRubyGem` when the release changes are already merged and a trusted signed tag already exists on the remote. It validates, tests, saves artifacts, publishes, and notifies, but never edits files, commits, tags, pushes, or bumps the version. ```ruby require 'ruby-gem-release/workflow/reviewed_ruby_gem' @@ -19,19 +19,38 @@ RubyGemRelease::Workflow::ReviewedRubyGem.new( ## Source Guards -`branches:` is a required, nonempty list of exact Git branch names, not patterns. The provider ref must name an allowed branch, the checkout must be clean and at its current remote tip, and the package version must match the selected release version. The default manual and semantic workflows retain their default-branch policy. +Required `branches:` lists exact branch names, not patterns. The release fails unless: -Before building and publishing, the workflow requires `vVERSION` at the captured checkout commit, the exact same tag object on the remote, and successful `git verify-tag`. Configure trusted GPG or SSH signers on the runner before invoking release tasks. Lightweight, unsigned, missing, conflicting, or untrusted tags fail rather than being created or replaced. Checkout and branch advancement fail even when the old source remains an ancestor. The default `SourceControl::ReviewedGit` wraps a `SourceControl::Git` checkout and exposes no operations that stage, commit, tag, or push. +- the current ref is one of those branches; +- the checkout is clean and exactly at the remote branch tip; +- the package version matches the release version. -The workflow does not infer review approval from a signature. Keep project-specific merged-PR, maintainer, codename, backport, and release-note policies in `validate:` or lifecycle hooks. Protect the release environment and allowed deployment branches. No option bypasses signature verification. +Before building and publishing, it also requires that: -`release:prepare` only verifies source; `release:bump` is a no-op. The workflow is independent of `Workflow::RubyGem` and accepts no `version:` or `changelog:`; it shares only lifecycle hooks and task installation. Build hooks must not edit tracked files or leave untracked files. A verified Git bundle is retained for inspection. `notes:` optionally accepts a [read-only notes reader](../changelog/notes.md); invalid notes fail validation before registry publication. Custom notifications continue to receive normal execution contexts. +1. Tag `vVERSION` points at the checkout commit. +2. The remote has the exact same tag object. +3. `git verify-tag` succeeds. + +Configure trusted GPG or SSH signers on the runner first. Lightweight, unsigned, missing, conflicting, or untrusted tags fail; they are never created or replaced, and no option skips signature verification. The default `SourceControl::ReviewedGit` has no methods that stage, commit, tag, or push. + +A valid signature does not prove review. Put merged-PR, maintainer, backport, or release-note policies in `validate:` or lifecycle hooks. Protect the release environment and limit its deployment branches. + +## Differences from the Standard Workflow + +`release:prepare` only verifies the source, and `release:bump` does nothing. The workflow accepts no `version:` or `changelog:` and shares only hooks and task installation with `Workflow::RubyGem`. Build hooks must leave the checkout clean. A verified Git bundle is kept for inspection. + +`notes:` optionally takes a [read-only notes reader](../changelog/notes.md). Invalid or empty notes fail validation, before anything is published. ## Package Sets and Retained Inputs -Pass a [package collection](../package/collection.md) as `package:` to publish ruby and Java archives together. Built packages need separate directories. Prebuilt packages need explicit paths, reviewed SHA256 digests, and expected identities; they verify instead of rebuilding. Use [content auditing](../package/ruby_gem.md#content-audit) to bind archive members to Git source, with explicit exceptions for generated outputs. +To publish Ruby and Java archives together, pass a [package collection](../package/collection.md) as `package:`. Packages built during the release need separate directories. Prebuilt packages need explicit paths, reviewed SHA256 digests, and expected identities; they are verified, not rebuilt. [Content auditing](../package/ruby_gem.md#content-audit) checks archive contents against Git source, with listed exceptions for generated files. + +Both Actions interfaces accept two optional inputs, both empty by default: + +- `prepare-artifacts`: a trusted command that runs after dependency setup and before capture. +- `artifacts`: extra newline-separated paths to save before publication. -Both Actions interfaces accept `prepare-artifacts`, an optional trusted command after dependency setup and before context capture, and `artifacts`, additional newline-separated paths to preserve before publication. Their defaults are empty and leave the existing workflow unchanged. For example, with an explicitly approved build run: +For example, to use the output of an approved build run: ```yaml with: @@ -42,6 +61,6 @@ with: ${{ runner.temp }}/reviewed/*.json ``` -Replace the sample run ID and artifact name with reviewed inputs; do not discover the most recent successful build during publication. Downloading Actions artifacts requires the caller's `actions: read` permission. Prepare inputs outside the checkout so capture stays clean. A Rakefile using prebuilt packages is loaded after this preparation command; its configured digests and audit policy remain authoritative. +Use a run ID and artifact name you reviewed; do not pick the latest successful build during publication. Downloading artifacts needs `actions: read` permission in the caller. Download outside the checkout so it stays clean. The Rakefile loads after this command, and its digests and audit policy still decide what is accepted. -The default `release.gem`, `release.json`, and `release.bundle` paths remain included in artifact preservation alongside additional paths. A collection may only produce member archives and the bundle, so explicitly list every member and its reviewed manifest. Uploads are a workflow transport boundary, not a substitute for Ruby-side verification; local consumer tests do not validate live Actions artifact transfer or OIDC. +`release.gem`, `release.json`, and `release.bundle` are always saved too. A collection may produce only member archives and the bundle, so list every member archive and its reviewed manifest in `artifacts`. Uploads do not replace Ruby-side verification. Local tests do not cover live Actions artifact transfer or OIDC. diff --git a/docs/workflow/ruby_gem.md b/docs/workflow/ruby_gem.md index 629d307..77e6859 100644 --- a/docs/workflow/ruby_gem.md +++ b/docs/workflow/ruby_gem.md @@ -1,57 +1,64 @@ # `RubyGemRelease::Workflow::RubyGem` -Installs the standard Ruby gem release sequence through [`Tasks`](../tasks.md), using the existing package, source control, and hosting objects. See [Usage](../../README.md#usage) for the minimal setup or [Detailed Usage](../usage.md) for manual callbacks. +`Workflow::RubyGem` installs the standard gem release tasks through [`Tasks`](../tasks.md). Only `version:` and `changelog:` are required. See [Usage](../../README.md#usage) for the minimal setup or [Detailed Usage](../usage.md) for manual callbacks. ## Version -The required `version:` object implements `read`, `set!(value)`, and `increment!(from:)`; construction fails when any is missing. Bumps always calculate from `release.version`, so repetition writes the same next version. The initial gemspec version remains `release.gemspec_version`. +The required `version:` object implements `read`, `set!(value)`, and `increment!(from:)`; construction fails if any is missing. The next version is always calculated from `release.version`, so a rerun writes the same value. ## Next Version -The optional `next_version:` selects the part incremented for the next development iteration: `:patch` (default), `:minor`, or `:major`, as a Symbol or String. For example, `next_version: :minor` starts `1.3.0` after releasing `1.2.0` or `1.2.1`. The default calls `increment!(from:)` unchanged; other parts call `increment!(from:, part:)`, which [`RubyConstant`](../version/ruby_constant.md), [`PlainText`](../version/plain_text.md), and [`References`](../version/references.md) support. Construction rejects other values, and rejects `:minor` or `:major` when the version object's `increment!` does not accept `part:`, so an unsupported selection fails before publication. +Optional `next_version:` picks the part to increment for the next development version: `:patch` (default), `:minor`, or `:major`, as a Symbol or String. For example, `next_version: :minor` starts `1.3.0` after releasing `1.2.0` or `1.2.1`. + +`:patch` calls `increment!(from:)`; the others call `increment!(from:, part:)`, which [`RubyConstant`](../version/ruby_constant.md), [`PlainText`](../version/plain_text.md), and [`References`](../version/references.md) support. Construction fails for other values, or for `:minor` and `:major` when your `increment!` does not accept `part:`. ## Changelog -The required `changelog:` object implements `release!(release)` and `prepare_next!(release)`. Choose [`KeepAChangelog`](../changelog/keep_a_changelog.md) or [`Intridea`](../changelog/intridea.md) explicitly. Set `changelog: nil` to skip changelog updates without skipping version incrementing. +The required `changelog:` object implements `release!(release)` and `prepare_next!(release)`. Choose [`KeepAChangelog`](../changelog/keep_a_changelog.md) or [`Intridea`](../changelog/intridea.md). Set `changelog: nil` to skip changelog updates; the version is still incremented. -Default validation requires `released?(release.version)` or `pending?`. This permits repetition after changelog preparation; otherwise empty pending notes raise before edits. Custom changelog objects must implement both queries or supply `validate: ->(ctx) { ... }`, raising on invalid state. Returning `false` also fails. With `changelog: nil`, validation passes. Direct `release!` calls reject empty notes unless that version already has a release heading. +Default validation passes when the changelog has pending notes (`pending?`) or already has this version's section (`released?(release.version)`), so reruns work. It always passes with `changelog: nil`. A custom changelog must implement both queries, or you pass `validate: ->(ctx) { ... }`, which must raise on invalid state; returning `false` also fails. Calling `release!` directly fails on empty notes unless the version already has a release heading. ## Package -The optional `package:` defaults to [`Package::RubyGem`](../package/ruby_gem.md), supplying capture, prepared-version checks, and reproducible builds. Implement `version`, `build!(release)`, `artifact(release)`, and `built?(release)` for equivalent verification and publication. `gemspec` remains optional for capture. +Optional `package:` defaults to [`Package::RubyGem`](../package/ruby_gem.md), which reads versions and builds reproducible gems. A custom package implements `version`, `build!(release)`, `artifact(release)`, and `built?(release)`; `gemspec` is optional. ## Destination -The optional `destination:` defaults to [`Destination::RubyGems`](../destination/ruby_gems.md). A registry destination implements `authenticate!(provider:)`, `published?(release, package:)`, `publish!(release, package:)`, and `authentication`. Subclass [`Destination`](../destination.md) for the default credential-retaining authentication hook. +Optional `destination:` defaults to [`Destination::RubyGems`](../destination/ruby_gems.md). A registry destination implements `authenticate!(provider:)`, `published?(release, package:)`, `publish!(release, package:)`, and `authentication`. Subclass [`Destination`](../destination.md) for a default authentication hook that keeps existing credentials. -The same package and destination are supplied to prepared-version resolution and publication. Custom destinations therefore do not run the default RubyGems version checks or authentication. Destination publication must preserve exact-artifact identity and stop before the Git push on failure. +The same package and destination are used to check the prepared version and to publish, so a custom destination replaces the RubyGems checks and authentication. It must publish the exact built archive and raise on failure, so the Git push does not happen. ## Git -The optional `git:` defaults to [`SourceControl::Git`](../source_control/git.md). Custom objects implement `stage_changes!` (yielding to trusted edits), `commit!`, `tag!`, `push!`, and `commit_next!`. Defaults use the provider's directory and checkout branch. Capture separately configures and checks checkout-local Git; task installation does not alter Git configuration. +Optional `git:` defaults to [`SourceControl::Git`](../source_control/git.md) in the provider's directory and checked-out branch. A custom object implements `stage_changes!` (yielding to the file edits), `commit!`, `tag!`, `push!`, and `commit_next!`. Capture configures and checks Git in the checkout; installing tasks changes no Git configuration. ## Execution Provider -The optional `provider:` defaults to [`ExecutionProvider.current`](../execution_provider.md). It supplies inputs, environment transport, execution contexts, temporary storage, and platform-specific authentication services. The same provider is passed to the installed tasks and context checks. Execution providers do not select hosting or registry destinations; no GitLab implementation is included. +Optional `provider:` defaults to [`ExecutionProvider.current`](../execution_provider.md). It supplies inputs, passes values between steps, builds execution contexts, and provides temporary storage and platform authentication. It does not choose hosting or the registry. No GitLab provider is included. ## Hosting -The optional `hosting:` defaults to [`Hosting::GitHubRelease`](../hosting/github_release.md). Custom objects implement idempotent `publish!(release, package:)`. When the changelog implements `notes(version)`, as the built-in formats do, the hosted release receives the released section as its notes, read before any publication so a missing or empty section fails before the gem is pushed. Releases that already carry notes, such as semantic releases, keep them; changelogs without `notes` and `changelog: nil` keep platform-generated notes. Set `hosting: nil` to disable hosting without disabling registry publication or Git. +Optional `hosting:` defaults to [`Hosting::GitHubRelease`](../hosting/github_release.md). A custom object implements `publish!(release, package:)`, which must be safe to repeat. Set `hosting: nil` to skip hosted releases while still publishing the gem and pushing to Git. + +The hosted release uses the release's own notes when it has them, as semantic releases do. Otherwise it uses `changelog.notes(version)`, which both built-in formats implement. These notes are read before anything is published, so a missing or empty section fails before the gem is pushed. Without `notes`, or with `changelog: nil`, the platform generates the notes. ## Install Tasks -`install_tasks` registers preparation, publication, next development iteration, success, failure, and workflow-context tasks. It does not immediately release or change project files. Use it instead of manual `Tasks.install` callback configuration, not alongside another installation. +`install_tasks` registers the release tasks without running them or changing files. Use it instead of `Tasks.install` with manual callbacks, never both. A release runs these steps: -Preparation updates the changelog with the selected version. In Actions, the checkpoint commits, builds, and tags before artifacts are preserved. Publication then authenticates as needed, repeats those three operations, publishes the package, pushes the release commit and tag, and updates hosting. The next development iteration prepares, commits, and pushes the next version. +1. Preparation applies an explicit version, if given, and updates the changelog. +2. In Actions, a checkpoint commits, builds, and tags, then the artifacts are saved. +3. Publication authenticates if needed, repeats the commit, build, and tag, publishes the package, pushes the release commit and tag, and creates the hosted release. +4. The next development version is prepared, committed, and pushed. -Pass optional `success:` and `failure:` callbacks for notifications. Success receives an execution context after the next development iteration completes; failure receives a `RubyGemRelease::ReleaseFailure`. Early failures may not have a release context, and failure callbacks do not turn a failed workflow into a successful one. +Optional `success:` and `failure:` callbacks send notifications. `success` receives an execution context after the next version is pushed. `failure` receives a `RubyGemRelease::ReleaseFailure`, which may have no release after an early failure. A failure callback never makes a failed run succeed. -Contexts expose the configured `ctx.workflow`. Each process reconstructs the workflow from the Rakefile; it is not serialized across Actions steps. +Contexts expose the workflow as `ctx.workflow`. Each process rebuilds it from the Rakefile. ## Lifecycle Hooks -Use `before(stage)` and `after(stage)` hooks to add checks or project edits without replacing callbacks. Preparation hooks run inside trusted Git staging. See the [hook guide](hooks.md) for ordering, safety, and an example. +Use `before(stage)` and `after(stage)` hooks to add checks or file edits without replacing callbacks. See the [hook guide](hooks.md). ## Errors -Errors stop the sequence. Default objects preserve concurrency checks, artifact verification, recovery bundles, and package-before-tag ordering. A failure context may not have a release if capture failed; custom operations must preserve publication order and artifact identity. +Any error stops the release. The default objects keep concurrency checks, artifact verification, recovery bundles, and build-before-tag order. If you replace an operation, keep the publication order and publish the exact built artifact. diff --git a/docs/workflow/ruby_gems_credentials.md b/docs/workflow/ruby_gems_credentials.md index 12ed6de..5ebbb8e 100644 --- a/docs/workflow/ruby_gems_credentials.md +++ b/docs/workflow/ruby_gems_credentials.md @@ -1,35 +1,50 @@ # `RubyGemRelease::Workflow::RubyGemsCredentials` -Performs RubyGems Trusted Publishing exchanges for both existing gems and a new gem's first publication. The RubyGems destination invokes this helper as part of `release:publish` when automatic RubyGems authentication is selected. Neither YAML interface contains a registry-specific authentication step. +`RubyGemsCredentials` uses RubyGems Trusted Publishing to trade the CI job's identity token for a short-lived API key, so you never store one. It works for existing gems and a new gem's first release. The RubyGems destination calls it during `release:publish`, so the YAML interfaces need no authentication step. ## Owner -`RubyGemsCredentials.new(owner: nil, provider: ExecutionProvider.current)` accepts an optional positive numeric RubyGems account ID. An omitted, `nil`, or empty owner selects the existing-gem exchange without an owner field. A nonempty owner must be a positive numeric ID; spaces are not treated as an empty value. +`RubyGemsCredentials.new(owner: nil, provider: ExecutionProvider.current)` takes an optional RubyGems account ID. -For first publication, find the ID on your Pending Trusted Publishers page. The ID identifies the account that will own a newly created gem; it is not an API key. A matching, unexpired pending trusted publisher is still required. +- For an existing gem, omit `owner` (or pass `nil` or an empty string). +- For a first release, pass the numeric ID from your RubyGems Pending Trusted Publishers page. It names the account that will own the gem; it is not an API key. A matching, unexpired pending trusted publisher is still required. + +Any other value must be a positive number; spaces are rejected, not treated as empty. ## Configure -`configure!` asks the [execution provider](../execution_provider.md) for an OIDC token with audience `rubygems.org` and posts `{jwt: token}` to RubyGems' trusted-publisher exchange endpoint, adding `owner` only when supplied. It delegates masking of the OIDC token and returned API key, then exports `RUBYGEMS_API_KEY`, `BUNDLE_GEM__PUSH_KEY`, and `GEM_HOST_API_KEY` through the provider. Only the GitHub provider reads Actions token-request variables or emits Actions logging commands. +`configure!`: + +1. Asks the [execution provider](../execution_provider.md) for an OIDC token with audience `rubygems.org`. +2. Posts `{jwt: token}`, plus `owner` if set, to the RubyGems trusted-publisher exchange endpoint. +3. Masks the token and the returned API key in logs. +4. Exports the key as `RUBYGEMS_API_KEY`, `BUNDLE_GEM__PUSH_KEY`, and `GEM_HOST_API_KEY`. + +On GitHub Actions, the caller must grant `id-token: write`; Actions supplies `ACTIONS_ID_TOKEN_REQUEST_URL`, `ACTIONS_ID_TOKEN_REQUEST_TOKEN`, and `GITHUB_ENV`. Other providers must fetch their own identity token and export values; this class adds no Trusted Publishing support for other platforms. -The direct task `release:workflow:credentials` remains available for custom commands and reads optional `RUBYGEMS_OWNER_ID` through its configured provider. GitHub Actions supplies `ACTIONS_ID_TOKEN_REQUEST_URL`, `ACTIONS_ID_TOKEN_REQUEST_TOKEN`, and `GITHUB_ENV`; the caller must grant `id-token: write`. Another provider must supply its own identity-token acquisition and export behavior; this does not add another platform's Trusted Publishing support. +The `release:workflow:credentials` task runs `configure!` for custom commands, reading optional `RUBYGEMS_OWNER_ID`. ## Check -`check!` performs the same token request and exchange as `configure!`, masks both credentials, and returns the token's `repository`, `job_workflow_ref`, and `environment` claims with the credential's `scopes`, `expires_at`, and asserted `owner` when present. It raises unless the credential grants `push_rubygem`. It exports nothing and discards the credential, which expires after 15 minutes. RubyGems does not report the publisher's gems, so a successful check does not prove that the publisher is attached to a particular gem. +`check!` tests your Trusted Publishing setup without exporting anything. It runs the same exchange as `configure!`, masks both credentials, and returns: + +- the token's `repository`, `job_workflow_ref`, and `environment` claims; +- the key's `scopes`, `expires_at`, and `owner`, when present. + +It raises unless the key grants `push_rubygem`. The key is discarded; it expires after 15 minutes. RubyGems does not report which gems a publisher covers, so a passing check does not prove it is attached to your gem. -A rejected exchange from either method names the decoded `repository`, `job_workflow_ref`, and `environment` claims RubyGems matched against, without the token or response body. A token whose claims cannot be decoded produces the generic message. +If RubyGems rejects the exchange, the error lists the token's `repository`, `job_workflow_ref`, and `environment` claims, but not the token or response body. If the claims cannot be decoded, the error is generic. ## Custom Publication Commands -Authentication is environment-only: the helper neither creates nor modifies `~/.gem/credentials`. This differs from the replaced `rubygems/configure-rubygems-credentials` action, which also wrote that file. Existing credential files are left untouched. +This class only sets environment variables. Unlike the `rubygems/configure-rubygems-credentials` action it replaces, it never creates or changes `~/.gem/credentials`. -Ruby publication callbacks invoked by `release:publish` receive the authenticated environment. Custom publication commands must inherit the exported environment and use `GEM_HOST_API_KEY`, `RUBYGEMS_API_KEY`, or `BUNDLE_GEM__PUSH_KEY` as appropriate for their tool. Do not assume a credentials file exists or rely on named keys in that file. The standard `gem push` publication uses `GEM_HOST_API_KEY`. Credentials are short-lived and must not be logged or persisted in release artifacts. +Ruby publication callbacks run by `release:publish` see the exported variables. A custom publication command must inherit them and use `GEM_HOST_API_KEY`, `RUBYGEMS_API_KEY`, or `BUNDLE_GEM__PUSH_KEY`, whichever its tool reads; the standard `gem push` uses `GEM_HOST_API_KEY`. Do not assume a credentials file or named keys exist. Never log the key or save it in release artifacts. -A `publish` command override that bypasses `release:publish` also bypasses destination authentication and must perform it explicitly. For RubyGems, it can invoke `release:workflow:credentials` before its own publication command. Prefer registering a custom Ruby publication callback and retaining the default task so the configured destination handles authentication automatically. +A `publish` command override that skips `release:publish` also skips authentication, so run `release:workflow:credentials` first. Better, keep the default task and register a Ruby publication callback, so the destination authenticates for you. -This helper supports only the RubyGems Trusted Publishing exchange, not API-token inputs, role assumption, or alternate gem servers. +This class supports only the RubyGems Trusted Publishing exchange. It does not take API tokens, assume roles, or support other gem servers. ## Errors -Requests use HTTPS and bounded connection/read timeouts, without retries. Invalid IDs, failed requests, malformed JSON, and invalid tokens fail before credentials are exported. Response bodies are not included in errors because they may contain credentials. +Requests use HTTPS with timeouts and no retries. Invalid IDs, failed requests, malformed JSON, and invalid tokens fail before anything is exported. Errors never include response bodies, because they may contain credentials. diff --git a/docs/workflow/semantic_ruby_gem.md b/docs/workflow/semantic_ruby_gem.md index d584b79..b6fff18 100644 --- a/docs/workflow/semantic_ruby_gem.md +++ b/docs/workflow/semantic_ruby_gem.md @@ -1,6 +1,6 @@ # `RubyGemRelease::Workflow::SemanticRubyGem` -Select releases from commits instead of handwritten pending notes. Keep the same [runtime and release setup](ruby_gem.md) and manually dispatched Actions interface; this does not enable triggers or authorize publication. +The semantic workflow picks the next version from commit messages instead of handwritten changelog notes. Setup and the manually dispatched Actions workflow match the [standard workflow](ruby_gem.md); it adds no automatic triggers. ```ruby require 'ruby-gem-release/workflow/semantic_ruby_gem' @@ -10,15 +10,13 @@ RubyGemRelease::Workflow::SemanticRubyGem.new( ).install_tasks ``` -Install only one workflow. Execution, package, destination, Git, hosting, and result callbacks remain independently replaceable. - -Use the same [lifecycle hooks](hooks.md) without replacing semantic analysis or publication. After validation, hooks can inspect the selected decision and version. Development hooks run only when `bump: true`. +Install only one workflow. The provider, package, destination, Git, hosting, and callbacks are still replaceable. [Lifecycle hooks](hooks.md) can read the release decision and version after validation; development hooks run only with `bump: true`. ## History and Versions -Validation selects the highest reachable stable `vMAJOR.MINOR.PATCH` tag, not the nearest or newest. Annotated and lightweight tags work; unrelated, prerelease, metadata, and alternate-format tags are ignored. Shallow checkouts fail. Capture fetches tags and checks remote advancement; supply full history. +The last release is the highest stable `vMAJOR.MINOR.PATCH` tag reachable from the current commit, not the nearest or newest. Annotated and lightweight tags count; prerelease, metadata, other-format, and unreachable tags do not. Shallow checkouts fail, so check out full history. -Analysis covers all reachable commits initially, then commits after the selected tag. First release defaults to `1.0.0` regardless of severity; override it with: +Commits after that tag are analyzed, or all commits if there is none. The first release is `1.0.0` whatever the commits say. To change it: ```ruby semantic = RubyGemRelease::SemanticRelease.new( @@ -31,15 +29,22 @@ RubyGemRelease::Workflow::SemanticRubyGem.new( ).install_tasks ``` -Later versions increment the last release, resetting lower components. Development versions do not affect selection. `release.gemspec_version` remains the initial gemspec version; `ctx.analysis.last_release` is the release baseline. +Later releases increment the last release and reset lower parts, for example `1.2.3` to `1.3.0`. Development versions are ignored; `ctx.analysis.last_release` holds the last release. -Explicit `version` can force a release without releasable commits. It must exceed the last release, not necessarily the development or suggested version. Preparation writes it through the version object's `set!`; all later phases must match the persisted selection. +An explicit `version` input forces a release, even without releasable commits. It must be higher than the last release. Preparation writes it with `set!`, and later steps must see the same version. ## Conventional Commits -The default analyzer understands `type(scope)!: description` headers and multiline `BREAKING CHANGE:` or `BREAKING-CHANGE:` notes. Breaking changes select major; `feat` selects minor; `fix` and `perf` select patch. A Git revert of an older change selects patch. Original/revert pairs within the analyzed range cancel each other, including abbreviated commit references. Other commit types and unstructured messages do not select a release by default. The highest applicable release type wins. +The default analyzer reads [Conventional Commits](https://www.conventionalcommits.org/) headers like `type(scope)!: description` and `BREAKING CHANGE:` or `BREAKING-CHANGE:` notes. The highest match wins: + +- A breaking change selects a major release. +- `feat` selects minor. +- `fix`, `perf`, and a Git revert of an older change select patch. +- Other types and unstructured messages select nothing. -Custom rules use Ruby symbol keys and shell-style glob matching through `File.fnmatch?`, not JavaScript micromatch: +A commit and its revert in the analyzed range cancel out, even with an abbreviated hash. + +Custom rules use symbol keys and shell-style globs (`File.fnmatch?`), not JavaScript micromatch: ```ruby analyzer = RubyGemRelease::SemanticRelease::ConventionalCommits.new( @@ -52,31 +57,37 @@ analyzer = RubyGemRelease::SemanticRelease::ConventionalCommits.new( semantic = RubyGemRelease::SemanticRelease.new(analyzer: analyzer) ``` -Supported selectors are `type`, `scope`, and `subject` strings, plus boolean `breaking` and `revert` selectors. A rule matches when all its selectors match. Matching custom rules replace defaults for that commit; the highest positive match wins, or `false` suppresses it if there is no positive match. Unmatched commits fall back to defaults. Use `release: :major`, `:minor`, `:patch`, or `false`. +A rule matches `type`, `scope`, and `subject` strings and boolean `breaking` and `revert`; all its selectors must match. `release:` is `:major`, `:minor`, `:patch`, or `false`. Matching rules replace the defaults for that commit: the highest positive match wins, otherwise `false` suppresses it. Unmatched commits use the defaults. -No releasable commits raises a validation error before downstream operations; the failure callback reports it. Handwritten pending notes do not affect selection. Optional `validate:` raises on invalid state; returning `false` also fails. Its context is the starting snapshot, while subsequent tasks see newly recorded analysis. +If no commit is releasable, validation raises and the failure callback reports it; pending notes do not count. An optional `validate:` callback must raise on invalid state, and returning `false` also fails. It receives the starting context; later tasks see the recorded analysis. ## Notes and Changelog -Generated notes group features, fixes, performance improvements, and other changes, include short commit identifiers, and list breaking-change descriptions separately. Canceled revert pairs are omitted. Headers are escaped for Markdown; breaking descriptions retain their Markdown. Notes are platform-neutral, without guessed host URLs. A forced release with no commits has an explicit-version note. +Generated notes group features, fixes, performance improvements, and other changes with short commit hashes, and list breaking changes separately. Canceled reverts are left out. Headers are escaped for Markdown; breaking-change text keeps its Markdown. Notes have no host URLs. A forced release with no commits gets an explicit-version note. -The default `Changelog::Generated` creates `CHANGELOG.md` if absent or inserts a dated `## VERSION (YYYY/MM/DD)` section before existing second-level sections, preserving historical source and line endings. Use it with a dedicated generated changelog, not a handwritten pending-section convention. It rejects duplicate release headings and content-free notes. It does not create an unreleased section or edit the changelog during a development bump. +The default `Changelog::Generated` creates `CHANGELOG.md` if missing and inserts a dated `## VERSION (YYYY/MM/DD)` section above existing second-level sections, keeping the rest of the file and its line endings. Use it only for a generated changelog, not one with a handwritten pending section. It rejects duplicate headings and empty notes, never adds an unreleased section, and is not changed by a development bump. -Set `changelog: nil` to disable file updates, or supply an object whose `release!(release)` consumes `release.notes`. With `bump: true`, also implement `prepare_next!(release)`. A handwritten changelog provider is not automatically converted to generated notes. +Set `changelog: nil` to skip file updates, or pass an object whose `release!(release)` uses `release.notes`; with `bump: true` it also needs `prepare_next!(release)`. Handwritten changelog classes do not switch to generated notes. -GitHub hosting passes frozen `release.notes` verbatim through a private file; manual workflows retain `--generate-notes`. Custom hosting must use supplied notes and the exact artifact, not reanalyze. +GitHub hosting uses `release.notes` unchanged; the manual workflows use `--generate-notes`. Custom hosting must use the supplied notes and exact artifact, not analyze commits again. ## Development Iterations -With default `bump: false`, the installed bump task does nothing and `release.next_version` stays `nil`. `bump: true` enables the standard increment, commit, and push, using patch unless [`next_version:`](ruby_gem.md#next-version) selects another part. Future selection still uses released tags. Manual workflows continue to bump automatically. +With the default `bump: false`, the bump task does nothing and `release.next_version` stays `nil`. `bump: true` increments, commits, and pushes the next version, using patch unless [`next_version:`](ruby_gem.md#next-version) says otherwise. Selection still uses release tags. Manual workflows always bump. ## State and Callbacks -Validation records one immutable `SemanticRelease::Decision` through `ctx.record_analysis!`. Its fields are `head`, `last_release`, `commits`, `release_type`, `version`, `notes`, and `explicit_version`. `last_release` is `nil` or a frozen hash with string keys `tag`, `version`, and `commit`. `commits` retains the full analyzed range as frozen hashes with `sha` and complete `message`, including commits canceled for release analysis. A no-release decision has `nil` release type, version, and notes. +Validation records one immutable `SemanticRelease::Decision` with `ctx.record_analysis!`: + +- `head`: the analyzed commit. +- `last_release`: `nil`, or a frozen hash with string keys `tag`, `version`, and `commit`. +- `commits`: every analyzed commit, including canceled ones, as frozen hashes with `sha` and full `message`. +- `release_type`, `version`, `notes`: all `nil` when nothing is released. +- `explicit_version`: the forced version, if any. -Later contexts expose persisted analysis without rerunning providers or mutating earlier snapshots. Private invocation-local JSON contains only `analysis` and `next_version`; recording a bump preserves analysis. Corrupt state or unexpected fields fail closed. Failure reporting uses one coherent snapshot, warning and omitting unreadable state without hiding the original error. +Later contexts read this saved decision without rerunning providers. The private JSON state file holds only `analysis` and `next_version`. Corrupt state or unknown fields fail the release. Failure reports skip unreadable state with a warning and still report the original error. -Preserve `RELEASE_STATE_FILE` and captured inputs across processes. Changed `SOURCE_COMMIT`, explicit input, or prepared version fails before publication. In-process tasks can share memory; separate processes need private storage and export transport. +Keep `RELEASE_STATE_FILE` and captured inputs across processes. If `SOURCE_COMMIT`, the explicit input, or the prepared version changes, the release fails before publication. Separate processes need private storage and a way to pass exported values. ## Replacing Providers @@ -89,10 +100,10 @@ Preserve `RELEASE_STATE_FILE` and captured inputs across processes. Changed `SOU | `selector:` | `select(last_release:, release_type:, explicit_version:)` receives the last version string or `nil` and returns a stable version string or `nil`. | | `notes:` | `generate(commits:, version:, last_release:)` returns nonempty Markdown for a selected release. | -`SemanticRelease` validates, copies, and freezes the result. Custom history providers must preserve default-branch ancestry checks and complete history. Custom providers must not publish, alter Git refs, or weaken selection guards. The [GitLab example](../../examples/gitlab_semantic_release/README.md) composes real semantic providers with explicitly unfinished platform adapters. +`SemanticRelease` validates, copies, and freezes each result. A custom history provider must keep default-branch ancestry checks and return complete history. No provider may publish, change Git refs, or weaken selection checks. The [GitLab example](../../examples/gitlab_semantic_release/README.md) combines the real providers with deliberately unfinished platform adapters. ## Compatibility and Scope -The Ruby implementation follows stable-release behavior from [semantic-release v25.0.9](https://github.com/semantic-release/semantic-release/tree/v25.0.9), [commit-analyzer v13.0.1](https://github.com/semantic-release/commit-analyzer/tree/v13.0.1), and [release-notes-generator v14.1.1](https://github.com/semantic-release/release-notes-generator/tree/v14.1.1), including highest reachable stable version, first release `1.0.0`, Conventional Commits severity, custom-rule fallback, and revert cancellation. It is not a port of their JavaScript plugin system, presets, or note templates and adds no Node dependency. +This Ruby code follows the stable-release behavior of [semantic-release v25.0.9](https://github.com/semantic-release/semantic-release/tree/v25.0.9), [commit-analyzer v13.0.1](https://github.com/semantic-release/commit-analyzer/tree/v13.0.1), and [release-notes-generator v14.1.1](https://github.com/semantic-release/release-notes-generator/tree/v14.1.1). It does not port their JavaScript plugins, presets, or note templates, and needs no Node. -Prereleases, maintenance branches, distribution channels, alternate tag formats, and additional CI-platform adapters are outside this first implementation. Clean-checkout, concurrency, preparation, and exact-artifact checks remain; an already-published version succeeds only on matching SHA256. Unlike upstream, this project verifies or uploads the package before atomically pushing commit and tag. Reruns use the [current checkout and inputs](../../RELEASING.md#verify-and-recover), not restored analysis. +Not supported yet: prereleases, maintenance branches, distribution channels, other tag formats, and other CI platforms. The usual clean-checkout, concurrency, and exact-artifact checks still apply, and an already-published version passes only if its SHA256 matches. Unlike upstream, the package is verified or uploaded before the commit and tag are pushed together. Reruns use the [current checkout and inputs](../../RELEASING.md#verify-and-recover), not a saved analysis. diff --git a/examples/gitlab_semantic_release/README.md b/examples/gitlab_semantic_release/README.md index fa9f2f7..0b6cf02 100644 --- a/examples/gitlab_semantic_release/README.md +++ b/examples/gitlab_semantic_release/README.md @@ -1,14 +1,14 @@ # GitLab and Semantic Releases -This example combines the built-in [semantic workflow](../../docs/workflow/semantic_ruby_gem.md) with custom GitLab execution and hosted releases. It keeps the standard Ruby gem builder, RubyGems destination, version-file editor, Git implementation, and publication order. +This example combines the built-in [semantic workflow](../../docs/workflow/semantic_ruby_gem.md) with custom GitLab execution and hosting. It keeps the standard gem builder, RubyGems destination, version file editor, Git support, and publication order. -**GitLab remains an architectural scaffold, not a working integration.** The example-local [execution provider](gitlab.rb) and [hosted-release provider](gitlab_release.rb) raise `NotImplementedError` for missing operations. No GitLab pipeline is supplied. Commit analysis, version selection, generated notes, and decision persistence are implemented by the gem, not placeholders. +**The GitLab parts are a scaffold, not a working integration.** The example [execution provider](gitlab.rb) and [hosting provider](gitlab_release.rb) raise `NotImplementedError` for missing operations, and there is no GitLab pipeline. Commit analysis, version selection, generated notes, and saving the decision are real; the gem implements them. -Start with [the self-release walkthrough](../self_release/README.md) for smaller customizations, or use the semantic workflow with the default GitHub provider before implementing GitLab adapters. +For smaller customizations, start with [the self-release walkthrough](../self_release/README.md). You can also try the semantic workflow with the default GitHub provider before writing GitLab adapters. ## 1. Compose the Workflow -Copy the [Rakefile](Rakefile), `gitlab.rb`, and `gitlab_release.rb` into your project and adjust the version path: +Copy the [Rakefile](Rakefile), `gitlab.rb`, and `gitlab_release.rb` into your project and set your version path: ```ruby require 'ruby-gem-release/workflow/semantic_ruby_gem' @@ -22,36 +22,38 @@ RubyGemRelease::Workflow::SemanticRubyGem.new( ).install_tasks ``` -Install this workflow only once; do not also install the manual workflow or another `Tasks` configuration. Registration does not contact GitLab or publish. Missing provider operations fail explicitly instead of falling back to GitHub. +Install only this workflow, not the manual workflow or another `Tasks` setup. Loading the Rakefile neither contacts GitLab nor publishes. Missing provider operations fail; they never fall back to GitHub. -Execution platform, package registry, and release hosting remain separate choices. This configuration still checks and publishes to RubyGems, not a GitLab registry. +The execution platform, registry, and hosting are separate choices. This setup still publishes to RubyGems, not a GitLab registry. ## 2. Implement GitLab Execution -The `GitLab` placeholder subclasses [`ExecutionProvider`](../../docs/execution_provider.md). Implement environment transport, full Git refs, execution snapshots, phase identities, failure reporting, identity tokens, and safe secret handling. Keep exports available through `fetch` both in the current process and subsequent processes. +The `GitLab` class subclasses [`ExecutionProvider`](../../docs/execution_provider.md). Implement: -Configure `DEFAULT_BRANCH`, `INPUT_GEMSPEC_PATH`, `INPUT_VERSION` (empty for commit-driven selection), and `TZ`. Set `RELEASE_DATA_DIR` to a private directory outside the checkout. Preserve it and the exported `RELEASE_STATE_FILE`, initial commit, initial version, and release date throughout the pipeline, including failure handling. The inherited neutral Git identity can be overridden with `GIT_USER_NAME` and `GIT_USER_EMAIL`. +- reading inputs and exporting values, available through `fetch` in this process and in later ones +- full Git refs +- execution snapshots and step identities +- failure reporting +- identity tokens and safe secret handling -The pipeline owns a complete checkout with tags, dependencies, tests, authorized default-branch execution, concurrency, protected credentials, conditional phases, and recovery-artifact uploads. The GitHub reusable workflow and composite action are not portable GitLab pipelines. +Set `DEFAULT_BRANCH`, `INPUT_GEMSPEC_PATH`, `INPUT_VERSION` (empty to select from commits), and `TZ`. Point `RELEASE_DATA_DIR` at a private directory outside the checkout. Keep that directory and the exported `RELEASE_STATE_FILE`, initial commit, initial version, and release date for the whole pipeline, including failure handling. To change the default Git identity, set `GIT_USER_NAME` and `GIT_USER_EMAIL`. -## 3. Use Built-in Semantic Decisions - -Validation discovers the highest reachable stable release tag, analyzes subsequent Conventional Commits, selects a version, and generates notes once. Its immutable decision is persisted in the private versioned state and exposed as `ctx.analysis` in later callbacks. Do not export the selection as `INPUT_VERSION` or reanalyze it in another process. +Your pipeline must provide a full checkout with tags, dependencies, tests, default-branch-only execution, concurrency control, protected credentials, conditional steps, and artifact uploads. The GitHub reusable workflow and composite action do not run on GitLab. -The selected version is based on the last release, not the checked-in development version. An explicit version can override analysis and force a release; otherwise, no releasable commits is a validation error. Preparation calls the version object's `set!` method and writes a generated changelog by default. +## 3. Use Built-in Semantic Decisions -See the [semantic workflow reference](../../docs/workflow/semantic_ruby_gem.md) for first-release configuration, custom rules and providers, optional changelog updates, and `bump: true`. Development bumps are disabled by default for this workflow. +The gem analyzes commits, selects the version, and generates notes once during validation, then exposes the decision as `ctx.analysis` in later callbacks. Do not export the version as `INPUT_VERSION` or analyze again in another process. Having no releasable commits fails validation unless you pass an explicit version. See the [semantic workflow reference](../../docs/workflow/semantic_ruby_gem.md) for version rules, first releases, custom rules, changelog options, and `bump: true`. ## 4. Implement GitLab Hosting -`GitLabRelease#publish!(release, package:)` replaces only hosting. Use `release.notes` for the captured body and `package.artifact(release)` for the verified archive. Verify metadata and asset bytes during publication; replace mutable notes/assets but reject immutable tag conflicts. Do not regenerate notes or rebuild inside hosting. +`GitLabRelease#publish!(release, package:)` replaces only hosting. Use `release.notes` for the body and `package.artifact(release)` for the verified gem file. Verify metadata and asset bytes; replace changed notes and assets, but fail on tag conflicts. Do not regenerate notes or rebuild the gem here. -The standard publication callback commits, builds reproducibly, tags locally, verifies or uploads the exact gem, pushes commit and tag atomically, then invokes hosting. Registry failure prevents the push and hosted release; artifacts remain available for manual inspection. +Publication calls hosting last, after the gem is published and the commit and tag are pushed; see [Execution](../../docs/actions/release.md#execution). ## 5. Supply the Pipeline and Authentication -Invoke capture, validation, preparation, resolution, project tests, checkpoint, required artifact upload, publication, bump, and success in that order. Stop on any failed command, including empty-release validation, and invoke failure handling rather than downstream release operations. Every command must be idempotent using the current checkout and inputs; do not restore an older workflow's context. The bump task is a no-op unless enabled. Retain artifacts for manual inspection. +Run these tasks in order: capture, validate, prepare, resolve, project tests, checkpoint, artifact upload (required), publish, bump, and success. Stop on any failure, including an empty release, and run failure handling instead of the remaining steps. Every task must follow the [rerun rules](../../RELEASING.md#verify-and-recover). The bump task does nothing unless enabled. -Publication authenticates through the configured destination. For RubyGems, implement compatible identity-token acquisition and configure a trusted publisher supported by the actual platform, or supply protected preconfigured credentials with an explicit destination authentication policy. Neither this scaffold nor a GitLab identity token alone establishes registry trust. +Publication authenticates through the configured destination. For RubyGems, either implement identity-token exchange with a trusted publisher that supports your platform, or supply protected credentials with an explicit destination authentication policy. Neither this scaffold nor a GitLab identity token sets up registry trust on its own. -Before enabling real publication, test the completed adapters across separate processes using local Git remotes and isolated registry and hosting boundaries, following the [provider-neutral consumer tests](../../spec/integration/consumer/portable_release_spec.rb). Verify empty-release rejection, selected versions, generated notes, exact-artifact publication, reruns, and failure callbacks without contacting production services. +Before real publication, test your adapters across separate processes, with local Git remotes and isolated registry and hosting, as in the [provider-neutral consumer tests](../../spec/integration/consumer/portable_release_spec.rb). Check empty-release rejection, selected versions, generated notes, exact-artifact publication, reruns, and failure callbacks without contacting production services. diff --git a/examples/lifecycle_hooks/README.md b/examples/lifecycle_hooks/README.md index 3a35798..701d81d 100644 --- a/examples/lifecycle_hooks/README.md +++ b/examples/lifecycle_hooks/README.md @@ -1,6 +1,6 @@ # Lifecycle Hook Example -The [Rakefile](Rakefile) installs the [project workflow](release_workflow.rb), which uses [release hooks](release_notes.rb) to update this README and built-in changelog options to clean contribution placeholders and restore its six-category template. +The [Rakefile](Rakefile) installs the [project workflow](release_workflow.rb). It uses [release hooks](release_notes.rb) to update this README, and built-in changelog options to remove contribution placeholders and restore a six-category template. ## Stable Release @@ -8,6 +8,6 @@ Development documentation. ## Testing -The [complete spec](spec/release_spec.rb) copies the actual workflow and this README into a disposable project. `project.configure_workflow` installs that builder with local adapters without changing the production Rakefile. The spec runs the release, checks both Git commits, and verifies that the registry and hosting adapters stored the exact archive locally. Deleting a README hook or removing the stable-release paragraph causes the spec to fail. +The [spec](spec/release_spec.rb) copies the workflow and this README into a temporary project. `project.configure_workflow` installs the workflow with local adapters, without changing the real Rakefile. The spec runs a release, checks both Git commits, and verifies that the local registry and hosting adapters received the exact gem. Removing a README hook or the Stable Release section makes it fail. -From the `ruby-gem-release` checkout, run `bundle exec rspec examples/lifecycle_hooks/spec/release_spec.rb`. See [Testing Custom Workflows](../../docs/testing.md) to adapt the helper to your own project. +From the `ruby-gem-release` checkout, run `bundle exec rspec examples/lifecycle_hooks/spec/release_spec.rb`. See [Testing Custom Workflows](../../docs/testing.md) to use the helper in your own project. diff --git a/examples/self_release/README.md b/examples/self_release/README.md index 3c9eec2..6b28974 100644 --- a/examples/self_release/README.md +++ b/examples/self_release/README.md @@ -1,12 +1,12 @@ # Releasing `ruby-gem-release` Itself -This project uses the standard workflow with three small customizations: its existing changelog format, a version object that also updates README and documentation pins, and a caller-selected timezone. GitHub Actions, RubyGems Trusted Publishing, package construction, Git publication, and hosted releases retain their defaults. +This project uses the standard workflow with three changes: its own changelog format, a version object that also updates version pins in README and documentation, and a chosen timezone. Everything else uses the defaults. -The working implementation lives in the root [Rakefile](../../Rakefile), [`ReleaseVersion`](../../tasks/release_version.rb), and [publish workflow](../../.github/workflows/publish.yml). This walkthrough explains those files rather than maintaining a second release configuration. +The real configuration is in the root [Rakefile](../../Rakefile), [`ReleaseVersion`](../../tasks/release_version.rb), and the [publish workflow](../../.github/workflows/publish.yml). This walkthrough explains those files. ## 1. Choose the Project Conventions -The Rakefile supplies the version object and the existing [`Intridea` changelog format](../../docs/changelog/intridea.md): +The Rakefile sets the version object and the [`Intridea` changelog format](../../docs/changelog/intridea.md): ```ruby require 'ruby-gem-release/workflow/ruby_gem' @@ -19,21 +19,25 @@ RubyGemRelease::Workflow::RubyGem.new( ).install_tasks ``` -The root Rakefile also installs development tasks; those are unrelated to release customization. Standard validation fails when there are no pending notes or existing heading for the selected release. +The root Rakefile also defines development tasks unrelated to releasing. Validation fails if the changelog has no pending notes and no heading for the release. ## 2. Decorate the Version Update -The project-local `ReleaseVersion.build` wraps a `Version::RubyConstant` in `Version::References`, configured with `readme_path:` and every `docs/**/*.md` file. Its `increment!(from:)` pins this repository's action and reusable workflow to the supplied release version, increments the wrapped version from that same input, writes changed files, and returns the next version. Repetition leaves the version and pins unchanged. +`ReleaseVersion.build` wraps a `Version::RubyConstant` in `Version::References` for `readme_path:` and every `docs/**/*.md` file. Its `increment!(from:)` does three things: -For example, publishing `0.5.0` results in README and documentation references to `v0.5.0` and a development version of `0.5.1`. These are deliberately different values. +1. Pins this repository's action and reusable workflow references to the release version. +2. Increments the wrapped version from that same release version. +3. Writes the changed files and returns the next version. -The standard workflow wraps `increment!` and changelog preparation in the same trusted Git staging boundary. All changed files therefore belong to the **next development iteration commit**, after the release commit and tag have already been published. The `v0.5.0` tag does not receive later README or documentation edits. No custom publication callback or hard-coded staging list is necessary. +Running it again changes nothing. For example, releasing `0.5.0` pins references to `v0.5.0` and sets the development version to `0.5.1`. -Use the [actual configuration](../../tasks/release_version.rb) as the complete implementation. When adapting it to another project, change the version-file path, documentation directory, and repository-specific reference pattern. +The workflow stages these edits together with the next changelog section. They go into the **next development commit**, after the release commit and tag are pushed, so the `v0.5.0` tag never contains them. No custom publication callback or file list is needed. + +To adapt [the configuration](../../tasks/release_version.rb) to another project, change the version file path, documentation directory, and reference pattern. ## 3. Configure the Caller -The project's [publish workflow](../../.github/workflows/publish.yml) calls its own reusable workflow: +The [publish workflow](../../.github/workflows/publish.yml) calls this repository's own reusable workflow: ```yaml jobs: @@ -44,16 +48,15 @@ jobs: version: ${{ inputs.version }} timezone: America/New_York rubygems-owner: ${{ vars.RUBYGEMS_OWNER_ID }} + dry-run: ${{ inputs.dry-run }} ``` -The complete caller defines manual dispatch, its optional version input, and the required contents-write and identity-token permissions. The timezone controls the release date and Git timestamp offsets, not registry timestamps. The non-secret owner variable identifies the RubyGems account for first publication; it is not an API key. +The full file also defines manual dispatch, the optional `version` and `dry-run` inputs, and the `contents: write` and `id-token: write` permissions. The timezone sets the release date and Git timestamp offsets, not registry timestamps. `RUBYGEMS_OWNER_ID` is a non-secret account ID needed only for a first release; it is not an API key. -Other repositories should use a released workflow reference as shown in the [default setup](../../README.md#usage), rather than copying this project's local `uses:` reference. Trusted Publishing, environment protection, and branch permissions still need the [normal setup](../../RELEASING.md). +Other repositories should use a released workflow reference, as in the [default setup](../../README.md#usage), not this local `uses:` path. They still need the [normal setup](../../RELEASING.md) for Trusted Publishing, environment protection, and branch permissions. ## 4. Follow the Standard Release Sequence -After authorized manual dispatch, the workflow captures and validates the checkout, checks for pending notes, prepares the selected version and changelog, resolves the prepared gemspec, and runs tests. It then authenticates, commits and builds the release, tags locally, publishes the exact gem, pushes the release commit and tag, and creates the GitHub Release. - -Only after publication succeeds does it increment the version, update README pins, prepare the next changelog section, and push the next development iteration commit. Standard recovery artifacts and failure handling remain in place. +After an authorized dispatch (see [Releasing This Project](../../RELEASING.md#releasing-this-project)), the workflow runs the [standard steps](../../docs/actions/release.md#execution). The version bump and pin updates happen only after publication succeeds. -For more extensive changes to execution, release decisions, generated notes, and hosting, continue with the [GitLab and semantic-release example](../gitlab_semantic_release/README.md). +For bigger changes to execution, version selection, generated notes, or hosting, see the [GitLab and semantic-release example](../gitlab_semantic_release/README.md).