diff --git a/.github/workflows/Action-Test.yml b/.github/workflows/Action-Test.yml index b2a7d72..11bc047 100644 --- a/.github/workflows/Action-Test.yml +++ b/.github/workflows/Action-Test.yml @@ -1,32 +1,113 @@ name: Action-Test -run-name: "Action-Test - [${{ github.event.pull_request.title }} #${{ github.event.pull_request.number }}] by @${{ github.actor }}" +run-name: "Action-Test - [${{ github.ref_name }}] by @${{ github.actor }}" on: workflow_dispatch: - pull_request: + workflow_call: schedule: - cron: '0 0 * * *' concurrency: - group: ${{ github.workflow }}-${{ github.ref }} + group: ${{ github.workflow }}-tests-${{ github.ref }} cancel-in-progress: true -permissions: - contents: read - pull-requests: read +permissions: {} jobs: + UnitTest: + name: Pester 6.1 + runs-on: ubuntu-24.04 + permissions: + contents: read + steps: + - name: Checkout repo + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Test release decisions + uses: PSModule/Invoke-Pester@4ff33199141fdf22568990b6107fe3148ae93a1c # v5.1.0 + with: + Path: tests + Version: 6.1.0 + Prescript: | + Install-PSResource -Name powershell-yaml -Version '[0.4.12]' -TrustRepository -Repository PSGallery + Install-PSResource -Name PSSemVer -Version '[1.1.10]' -TrustRepository -Repository PSGallery + ActionTestDefault: name: Action-Test - [Default] - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 + permissions: + contents: read + pull-requests: read steps: - name: Checkout repo - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: + ref: ${{ github.sha }} persist-credentials: false - name: Action-Test uses: ./ with: + DefaultBump: patch WhatIf: true + + - name: Prepare caller settings + id: caller-settings + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + $settingsFilePath = Join-Path -Path $env:RUNNER_TEMP -ChildPath 'release-caller.settings.yml' + @' + DefaultBump: major + AutoCleanup: true + CreateMajorTag: false + DatePrereleaseFormat: yyyyMMdd + VersionPrefix: v + WhatIf: false + Debug: true + Verbose: true + WorkingDirectory: .github + Version: '[0.43.1]' + Prerelease: true + '@ | Set-Content -LiteralPath $settingsFilePath + "path=$settingsFilePath" | Add-Content -LiteralPath $env:GITHUB_OUTPUT + + - name: Action-Test - Repository policy + uses: ./ + with: + SettingsFilePath: ${{ steps.caller-settings.outputs.path }} + AutoCleanup: false + DatePrereleaseFormat: '' + VersionPrefix: '' + Debug: '' + Verbose: '' + WorkingDirectory: '' + Version: '' + Prerelease: '' + WhatIf: true + + - name: Action-Test - Explicit standard-value override + uses: ./ + with: + SettingsFilePath: ${{ steps.caller-settings.outputs.path }} + DefaultBump: patch + AutoCleanup: false + DatePrereleaseFormat: '' + VersionPrefix: '' + Debug: false + Verbose: false + WorkingDirectory: ${{ github.workspace }} + Version: '[0.43.1]' + Prerelease: false + WhatIf: true + + - name: Remove caller settings + if: ${{ always() && steps.caller-settings.outputs.path != '' }} + shell: pwsh + env: + CALLER_SETTINGS_PATH: ${{ steps.caller-settings.outputs.path }} + run: Remove-Item -LiteralPath $env:CALLER_SETTINGS_PATH -ErrorAction Stop diff --git a/.github/workflows/Release-Decision.yml b/.github/workflows/Release-Decision.yml new file mode 100644 index 0000000..e62bcba --- /dev/null +++ b/.github/workflows/Release-Decision.yml @@ -0,0 +1,82 @@ +name: Release decision + +on: + workflow_call: + outputs: + Decision: + description: The release or skip decision. + value: ${{ jobs.ReleaseDecision.outputs.Decision }} + ReleaseVersion: + description: The calculated version, if the decision is release. + value: ${{ jobs.ReleaseDecision.outputs.ReleaseVersion }} + ReleasePlan: + description: The source-bound handoff to Publish, if the decision is release. + value: ${{ jobs.ReleaseDecision.outputs.ReleasePlan }} + +permissions: + contents: read + pull-requests: read + +jobs: + ReleaseDecision: + name: Release decision + runs-on: ubuntu-24.04 + outputs: + Decision: ${{ steps.calculate.outputs.Decision }} + ReleaseVersion: ${{ steps.calculate.outputs.ReleaseVersion }} + ReleasePlan: ${{ steps.calculate.outputs.ReleasePlan }} + steps: + - name: Check out the revision under test + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Verify the pull request snapshot + if: ${{ github.event_name == 'pull_request' }} + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + run: $null = & '.\src\Test-ReleaseDecisionContext.ps1' + + - name: Calculate the release decision + id: calculate + uses: ./ + env: + PSMODULE_AUTO_RELEASE_CHECK_PUBLISHER: 'true' + with: + Mode: calculate + + - name: Recheck and report the decision + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + RELEASE_DECISION: ${{ steps.calculate.outputs.Decision }} + RELEASE_VERSION: ${{ steps.calculate.outputs.ReleaseVersion }} + RELEASE_PLAN: ${{ steps.calculate.outputs.ReleasePlan }} + RELEASE_BUMP_SOURCE: ${{ steps.calculate.outputs.BumpSource }} + run: | + $ErrorActionPreference = 'Stop' + $decision = $env:RELEASE_DECISION + $version = $env:RELEASE_VERSION + $source = $env:RELEASE_BUMP_SOURCE + $hasVersion = -not [string]::IsNullOrWhiteSpace($version) + $hasPlan = -not [string]::IsNullOrWhiteSpace($env:RELEASE_PLAN) + if ($decision -cnotin @('release', 'skip') -or -not $source -or + ($decision -ceq 'release') -ne $hasVersion -or $hasVersion -ne $hasPlan) { + throw 'Calculate did not return a complete release decision.' + } + $summary = [ordered]@{ + SourceSha = $env:GITHUB_SHA + Decision = $decision + BumpSource = $source + Version = $version + } + if ($env:GITHUB_EVENT_NAME -ceq 'pull_request') { + $checked = & '.\src\Test-ReleaseDecisionContext.ps1' + $summary.PullRequest = $checked.Number + $summary.BaseBranch = $checked.BaseRef + $summary.BaseSha = $checked.BaseSha + $summary.HeadSha = $checked.HeadSha + } + $summary | ConvertTo-Json diff --git a/.github/workflows/Release.yml b/.github/workflows/Release.yml index fd81eb0..a6d1d4e 100644 --- a/.github/workflows/Release.yml +++ b/.github/workflows/Release.yml @@ -1,8 +1,11 @@ name: Release -run-name: "Release - [${{ github.event.pull_request.title }} #${{ github.event.pull_request.number }}] by @${{ github.actor }}" +run-name: "Release - [${{ github.event.pull_request.title || github.ref_name }}] by @${{ github.actor }}" on: + push: + branches: + - main pull_request: branches: - main @@ -12,25 +15,89 @@ on: - reopened - synchronize - labeled - paths: - - 'action.yml' - - 'src/**' + - unlabeled + - edited concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: false -permissions: - contents: write # Required to create releases - pull-requests: write # Required to create comments on the PRs +permissions: {} jobs: + Plan: + name: Plan + if: ${{ github.event_name == 'push' || github.event.action != 'closed' }} + uses: ./.github/workflows/Release-Decision.yml + permissions: + contents: read + pull-requests: read + + CI: + name: CI + if: ${{ github.event_name == 'push' || github.event.action != 'closed' }} + uses: ./.github/workflows/Action-Test.yml + permissions: + contents: read + pull-requests: read + + PublishStable: + name: Publish stable + needs: [Plan, CI] + if: >- + ${{ github.event_name == 'push' && github.ref_name == github.event.repository.default_branch + && needs.Plan.outputs.Decision == 'release' }} + runs-on: ubuntu-24.04 + permissions: + contents: write # Create the release and its tags + pull-requests: read # Verify the merged pull request and its release decision + steps: + - name: Check out the tested commit + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Require the calculated plan + shell: pwsh + env: + RELEASE_PLAN: ${{ needs.Plan.outputs.ReleasePlan }} + run: | + if ([string]::IsNullOrWhiteSpace($env:RELEASE_PLAN)) { + throw 'A release decision requires a plan from the Plan job.' + } + + - name: Publish the tested release + uses: ./ + with: + Mode: publish + ReleasePlan: ${{ needs.Plan.outputs.ReleasePlan }} + Release: - runs-on: ubuntu-latest + name: Prerelease and cleanup + needs: [Plan, CI] + if: >- + ${{ !cancelled() && github.event_name == 'pull_request' + && github.event.pull_request.head.repo.full_name == github.repository + && (github.event.action == 'closed' || (github.event.action != 'edited' + && needs.Plan.result == 'success' && needs.Plan.outputs.Decision == 'release' && needs.CI.result == 'success' + && contains(github.event.pull_request.labels.*.name, 'release:prerelease'))) }} + runs-on: ubuntu-24.04 + permissions: + contents: write # Create prereleases and clean up their tags + pull-requests: write # Manage release labels and comment on pull requests steps: + - name: Require the merge commit SHA + if: ${{ github.event.action == 'closed' && github.event.pull_request.merged && !github.event.pull_request.merge_commit_sha }} + shell: pwsh + run: throw 'GitHub did not report the merge commit SHA.' + - name: Checkout repo - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 with: + ref: >- + ${{ github.event.action == 'closed' && github.event.pull_request.merged + && github.event.pull_request.merge_commit_sha || github.event.pull_request.base.sha }} persist-credentials: false - name: Release diff --git a/README.md b/README.md index 9cff238..3b9dd05 100644 --- a/README.md +++ b/README.md @@ -1,86 +1,166 @@ # Release-GHRepository -Automatically creates releases based on pull requests and labels. +Calculate versions and create GitHub releases from pull request labels and repository settings. +Repository and workflow maintainers can set the release policy in a GitHub Actions workflow or in the repository settings file. -## Specifications and practices +## Release decision -Release-GHRepository follows: +Release-GHRepository manages five [namespaced release labels][automation-labels]. +Each name uses the format `:`. +The namespace is `release`. The qualifier selects the release instruction. -- [SemVer 2.0.0 specifications](https://semver.org) -- [GitHub Flow specifications](https://docs.github.com/en/get-started/using-github/github-flow) -- [Continuous Delivery practices](https://en.wikipedia.org/wiki/Continuous_delivery) +| Label | Instruction | Valid combination | +| --- | --- | --- | +| `release:patch` | Increment the patch version. | Exactly one bump label. | +| `release:minor` | Increment the minor version. | Exactly one bump label. | +| `release:major` | Increment the major version. | Exactly one bump label. | +| `release:prerelease` | Publish from an open pull request as a prerelease. | With one bump label or a configured default bump. | +| `release:skip` | Validate without publishing a release. | Without another label from the table. | + +If the pull request has no bump or skip label from the table, the action uses `DefaultBump`. +Without a configured bump, the effective value is `none`. Apply one bump label or `release:skip`. +A `release:patch`, `release:minor`, or `release:major` label overrides `DefaultBump`. + +The `release:prerelease` label permits prerelease publication. It is not necessary to calculate a prerelease version. +The `release:skip` label prevents publication. + +The action rejects: + +- a `DefaultBump` value other than exactly `none`, `patch`, `minor`, or `major`; +- no bump label or skip decision when `DefaultBump` is `none`; +- multiple bump labels; +- `release:skip` with another label from the table. + +The action ignores labels that are not in the table. ## How it works -The workflow will trigger on pull requests to the main branch. +In `publish` mode during a pull request run with `WhatIf: false`, the action creates missing labels from the table. +It sets their colors and descriptions. It leaves all other labels unchanged. +The action completes label setup before it changes a release or tag. +Push events do not change labels. -The following labels will inform the action what kind of release to create: -- For a major release, and increasing the first number in the version use: - - `major` - - `breaking` -- For a minor release, and increasing the second number in the version. - - `minor` - - `feature` -- For a patch release, and increases the third number in the version. - - `patch` - - `fix` +The action publishes a prerelease for an open pull request with `release:prerelease`, or for a branch push that matches that pull request. +The prerelease name uses the head branch name. The version tag points to the exact pull request head commit. -When a pull request is closed, the action will create a release based on the labels and clean up any previous prereleases that were created. +Only a push to the default branch can publish a stable release. The version tag points to the exact pushed commit. +The action requires a pull request that merged into that branch at that commit. It uses the labels of that pull request. +A direct push without a matching merged pull request does not publish, even with a configured `DefaultBump`. +The action does not move an existing stable version tag. After publication, it sets each enabled major or minor tag to the same commit. -> [!NOTE] -> The labels can be configured using the `MajorLabels`, `MinorLabels` and `PatchLabels` parameters/settings in the configuration file to trigger -> on other labels. +By default, the release notes start with the pull request title and number, followed by the full pull request description. +Put release-specific upgrade instructions in that description. + +When the pull request closes, Publish does not create a release. If `AutoCleanup` is `true`, it deletes matching prereleases and their tags. +Cleanup does not require a bump or skip label. + +For cleanup, the action finds the version number after `VersionPrefix`. It then matches the exact, case-sensitive identifier for the head branch. +The prefix can be empty or contain hyphens. If you change the prefix, cleanup does not remove prereleases that use the previous prefix. + +The action uses [GitHub-Script](https://github.com/PSModule/GitHub-Script), which uses the workflow token by default. -This action is built on [GitHub-Script](https://github.com/PSModule/GitHub-Script) which by default uses the `GITHUB_TOKEN`. ## Usage -The action can be configured using the following settings: +Run Calculate and CI on `pull_request` events, including `synchronize` and changes to labels. +Also run them on pushes to the repository's default branch. For example, use the following triggers for a repository with `main` as its default branch: -| Name | Description | Default | Required | -| --- | --- | --- | --- | -| `AutoCleanup` | Control whether to automatically cleanup prereleases. If disabled, the action will not remove any prereleases. | `true` | false | -| `AutoPatching` | Control whether to automatically handle patches. If disabled, the action will only create a patch release if the pull request has a 'patch' label. | `true` | false | -| `ConfigurationFile` | The path to the configuration file. Settings in the configuration file take precedence over the action inputs. | `.github\auto-release.yml` | false | -| `CreateMajorTag` | Control whether to create a tag for major releases. | `true` | false | -| `CreateMinorTag` | Control whether to create a tag for minor releases. | `true` | false | -| `DatePrereleaseFormat` | The format to use for the prerelease number using [.NET DateTime format strings](https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings). | `''` | false | -| `IgnoreLabels` | A comma separated list of labels that do not trigger a release. | `NoRelease` | false | -| `IncrementalPrerelease` | Control whether to automatically increment the prerelease number. If disabled, the action will ensure only one prerelease exists for a given branch. | `true` | false | -| `MajorLabels` | A comma separated list of labels that trigger a major release. | `major, breaking` | false | -| `MinorLabels` | A comma separated list of labels that trigger a minor release. | `minor, feature` | false | -| `PatchLabels` | A comma separated list of labels that trigger a patch release. | `patch, fix` | false | -| `UsePRTitleAsReleaseName` | When enabled, uses the pull request title as the name for the GitHub release. | `false` | false | -| `UsePRBodyAsReleaseNotes` | When enabled, uses the pull request body as the release notes for the GitHub release. | `true` | false | -| `UsePRTitleAsNotesHeading` | When enabled, the release notes will begin with the pull request title as a H1 heading followed by the pull request body. The title will include a reference to the PR number. | `true` | false | -| `VersionPrefix` | The prefix to use for the version number. | `v` | false | -| `WhatIf` | Control whether to simulate the action. If enabled, the action will not create any releases. Used for testing. | `false` | false | -| `Debug` | Enable debug output. | `'false'` | false | -| `Verbose` | Enable verbose output. | `'false'` | false | -| `Version` | Specifies the version of the GitHub module to install. Accepts an exact version or a NuGet version range (for example `[1.2.0, 2.0.0)`). | | false | -| `Prerelease` | Allow prerelease versions if available. | `'false'` | false | -| `WorkingDirectory` | The working directory where the script runs. | `${{ github.workspace }}` | false | - -### Configuration file - -The configuration file is a YAML file that can be used to configure the action. -By default, the configuration file is expected at `.github\auto-release.yml`, which can be changed using the `ConfigurationFile` setting. -The action's configuration can be changed by altering the settings in the configuration file. +```yaml +on: + pull_request: + branches: [main] + types: [opened, reopened, synchronize, labeled, unlabeled, edited] + push: + branches: [main] +``` + +Give Calculate read access to contents and pull requests. Give the stable publisher `contents: write` and `pull-requests: read`. +Pin the action to the full commit SHA of a published release that supports these inputs. +Do not use a pull request head in a production workflow. +Use a moving major tag only if the producer's release automation moves it only to compatible stable releases in that major version. + +### Calculate in CI + +Use the same action revision and release settings in CI and in the publisher. +For example, set `DefaultBump` in the repository settings file or pass the same literal value to both invocations. ```yaml -DatePrereleaseFormat: 'yyyyMMddHHmm' -IncrementalPrerelease: false -VersionPrefix: '' +- name: Calculate the release plan + id: calculate + uses: PSModule/Release-GHRepository@ + with: + Mode: calculate ``` -This example uses the date format for the prerelease, disables the incremental prerelease and removes the version prefix. +Calculate does not change releases, tags, labels, or comments. +When there is no bump label, it uses the configured default. Without either, the step fails and tells you how to select a bump or skip. +A valid `release:skip` returns `skip` with no version or plan. CI can still run when publication is skipped. -## Example +On `pull_request`, Calculate returns a prerelease version for an open pull request, even without `release:prerelease`. +For a branch push other than a push to the target repository's default branch, Calculate also needs an open pull request with the exact source repository, branch, and pushed commit. +If more than one matches, set `PullRequest` to the target `OWNER/REPO#NUMBER`. Always set it for a push in a fork. -Add a workflow in your repository using the following example: +On a default-branch push, Calculate returns a stable version only when a merged pull request at that exact commit supplies a release decision. +Use the version from the push run, not the preview from the pull request run. A failed read, a stale pull request, or an invalid decision fails the run without outputs. + +### Publish after CI + +Choose one stable publisher. In both paths, make the publish job depend on successful CI and limit it to pushes to the default branch. +Check out the exact pushed commit (`github.sha`). Do not publish from `pull_request` or from a tag push. + +**Calculate and publish in one action invocation.** Use this step in the publish job when nothing else needs the stable version before publication. +The action resolves the decision again. It publishes only for `release` and does nothing for a valid skip. + +```yaml +- name: Calculate and publish the release + uses: PSModule/Release-GHRepository@ + with: + Mode: publish +``` + +**Calculate early and publish the same plan.** Run Calculate in a read-only `Plan` job on the same push. Expose `Decision`, `ReleaseVersion`, and `ReleasePlan` as job outputs. +Use `ReleaseVersion` for build steps that need the version. Run the publish job only after `Plan` and CI succeed and `needs.Plan.outputs.Decision` is `release`. +Require a nonempty `ReleasePlan` before invoking Publish so a missing output cannot fall back to one-step publication. + +```yaml +- name: Require the calculated plan + shell: pwsh + env: + RELEASE_PLAN: ${{ needs.Plan.outputs.ReleasePlan }} + run: | + if ([string]::IsNullOrWhiteSpace($env:RELEASE_PLAN)) { + throw 'A release decision requires a plan from the Plan job.' + } + +- name: Publish the tested release + uses: PSModule/Release-GHRepository@ + with: + Mode: publish + ReleasePlan: ${{ needs.Plan.outputs.ReleasePlan }} +``` + +Pass the plan unchanged. Publish checks the workflow run, source commit, release settings, supported labels, release history, and PR notes before it writes. +If the plan no longer matches, the action fails instead of publishing with a different version or different notes. +Use `WhatIf: true` to preview either publish path. + +[This repository's pipeline](.github/workflows/Release.yml) uses the staged path. +Its read-only `Release decision` job checks the candidate merge on PRs, including forks and changes that affect only documentation, and the exact pushed commit on `main`. +It reads literal inputs from the `PublishStable` job. If it cannot resolve the publisher or its settings, it fails. +CI still runs when the decision is `skip`. The publisher waits for both jobs. + +The decision result is advisory until branch policy requires a result for the current inputs. +A label-only rerun does not invalidate an earlier pass on the same commit. +See the [required check design][release-decision-check]. + +### Publish and clean up prereleases + +Use a separate PR job for prereleases and cleanup. Keep it separate from the stable publisher. +Use trusted base-repository code and run the write-enabled job only for same-repository pull requests. +For an open PR, only a valid decision with `release:prerelease` can publish. Edits to the PR description do not require another prerelease. +Handle `closed` for cleanup even when there is no release decision. ```yaml -name: Release-GHRepository +name: Prerelease and cleanup on: pull_request: @@ -92,27 +172,164 @@ on: - reopened - synchronize - labeled + - unlabeled concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.base.ref }} + cancel-in-progress: false + +permissions: {} jobs: Release-GHRepository: - runs-on: ubuntu-latest + if: >- + ${{ github.event.pull_request.head.repo.full_name == github.repository + && (github.event.action == 'closed' || contains(github.event.pull_request.labels.*.name, 'release:prerelease')) }} + runs-on: ubuntu-24.04 + permissions: + contents: write # Create releases and tags + pull-requests: write # Manage release labels and comment on pull requests steps: - - name: Checkout Code - uses: actions/checkout@v4 + - name: Checkout code + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false - - name: Release-GHRepository - uses: PSModule/Release-GHRepository@v1 + - name: Release repository + uses: PSModule/Release-GHRepository@ ``` -## Permissions +If a fork contribution needs publication, follow [Prerelease a fork contribution][fork-prerelease]. + +## Inputs -If running the action in a restrictive mode, the following permissions needs to be granted to the action: +`SettingsFilePath` selects the settings file. For inputs that are also settings, a file value overrides the default. +A nonempty input overrides the file value, even if the input equals the default. For Boolean settings, `false` overrides the file value. +If you omit an input or supply `null` or an empty string, the action keeps the file value. + +| Name | Description | Effective default | Required | +| --- | --- | --- | --- | +| `Mode` | Use `calculate` for a read-only version or `publish` to create the release. | `publish` | false | +| `PullRequest` | Select a pull request as `OWNER/REPO#NUMBER` for a branch push. Publish must run in the target repository. | `''` | false | +| `ReleasePlan` | Use the unchanged plan from Calculate in the same workflow run. Omit it to calculate the version during Publish. | `''` | false | +| `AutoCleanup` | Delete prereleases after the pull request closes. | `true` | false | +| `SettingsFilePath` | Select the repository settings file before startup. | `.github\auto-release.yml` | false | +| `DefaultBump` | Select the bump when no bump or skip label exists. Accepts exactly `none`, `patch`, `minor`, or `major` with case-sensitive matching. | `none` | false | +| `CreateMajorTag` | Create or update the floating major tag after a stable release. | `true` | false | +| `CreateMinorTag` | Create or update the floating minor tag after a stable release. | `true` | false | +| `DatePrereleaseFormat` | Append a [.NET date and time format](https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings) to prerelease versions. | `''` | false | +| `IncrementalPrerelease` | Enable prerelease numbering. When false, replace a release at the same prerelease tag. A supplied `ReleasePlan` cannot move that tag to a different commit. | `true` | false | +| `UsePRTitleAsReleaseName` | Use the pull-request title as the GitHub Release name. | `false` | false | +| `UsePRBodyAsReleaseNotes` | Use the pull-request body as release notes. | `true` | false | +| `UsePRTitleAsNotesHeading` | Add the pull-request title and number as the release-notes heading. | `true` | false | +| `VersionPrefix` | Prefix the version number. | `v` | false | +| `WhatIf` | Log release and label changes without mutating repository state. | `false` | false | +| `Debug` | Enable GitHub-Script debug output. | `false` | false | +| `Verbose` | Enable GitHub-Script verbose output. | `false` | false | +| `Version` | Select the GitHub module dependency by exact version or NuGet version range. | `''` (latest) | false | +| `Prerelease` | Allow a prerelease version of the GitHub module dependency. This does not select a repository prerelease. | `false` | false | +| `WorkingDirectory` | Set the execution directory before GitHub-Script starts. Relative values use `github.workspace`. | `github.workspace` | false | + +Use `release:prerelease` to publish a repository prerelease. The `Prerelease` input only controls the GitHub module version. + +### Settings file path + +Omit `SettingsFilePath` to select `.github\auto-release.yml`. To select a different file, supply its path. +Use a file system path. It can contain spaces or brackets. +Do not supply an empty path, a path that contains only whitespace, or a directory. +If the file does not exist, the action uses the defaults and nonempty inputs. + +File selection and execution follow this order: + +1. The action starts from `github.workspace` unless you supply a nonempty `WorkingDirectory` input. It resolves a relative `WorkingDirectory` from `github.workspace`. +2. The action resolves a relative `SettingsFilePath` from that directory. It uses an absolute path as supplied. +3. The action reads the file once. If the file specifies a relative `WorkingDirectory`, the action resolves it from `github.workspace`, not from the file's directory. +4. The action applies the defaults from `action.yml`, then the file values, then nonempty inputs. It runs in the resulting `WorkingDirectory` without selecting another settings file. + +Use the input names in the table as YAML keys, except `SettingsFilePath` and `ReleasePlan`. +The file must contain a YAML mapping. +The action checks the defaults, the file values, and all nonempty inputs before GitHub-Script starts. +It rejects unknown keys, null file values, and invalid values, even if a later input would override them. +Each specified working directory must exist. + +For Boolean settings, use `true` or `false`. You can also use these words as strings in any letter case. Do not add spaces. +The action accepts text values as written. Use a value from the table for `DefaultBump`. + +The action reports whether a label, a workflow input, or the settings file supplies the bump. +For example, if the file sets `DefaultBump: major`, omit the input to use `major`. Set the input to `patch` to use `patch`. +Set the input to `none` to require one bump label or `release:skip` even if the file sets a default bump. + +To remove the prefix or date suffix, set `VersionPrefix: ''` or `DatePrereleaseFormat: ''` in the file. +To use the latest version of the GitHub module, set `Version: ''` in the file. + +```yaml +DatePrereleaseFormat: 'yyyyMMddHHmm' +DefaultBump: patch +IncrementalPrerelease: false +VersionPrefix: '' +Debug: false +Verbose: true +Version: '[0.43.0, 1.0.0)' +Prerelease: false +WorkingDirectory: '.' +``` + +To use a minor bump and turn off cleanup for one run: ```yaml -permissions: - contents: write # Required to create releases - pull-requests: write # Required to create comments on the PRs +with: + DefaultBump: minor + AutoCleanup: false ``` + +To use a custom settings file and run without changing the repository: + +```yaml +with: + SettingsFilePath: .github\repository-release.settings.yml + WhatIf: true +``` + +## Outputs + +These outputs are available only in Calculate mode. For example, read `steps.calculate.outputs.ReleaseVersion` after the step above. + +| Name | Description | +| --- | --- | +| `Decision` | `release` if the version is valid. `skip` for a valid `release:skip` decision or a direct push without a matching merged pull request. | +| `BumpSource` | The release label or settings layer that supplied the decision. | +| `ReleaseVersion` | The calculated SemVer string without `VersionPrefix`. Empty for `skip`. | +| `ReleasePlan` | The source-bound handoff to Publish. Empty for `skip`. | +| `CalculatedAt` | The ISO 8601 UTC instant used to calculate a date-dependent prerelease. Empty for other results. | + +`Version` remains the GitHub module dependency input. It does not accept the calculated release version. + +## Upgrade the action + +Use the [MSX consumer upgrade procedure][consumer-upgrades] to plan the upgrade. +Read the [release notes][release-notes] for each applicable release after the one your workflow uses, through the target release. +Apply only the changes that affect your repository. Update the action pin and make those changes in the same pull request. + +If your workflow relies on an automatic patch bump, set `DefaultBump: patch` in the settings file or action inputs. + +## Contributing + +Follow the [MSX coding standards](https://msxorg.github.io/docs/Coding-Standards/) and [contribution workflow](https://msxorg.github.io/docs/Ways-of-Working/Contribution-Workflow/). + +Run the local tests with PowerShell 7, Pester 6.1.0, powershell-yaml 0.4.12, PSSemVer 1.1.10, and the GitHub module. +The tests do not need GitHub credentials. + +```powershell +Import-Module -Name Pester -RequiredVersion 6.1.0 +Invoke-Pester -Path .\tests +``` + +The tests run the settings and version code. They simulate GitHub responses and prevent repository writes. +The caller job runs the composite action with `WhatIf: true`. These checks do not verify live publication or concurrent release runs. + +[automation-labels]: https://msx.no/docs/Ways-of-Working/Automation-Labels/#namespacing +[release-decision-check]: https://msx.no/docs/Capabilities/release-management/design/#required-pre-merge-decision-check +[fork-prerelease]: https://msx.no/docs/Capabilities/release-management/design/#prerelease-a-fork-contribution +[consumer-upgrades]: https://msx.no/docs/Ways-of-Working/Consumer-Upgrades/ +[release-notes]: https://github.com/PSModule/Release-GHRepository/releases diff --git a/action.yml b/action.yml index bd28559..c954fb5 100644 --- a/action.yml +++ b/action.yml @@ -1,124 +1,208 @@ name: Release GHRepository (by PSModule) -description: Automatically creates releases based on pull requests and labels. +description: Calculates versions and creates GitHub releases from pull request labels and release settings. author: PSModule branding: icon: upload-cloud color: white inputs: - AutoCleanup: - description: Control whether to automatically delete the prerelease tags after the stable release is created. + Mode: + description: >- + Use calculate to return a version without changing the repository. Use publish to create the release. + Effective standard default: publish. + required: false + PullRequest: + description: >- + Select a pull request as OWNER/REPO#NUMBER for a branch push. + The action checks that the pull request matches the push. required: false - default: 'true' - AutoPatching: - description: Control whether to automatically handle patches. If disabled, the action will only create a patch release if the pull request has a 'patch' label. + ReleasePlan: + description: >- + Pass the unchanged ReleasePlan output from Calculate in the same workflow run. + Omit it to calculate and publish in one step. + required: false + AutoCleanup: + description: >- + Delete pull-request prereleases and their tags after the pull request closes. + Effective standard default: true. required: false - default: 'true' - ConfigurationFile: - description: The path to the configuration file. Settings in the configuration file take precedence over the action inputs. + SettingsFilePath: + description: >- + Select the repository settings file before startup. Relative paths use an explicit WorkingDirectory, + otherwise github.workspace. Nonempty named inputs override file values; omitted or empty inputs retain them. required: false default: .github\auto-release.yml + DefaultBump: + description: >- + The bump when the pull request has neither a supported bump label nor release:skip. + Accepts exactly none, patch, minor, or major. Effective standard default: none. + Omit or leave empty to follow repository policy. Use none to clear a configured bump. + required: false CreateMajorTag: - description: Control whether to create a major tag when a pull request is merged into the main branch. + description: >- + Control whether to create or update a major tag after a stable release. + Effective standard default: true. required: false - default: 'true' CreateMinorTag: - description: Control whether to create a minor tag when a pull request is merged into the main branch. + description: >- + Control whether to create or update a minor tag after a stable release. + Effective standard default: true. required: false - default: 'true' DatePrereleaseFormat: - description: If specified, uses a date based prerelease scheme. The format should be a valid .NET format string like 'yyyyMMddHHmm'. - required: false - default: '' - IgnoreLabels: - description: A comma separated list of labels that do not trigger a release. + description: >- + Format the existing prerelease date suffix with a valid .NET format such as yyyyMMddHHmm. + Effective standard default: empty string (no date suffix). required: false - default: NoRelease IncrementalPrerelease: - description: Control whether to automatically increment the prerelease number. If disabled, the action will ensure only one prerelease exists for a given branch. - required: false - default: 'true' - MajorLabels: - description: A comma separated list of labels that trigger a major release. + description: >- + Automatically increment the prerelease number; when false, keep one prerelease for the branch. + Effective standard default: true. required: false - default: major, breaking - MinorLabels: - description: A comma separated list of labels that trigger a minor release. - required: false - default: minor, feature - PatchLabels: - description: A comma separated list of labels that trigger a patch release. - required: false - default: patch, fix UsePRTitleAsReleaseName: - description: When enabled, uses the pull request title as the name for the GitHub release. + description: >- + Use the pull request title as the GitHub release name. + Effective standard default: false. required: false - default: 'false' UsePRBodyAsReleaseNotes: - description: When enabled, uses the pull request body as the release notes for the GitHub release. + description: >- + Use the pull request body as GitHub release notes. + Effective standard default: true. required: false - default: 'true' UsePRTitleAsNotesHeading: - description: When enabled, the release notes will begin with the pull request title as a H1 heading followed by the pull request body. The title will reference the pull request number. + description: >- + Begin release notes with the pull request title and number as an H1 heading. + Effective standard default: true. required: false - default: 'true' VersionPrefix: - description: The prefix to use for the version number. + description: >- + Prefix the version number. + Effective standard default: v. required: false - default: v WhatIf: - description: If specified, the action will only log the changes it would make, but will not actually create or delete any releases or tags. + description: >- + Log planned label, release, tag, and comment changes without mutating repository state. + Effective standard default: false. required: false - default: 'false' Debug: - description: Enable debug output. + description: >- + Enable GitHub-Script debug output. Effective standard default: false. required: false - default: 'false' Verbose: - description: Enable verbose output. + description: >- + Enable GitHub-Script verbose output. Effective standard default: false. required: false - default: 'false' Version: - description: Specifies the version of the GitHub module to be installed. Accepts an exact version or a NuGet version range (for example '[1.2.0, 2.0.0)'). + description: >- + Select the GitHub module dependency by exact version or NuGet version range, such as '[1.2.0, 2.0.0)'. + Effective standard default: empty string (latest dependency version). required: false Prerelease: - description: Allow prerelease versions if available. + description: >- + Allow prerelease versions of the GitHub module dependency. Effective standard default: false. + This does not select repository prerelease mode; use the release:prerelease label. required: false - default: 'false' WorkingDirectory: - description: The working directory where the script will run from. + description: >- + Set the execution directory before GitHub-Script starts. Relative values use github.workspace. + Effective standard default: github.workspace. A file-defined directory does not select another settings file. required: false - default: ${{ github.workspace }} + +outputs: + Decision: + description: The Calculate decision, release or skip. + value: ${{ fromJSON(steps.release.outputs.result || '{}').Decision }} + BumpSource: + description: The release label or settings layer that supplied the Calculate decision. + value: ${{ fromJSON(steps.release.outputs.result || '{}').BumpSource }} + ReleaseVersion: + description: The unprefixed semantic version. Empty for skip. + value: ${{ fromJSON(steps.release.outputs.result || '{}').ReleaseVersion }} + ReleasePlan: + description: The source-bound handoff to Publish. Empty for skip. Do not edit. + value: ${{ fromJSON(steps.release.outputs.result || '{}').ReleasePlan }} + CalculatedAt: + description: The ISO 8601 UTC instant used for a date-dependent prerelease, if applicable. + value: ${{ fromJSON(steps.release.outputs.result || '{}').CalculatedAt }} runs: using: composite steps: - - name: Release-GHRepository - uses: PSModule/GitHub-Script@8083ec1f733f00357ee4d0db0c6056686e483bc0 # v1.9.0 + - name: Resolve release settings + id: settings + shell: pwsh + working-directory: ${{ github.workspace }} env: + PSMODULE_AUTO_RELEASE_ACTION_PATH: ${{ github.action_path }} + PSMODULE_AUTO_RELEASE_SETTING_METADATA: | + Mode: { Type: ReleaseMode, Default: publish, Phase: Release } + PullRequest: { Type: PullRequestSelector, Default: '', Phase: Release } + AutoCleanup: { Type: Boolean, Default: true, Phase: Release } + DefaultBump: { Type: Bump, Default: none, Phase: Release } + CreateMajorTag: { Type: Boolean, Default: true, Phase: Release } + CreateMinorTag: { Type: Boolean, Default: true, Phase: Release } + DatePrereleaseFormat: { Type: DateTimeFormat, Default: '', Phase: Release } + IncrementalPrerelease: { Type: Boolean, Default: true, Phase: Release } + UsePRTitleAsReleaseName: { Type: Boolean, Default: false, Phase: Release } + UsePRBodyAsReleaseNotes: { Type: Boolean, Default: true, Phase: Release } + UsePRTitleAsNotesHeading: { Type: Boolean, Default: true, Phase: Release } + VersionPrefix: { Type: Text, Default: v, Phase: Release } + WhatIf: { Type: Boolean, Default: false, Phase: Release } + Debug: { Type: Boolean, Default: false, Phase: Startup } + Verbose: { Type: Boolean, Default: false, Phase: Startup } + WorkingDirectory: { Type: DirectoryPath, Default: '.', Phase: Startup } + Version: { Type: VersionConstraint, Default: '', Phase: Startup } + Prerelease: { Type: Boolean, Default: false, Phase: Startup } + PSMODULE_AUTO_RELEASE_INPUT_Mode: ${{ inputs.Mode }} + PSMODULE_AUTO_RELEASE_INPUT_PullRequest: ${{ inputs.PullRequest }} PSMODULE_AUTO_RELEASE_INPUT_AutoCleanup: ${{ inputs.AutoCleanup }} - PSMODULE_AUTO_RELEASE_INPUT_AutoPatching: ${{ inputs.AutoPatching }} - PSMODULE_AUTO_RELEASE_INPUT_ConfigurationFile: ${{ inputs.ConfigurationFile }} + PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath: ${{ inputs.SettingsFilePath }} + PSMODULE_AUTO_RELEASE_INPUT_DefaultBump: ${{ inputs.DefaultBump }} PSMODULE_AUTO_RELEASE_INPUT_CreateMajorTag: ${{ inputs.CreateMajorTag }} PSMODULE_AUTO_RELEASE_INPUT_CreateMinorTag: ${{ inputs.CreateMinorTag }} PSMODULE_AUTO_RELEASE_INPUT_DatePrereleaseFormat: ${{ inputs.DatePrereleaseFormat }} - PSMODULE_AUTO_RELEASE_INPUT_IgnoreLabels: ${{ inputs.IgnoreLabels }} PSMODULE_AUTO_RELEASE_INPUT_IncrementalPrerelease: ${{ inputs.IncrementalPrerelease }} - PSMODULE_AUTO_RELEASE_INPUT_MajorLabels: ${{ inputs.MajorLabels }} - PSMODULE_AUTO_RELEASE_INPUT_MinorLabels: ${{ inputs.MinorLabels }} - PSMODULE_AUTO_RELEASE_INPUT_PatchLabels: ${{ inputs.PatchLabels }} PSMODULE_AUTO_RELEASE_INPUT_UsePRBodyAsReleaseNotes: ${{ inputs.UsePRBodyAsReleaseNotes }} PSMODULE_AUTO_RELEASE_INPUT_UsePRTitleAsReleaseName: ${{ inputs.UsePRTitleAsReleaseName }} PSMODULE_AUTO_RELEASE_INPUT_UsePRTitleAsNotesHeading: ${{ inputs.UsePRTitleAsNotesHeading }} PSMODULE_AUTO_RELEASE_INPUT_VersionPrefix: ${{ inputs.VersionPrefix }} PSMODULE_AUTO_RELEASE_INPUT_WhatIf: ${{ inputs.WhatIf }} + PSMODULE_AUTO_RELEASE_INPUT_Debug: ${{ inputs.Debug }} + PSMODULE_AUTO_RELEASE_INPUT_Verbose: ${{ inputs.Verbose }} + PSMODULE_AUTO_RELEASE_INPUT_WorkingDirectory: ${{ inputs.WorkingDirectory }} + PSMODULE_AUTO_RELEASE_INPUT_Version: ${{ inputs.Version }} + PSMODULE_AUTO_RELEASE_INPUT_Prerelease: ${{ inputs.Prerelease }} + run: | + $configuration = @{} + if ($env:PSMODULE_AUTO_RELEASE_CHECK_PUBLISHER -ceq 'true') { + if ($env:PSMODULE_AUTO_RELEASE_INPUT_Mode -cne 'calculate') { + throw 'Publisher settings can only be evaluated in Calculate mode.' + } + $configuration.PublisherBranch = if ($env:GITHUB_EVENT_NAME -ceq 'pull_request') { + $env:GITHUB_BASE_REF + } else { + $env:GITHUB_REF_NAME + } + } + $bootstrap = Join-Path -Path $env:PSMODULE_AUTO_RELEASE_ACTION_PATH -ChildPath 'src\Initialize-ReleaseConfiguration.ps1' + $null = & $bootstrap @configuration + + - name: Release-GHRepository + id: release + uses: PSModule/GitHub-Script@8083ec1f733f00357ee4d0db0c6056686e483bc0 # v1.9.0 + env: + PSMODULE_AUTO_RELEASE_ACTION_PATH: ${{ github.action_path }} + PSMODULE_AUTO_RELEASE_RESOLVED_SETTINGS: ${{ steps.settings.outputs.ReleaseSettings }} + PSMODULE_AUTO_RELEASE_INPUT_ReleasePlan: ${{ inputs.ReleasePlan }} with: - Debug: ${{ inputs.Debug }} - Prerelease: ${{ inputs.Prerelease }} - Verbose: ${{ inputs.Verbose }} - Version: ${{ inputs.Version }} + Debug: ${{ steps.settings.outputs.Debug }} + Prerelease: ${{ steps.settings.outputs.Prerelease }} + Verbose: ${{ steps.settings.outputs.Verbose }} + Version: ${{ steps.settings.outputs.Version }} Name: Release-GHRepository - WorkingDirectory: ${{ inputs.WorkingDirectory }} + WorkingDirectory: ${{ steps.settings.outputs.WorkingDirectory }} Script: | - # Release-GHRepository - ${{ github.action_path }}/src/main.ps1 + $parameters = @{ + Settings = ConvertFrom-Json -InputObject $env:PSMODULE_AUTO_RELEASE_RESOLVED_SETTINGS + ReleasePlan = $env:PSMODULE_AUTO_RELEASE_INPUT_ReleasePlan + } + & (Join-Path -Path $env:PSMODULE_AUTO_RELEASE_ACTION_PATH -ChildPath 'src\main.ps1') @parameters diff --git a/src/Get-EventReleasePlan.ps1 b/src/Get-EventReleasePlan.ps1 new file mode 100644 index 0000000..f836c12 --- /dev/null +++ b/src/Get-EventReleasePlan.ps1 @@ -0,0 +1,513 @@ +#Requires -Version 7.2 + +<# + .SYNOPSIS + Resolve the current release decision, version, and target. + + .DESCRIPTION + Read the matching pull request and stable release baseline for Calculate + and Publish. In Publish mode, check eligibility, an optional exact + source-bound handoff, and existing tags before any write. + + .EXAMPLE + .\Get-EventReleasePlan.ps1 -Settings $releaseSettings + + Return the plan for the current GitHub Actions event. + + .INPUTS + None + + You can't pipe objects to Get-EventReleasePlan.ps1. + + .OUTPUTS + System.Management.Automation.PSCustomObject + + The release plan and exact pull request snapshot used for the decision. +#> +[OutputType([PSCustomObject])] +[CmdletBinding()] +param( + # The validated release settings from the action's startup step. + [Parameter(Mandatory)] + [ValidateNotNull()] + [PSCustomObject] $Settings, + + # The event read by Publish. Calculate reads it from the runner by default. + [Parameter()] + [PSCustomObject] $GitHubEvent, + + # The unchanged Calculate fingerprint to verify before publication. + [Parameter()] + [string] $PlanFingerprint, + + # The original UTC instant for an exact date-dependent version. + [Parameter()] + [datetime] $CalculationTime +) + +$ErrorActionPreference = 'Stop' + +function Invoke-ReleaseGitHubRead { + <# + .SYNOPSIS + Read and parse a GitHub API response for version calculation. + + .DESCRIPTION + Fail on a CLI error or missing response. Keep paginated arrays intact + so the caller can distinguish a successful empty page from a failure. + + .EXAMPLE + Invoke-ReleaseGitHubRead -Endpoint 'repos/example/project/pulls/42' -Hostname 'github.com' -Resource 'pull request 42' + + Return pull request 42 from the target repository. + + .INPUTS + None + + You can't pipe objects to Invoke-ReleaseGitHubRead. + + .OUTPUTS + System.Management.Automation.PSCustomObject + + A JSON object returned by the GitHub API. + + .OUTPUTS + System.Array + + An array of GitHub API pages. + #> + [OutputType([PSCustomObject], [array])] + [CmdletBinding()] + param( + # The API route. + [Parameter(Mandatory)] + [string] $Endpoint, + + # The host of the repository that started the workflow. + [Parameter(Mandatory)] + [string] $Hostname, + + # The resource name for error messages. + [Parameter(Mandatory)] + [string] $Resource, + + # Arguments for the read request. + [Parameter()] + [string[]] $ArgumentList = @('--method', 'GET') + ) + + $PSNativeCommandUseErrorActionPreference = $false + $json = gh api $Endpoint --hostname $Hostname @ArgumentList + if ($LASTEXITCODE -ne 0) { + throw "Failed to read $Resource. gh exited with code [$LASTEXITCODE]." + } + $response = ConvertFrom-Json -InputObject ($json -join "`n") -NoEnumerate + if ($null -eq $response) { + throw "GitHub returned no response when reading $Resource." + } + , $response +} + +function Test-ReleasePullRequest { + <# + .SYNOPSIS + Test whether a pull request matches the exact calculation context. + + .DESCRIPTION + For a stable calculation, require the exact merged commit and base + branch. For a prerelease, require an open pull request with the exact head. + + .EXAMPLE + Test-ReleasePullRequest -PullRequest $pullRequest -Context $context + + Return true only if the pull request matches the event. + + .INPUTS + None + + You can't pipe objects to Test-ReleasePullRequest. + + .OUTPUTS + System.Boolean + + Whether the pull request matches the event. + #> + [OutputType([bool])] + [CmdletBinding()] + param( + # A pull request returned from the target repository. + [Parameter(Mandatory)] + [PSCustomObject] $PullRequest, + + # The target repository, refs, and exact commit from the event. + [Parameter(Mandatory)] + [PSCustomObject] $Context + ) + + if ($PullRequest.base.repo.full_name -ine $Context.TargetRepository -or + [string]::IsNullOrWhiteSpace($PullRequest.base.ref) -or + ($Context.BaseRef -and $PullRequest.base.ref -cne $Context.BaseRef)) { + return $false + } + if ($Context.Stable) { + return ($PullRequest.state -ceq 'closed' -and $PullRequest.merged_at -and + $PullRequest.merge_commit_sha -ieq $Context.CommitSha) + } + $headMatches = $PullRequest.head.ref -ceq $Context.HeadRef -and $PullRequest.head.sha -ieq $Context.CommitSha + $PullRequest.state -ceq 'open' -and $PullRequest.head.repo.full_name -ieq $Context.SourceRepository -and $headMatches +} + +$repository = [Environment]::GetEnvironmentVariable('GITHUB_REPOSITORY') +$eventName = [Environment]::GetEnvironmentVariable('GITHUB_EVENT_NAME') +if ($null -eq $GitHubEvent) { + $eventPath = [Environment]::GetEnvironmentVariable('GITHUB_EVENT_PATH') + $GitHubEvent = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($eventPath)) +} +$repositoryPattern = '\A[A-Za-z0-9][A-Za-z0-9-]*/(?!\.{1,2}\z)[A-Za-z0-9_.-]+\z' +if ($repository -cnotmatch $repositoryPattern -or $GitHubEvent.repository.full_name -ine $repository) { + throw 'The event repository must match GITHUB_REPOSITORY.' +} +$server = $null +if (-not [uri]::TryCreate($env:GITHUB_SERVER_URL, [UriKind]::Absolute, [ref] $server) -or + $server.Scheme -cne 'https' -or -not $server.Host) { + throw 'GITHUB_SERVER_URL must identify the GitHub host.' +} +$publishing = $Settings.Mode -ceq 'publish' +$closedPullRequest = $GitHubEvent.action -ceq 'closed' -or $GitHubEvent.pull_request.state -ceq 'closed' +$cleanupOnly = $publishing -and $eventName -ceq 'pull_request' -and $closedPullRequest +if ($cleanupOnly -and $PlanFingerprint) { + throw 'ReleasePlan was supplied, but a closed pull request is not eligible for publication.' +} +$readParameters = @{ Hostname = $server.Host } +$shaPattern = '\A[0-9a-fA-F]{40}\z' +$context = [PSCustomObject]@{ + SourceRepository = $repository + TargetRepository = $repository + BaseRef = '' + HeadRef = '' + CommitSha = '' + Stable = $false +} +$number = 0 + +switch -CaseSensitive ($eventName) { + 'pull_request' { + if ($Settings.PullRequest) { + throw 'PullRequest can only select a pull request for a branch push.' + } + $eventPullRequest = $GitHubEvent.pull_request + $context.SourceRepository = [string] $eventPullRequest.head.repo.full_name + $context.BaseRef = [string] $eventPullRequest.base.ref + $context.HeadRef = [string] $eventPullRequest.head.ref + $context.CommitSha = [string] $eventPullRequest.head.sha + if (-not [int]::TryParse([string] $eventPullRequest.number, [ref] $number) -or $number -le 0 -or + $eventPullRequest.base.repo.full_name -ine $repository -or -not $context.BaseRef -or + $context.SourceRepository -cnotmatch $repositoryPattern -or -not $context.HeadRef -or + $context.CommitSha -cnotmatch $shaPattern -or $context.CommitSha -ceq ('0' * 40)) { + throw 'The pull request event must identify the target repository and the exact source repository, branch, and commit.' + } + } + 'push' { + $ref = [string] $GitHubEvent.ref + $context.CommitSha = [string] $GitHubEvent.after + if ($GitHubEvent.deleted -isnot [bool] -or $GitHubEvent.deleted -or $ref -cnotmatch '\Arefs/heads/\S+\z' -or + $context.CommitSha -cnotmatch $shaPattern -or $context.CommitSha -ceq ('0' * 40)) { + throw 'Release planning requires a branch push with a full commit SHA, not a tag push or a deleted branch.' + } + $context.HeadRef = $ref.Substring('refs/heads/'.Length) + if ([string]::IsNullOrWhiteSpace($GitHubEvent.repository.default_branch) -or $GitHubEvent.repository.fork -isnot [bool]) { + throw 'The push event must identify the default branch and whether the repository is a fork.' + } + if ($Settings.PullRequest) { + $context.TargetRepository, $selectedNumber = $Settings.PullRequest.Split('#', 2) + $number = [int] $selectedNumber + if ($publishing -and $context.TargetRepository -ine $repository) { + throw 'Publish must run in the target repository. Use Calculate for a pull request selection from a fork.' + } + } elseif ($GitHubEvent.repository.fork) { + if ($publishing) { + if ($PlanFingerprint) { + throw 'ReleasePlan was supplied, but a fork push is not eligible for publication to its upstream repository.' + } + return + } + throw 'For a fork push, set PullRequest to the target OWNER/REPO#NUMBER.' + } + + $context.Stable = ($context.TargetRepository -ieq $repository -and + $context.HeadRef -ceq $GitHubEvent.repository.default_branch) + if ($context.Stable) { + $context.BaseRef = $context.HeadRef + if ($publishing) { + $currentRepository = Invoke-ReleaseGitHubRead @readParameters -Endpoint "repos/$repository" -Resource "repository $repository" + if ($currentRepository.full_name -ine $repository -or $currentRepository.default_branch -cne $context.BaseRef) { + throw "The push branch [$($context.BaseRef)] no longer matches the repository default branch." + } + } + } + } + default { throw 'Calculate requires a pull_request or branch push event.' } +} + +if ($number -eq 0) { + $lookupOptions = @('--method', 'GET', '--paginate', '--slurp') + if ($context.Stable) { + $route = "repos/$repository/commits/$($context.CommitSha)/pulls" + $resource = 'pull requests associated with the pushed commit' + } else { + $sourceOwner = $context.SourceRepository.Split('/')[0] + $route = "repos/$repository/pulls" + $resource = 'open pull requests for the pushed branch' + $lookupOptions += @('-f', 'state=open', '-f', "head=${sourceOwner}:$($context.HeadRef)") + } + $pages = Invoke-ReleaseGitHubRead @readParameters -Endpoint $route -Resource $resource -ArgumentList $lookupOptions + if ($pages -isnot [array] -or $pages.Count -eq 0) { + throw "GitHub returned an invalid response for $resource." + } + $matchesByNumber = [Collections.Generic.HashSet[int]]::new() + foreach ($page in $pages) { + if ($page -isnot [array]) { + throw "GitHub returned an invalid page for $resource." + } + foreach ($candidate in $page) { + if ($candidate -isnot [PSCustomObject] -or [int] $candidate.number -le 0 -or + $candidate.state -cnotin @('open', 'closed') -or -not $candidate.base.repo.full_name -or -not $candidate.base.ref) { + throw "GitHub returned an invalid pull request for $resource." + } + if (Test-ReleasePullRequest -PullRequest $candidate -Context $context) { + $null = $matchesByNumber.Add($candidate.number) + } + } + } + if ($matchesByNumber.Count -gt 1) { + if ($context.Stable) { + throw 'More than one merged pull request matches this push. Set PullRequest to select the correct one.' + } + throw 'More than one open pull request matches this push. Set PullRequest to select the correct one.' + } + if ($matchesByNumber.Count -eq 1) { + $number = $matchesByNumber | Select-Object -First 1 + } elseif (-not $context.Stable) { + if ($publishing) { + if ($PlanFingerprint) { + throw 'ReleasePlan was supplied, but no open pull request matches this push. The event is not eligible for publication.' + } + return + } + throw 'No open pull request matches the source repository, branch, and exact pushed SHA.' + } +} + +$targetRepository = $context.TargetRepository +$labels = @() +$pullRequest = $null +if ($number -gt 0) { + if ($cleanupOnly) { + $pullRequest = $eventPullRequest + } else { + $pullRequestParameters = @{ + Endpoint = "repos/$targetRepository/pulls/$number" + Resource = "pull request $targetRepository#$number" + } + $pullRequest = Invoke-ReleaseGitHubRead @readParameters @pullRequestParameters + if ($pullRequest -isnot [PSCustomObject] -or $pullRequest.number -ne $number -or + -not (Test-ReleasePullRequest -PullRequest $pullRequest -Context $context)) { + throw "Pull request $targetRepository#$number no longer matches the event repository, branch, and exact commit." + } + if ($pullRequest.labels -isnot [array]) { + throw "GitHub did not return the current labels for pull request $targetRepository#$number." + } + $labels = foreach ($label in $pullRequest.labels) { + if ([string]::IsNullOrWhiteSpace($label.name)) { + throw "GitHub returned an invalid label for pull request $targetRepository#$number." + } + $label.name + } + } +} + +$decision = if ($cleanupOnly -or ($context.Stable -and -not $pullRequest)) { + if ($PlanFingerprint) { + throw 'ReleasePlan cannot publish a stable release without an exact matching merged pull request.' + } + if (-not $cleanupOnly) { + Write-Warning 'No merged pull request matches the pushed commit. No stable release will be published.' + } + [PSCustomObject]@{ + Bump = 'None' + Prerelease = $false + Skip = $true + DefaultBumpApplied = $false + BumpSource = if ($cleanupOnly) { 'pull-request-closed' } else { 'no-reviewed-pull-request' } + } +} else { + $decisionParameters = @{ + Labels = $labels + DefaultBump = $Settings.DefaultBump + DefaultBumpSource = $Settings.DefaultBumpSource + } + Resolve-ReleaseDecision @decisionParameters +} +Write-Information "Release bump source: [$($decision.BumpSource)]." -InformationAction Continue +$eligible = if ($publishing -and -not $context.Stable) { + Test-PrereleaseCreation -ReleaseDecision $decision -PullRequestClosed:$cleanupOnly +} else { + -not $decision.Skip +} +if ($PlanFingerprint -and -not $eligible) { + if ($decision.Skip) { + throw 'Do not supply ReleasePlan with release:skip.' + } + throw 'ReleasePlan cannot publish a prerelease without release:prerelease on the pull request.' +} + +$hasCalculationTime = $PSBoundParameters.ContainsKey('CalculationTime') +$usesDate = $eligible -and -not $context.Stable -and $Settings.DatePrereleaseFormat +if ($hasCalculationTime -and -not $usesDate) { + throw 'CalculatedAt applies only to a date-dependent prerelease.' +} +if ($PlanFingerprint -and $usesDate -and -not $hasCalculationTime) { + throw 'ReleasePlan is missing its calculation time. Pass the unchanged output from Calculate.' +} + +$planParameters = @{ ReleaseDecision = $decision; Settings = $Settings } +if ($eligible) { + if (-not $context.Stable) { + $pullRequestContext = Resolve-PullRequestReleaseContext -PullRequest $pullRequest + $planParameters.PrereleaseName = $pullRequestContext.PrereleaseName + } + if ($usesDate) { + $planParameters.CalculationTime = if ($hasCalculationTime) { $CalculationTime } else { Get-Date -AsUTC } + } + $owner, $name = $targetRepository.Split('/') + $query = @( + 'query($owner: String!, $name: String!) {' + 'repository(owner: $owner, name: $name) { nameWithOwner latestRelease { tagName isDraft isPrerelease } }' + '}' + ) -join ' ' + $historyParameters = @{ + Endpoint = 'graphql' + Resource = "release history for $targetRepository" + ArgumentList = @('-f', "query=$query", '-f', "owner=$owner", '-f', "name=$name") + } + $history = Invoke-ReleaseGitHubRead @readParameters @historyParameters + $repositoryHistory = $history.data.repository + if ($history.errors -or $repositoryHistory.nameWithOwner -ine $targetRepository -or + $null -eq $repositoryHistory.PSObject.Properties['latestRelease']) { + throw "GitHub returned invalid release history for $targetRepository." + } + $latest = $repositoryHistory.latestRelease + if ($null -ne $latest) { + if ($latest.isDraft -ne $false -or $latest.isPrerelease -ne $false -or [string]::IsNullOrWhiteSpace($latest.tagName)) { + throw "GitHub returned an invalid stable release in the release history for $targetRepository." + } + $planParameters.BaselineTag = $latest.tagName + } +} +$versionPlan = if ($eligible -or $decision.Skip) { Get-ReleaseVersionPlan @planParameters } +$releasePlan = if ($eligible -and (-not $publishing -or $PlanFingerprint)) { + $policy = [ordered]@{} + foreach ($setting in ($Settings.PSObject.Properties | Sort-Object -Property Name)) { + if ($setting.Name -cnotin @('Mode', 'WhatIf')) { + $policy[$setting.Name] = $setting.Value + } + } + $supportedLabels = (Get-ReleaseLabelDefinition).Name + $snapshot = [ordered]@{ + Hostname = $server.Host + Repository = $targetRepository + EventName = $eventName + RunId = $env:GITHUB_RUN_ID + Source = $context + PullRequest = $number + Labels = @($labels | Where-Object { $_ -cin $supportedLabels } | Sort-Object -CaseSensitive) + Title = $pullRequest.title + Body = $pullRequest.body + Policy = $policy + BumpSource = $decision.BumpSource + Baseline = $planParameters.BaselineTag + ReleaseVersion = $versionPlan.ReleaseVersion + CalculatedAt = $versionPlan.CalculatedAt + } + # Keep the full PR text out of job outputs, but reject publication if it changes. + $json = ConvertTo-Json -InputObject $snapshot -Depth 6 -Compress + $fingerprint = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($json))) + if ($PlanFingerprint -and $fingerprint -cne $PlanFingerprint) { + throw 'ReleasePlan does not match the current source, settings, or release inputs. Run Calculate again.' + } + "$fingerprint|$($versionPlan.CalculatedAt)" +} + +$tagExists = $false +$replacePrerelease = $false +if ($publishing -and $eligible) { + $tag = $versionPlan.TagVersion.ToString() + $tagRef = "refs/tags/$tag" + $null = git check-ref-format $tagRef + if ($LASTEXITCODE -ne 0 -or $tag.StartsWith('-', [StringComparison]::Ordinal)) { + throw "VersionPrefix produces an invalid release tag [$tag]." + } + + $encodedTag = [uri]::EscapeDataString($tag) + $tagParameters = @{ + Endpoint = "repos/$targetRepository/git/matching-refs/tags/$encodedTag" + Resource = "release tag [$tag] in $targetRepository" + } + $tagRefs = Invoke-ReleaseGitHubRead @readParameters @tagParameters + if ($tagRefs -isnot [array]) { + throw "GitHub returned an invalid response for release tag [$tag]." + } + foreach ($ref in $tagRefs) { + if ($ref.ref -isnot [string] -or -not $ref.ref.StartsWith($tagRef, [StringComparison]::Ordinal)) { + throw "GitHub returned an invalid reference for release tag [$tag]." + } + } + $exactRefs = @($tagRefs | Where-Object { $_.ref -ceq $tagRef }) + if ($exactRefs.Count -gt 0) { + $tagObject = $exactRefs[0].object + if ($exactRefs.Count -ne 1 -or $tagObject.type -cne 'commit' -or $tagObject.sha -cnotmatch $shaPattern) { + throw "Release tag [$tag] has no verifiable commit target." + } + $tagExists = $tagObject.sha -ieq $context.CommitSha + if (-not $tagExists -and ($PlanFingerprint -or $context.Stable -or $Settings.IncrementalPrerelease)) { + throw "Release tag [$tag] does not point to the validated target [$($context.CommitSha)]." + } + + $repositoryArgument = "$($server.Host)/$targetRepository" + $recordsJson = gh release list --repo $repositoryArgument --json 'isDraft,isPrerelease,tagName' + if ($LASTEXITCODE -ne 0) { + throw "Failed to read the release for tag [$tag] in $targetRepository." + } + $records = ConvertFrom-Json -InputObject ($recordsJson -join "`n") -NoEnumerate + if ($records -isnot [array]) { + throw "GitHub returned an invalid release list for $targetRepository." + } + $previousReleases = @($records | Where-Object { $_.tagName -ceq $tag }) + if ($previousReleases.Count -gt 0) { + if ($previousReleases.Count -ne 1 -or $context.Stable -or $Settings.IncrementalPrerelease -or + $previousReleases[0].isPrerelease -ne $true -or $previousReleases[0].isDraft -ne $false) { + throw "Release tag [$tag] already has a GitHub release." + } + $replacePrerelease = $true + } elseif (-not $tagExists) { + throw "Release tag [$tag] does not point to the validated target [$($context.CommitSha)]." + } + } +} + +[PSCustomObject]@{ + Decision = $versionPlan.Decision + ReleaseVersion = $versionPlan.ReleaseVersion + ReleasePlan = $releasePlan + TagVersion = $versionPlan.TagVersion + CalculatedAt = $versionPlan.CalculatedAt + ReleaseDecision = $decision + PullRequest = $pullRequest + Hostname = $server.Host + TargetRepository = $targetRepository + CommitSha = $context.CommitSha + Stable = $context.Stable + CleanupOnly = $cleanupOnly + TagExists = $tagExists + ReplacePrerelease = $replacePrerelease +} diff --git a/src/Get-ReleaseWorkflowInputs.ps1 b/src/Get-ReleaseWorkflowInputs.ps1 new file mode 100644 index 0000000..f3f0869 --- /dev/null +++ b/src/Get-ReleaseWorkflowInputs.ps1 @@ -0,0 +1,133 @@ +#Requires -Version 7.2 +#Requires -Modules powershell-yaml + +<# + .SYNOPSIS + Read the supported inputs from the local release workflow. + + .DESCRIPTION + Select the stable publisher for the target branch. Read literal policy inputs + and verify any ReleasePlan handoff without evaluating workflow expressions. + + .OUTPUTS + System.Collections.IDictionary +#> +[OutputType([System.Collections.IDictionary])] +[CmdletBinding()] +param( + # The candidate publisher workflow file. + [Parameter(Mandatory)] + [string] $Path, + + # The pull request target branch, without refs/heads/. + [Parameter(Mandatory)] + [string] $TargetBranch, + + # The settings supported by the same action that publishes. + [Parameter(Mandatory)] + [string[]] $SettingNames +) + +$ErrorActionPreference = 'Stop' +$workflow = ConvertFrom-Yaml -Yaml ([IO.File]::ReadAllText($Path)) -Ordered +$trigger = $workflow.on.push +if ($trigger -isnot [System.Collections.IDictionary]) { + throw 'The release workflow must have a supported push trigger for stable publication.' +} +foreach ($filter in $trigger.GetEnumerator()) { + if ($filter.Key -cne 'branches') { + throw "The release workflow has an unsupported push filter [$($filter.Key)]." + } +} +if ($trigger.branches -isnot [System.Collections.IList] -or + @($trigger.branches | Where-Object { $_ -isnot [string] -or $_ -match '[!+*?\[\]\\]' }).Count -gt 0) { + throw 'The release workflow has an unsupported branch filter. List the target branch names literally.' +} +if ($trigger.branches -cnotcontains $TargetBranch) { + throw "The release workflow does not handle [$TargetBranch] with an explicit push branch filter." +} + +$job = $workflow.jobs.PublishStable +if ($job -isnot [System.Collections.IDictionary]) { + throw 'The release workflow must define a PublishStable job.' +} +$publisher = @($job.steps | Where-Object { $_.uses -ceq './' }) +if ($publisher.Count -ne 1) { + throw 'The release workflow must have exactly one local action invocation in the PublishStable job.' +} +$usesPlan = $job.needs -ccontains 'Plan' +$condition = "github.event_name == 'push' && github.ref_name == github.event.repository.default_branch" +if ($usesPlan) { + $condition += " && needs.Plan.outputs.Decision == 'release'" +} +if ($job.if -isnot [string] -or ($job.if.Trim() -replace '\s+', ' ') -cnotin @($condition, ('${{ ' + $condition + ' }}'))) { + throw ('The release check cannot resolve the conditional stable publisher. ' + + 'Require a default-branch push and, when staged, a release decision from Plan.') +} +if ($publisher[0].Contains('if') -or $job.Contains('strategy')) { + throw 'The release check cannot resolve a conditional publisher step or a matrix of publisher inputs.' +} + +$checkouts = @(foreach ($step in $job.steps) { + if ([object]::ReferenceEquals($step, $publisher[0])) { + break + } + if ($step.uses -clike 'actions/checkout@*') { + $step + } + }) +if ($checkouts.Count -ne 1 -or $checkouts[0].Contains('if')) { + throw 'The release check requires one unconditional checkout before the local publisher.' +} +if ($checkouts[0].Contains('with')) { + $checkoutInputs = $checkouts[0].with + if ($checkoutInputs -isnot [System.Collections.IDictionary]) { + throw 'The publisher checkout with block must contain a mapping.' + } + if ($checkoutInputs.Contains('repository') -and + ($checkoutInputs.repository -isnot [string] -or $checkoutInputs.repository -cne '${{ github.repository }}')) { + throw 'The publisher checkout must use the current repository.' + } + if (($checkoutInputs.Contains('path') -and $checkoutInputs.path -cnotin @('.', './')) -or $checkoutInputs.Contains('sparse-checkout')) { + throw 'The publisher checkout must use the workspace root without a sparse checkout.' + } + if ($checkoutInputs.Contains('ref') -and + ($checkoutInputs.ref -isnot [string] -or $checkoutInputs.ref -cne '${{ github.sha }}')) { + throw 'The publisher checkout ref must be the exact pushed commit.' + } +} + +$inputs = @{} +$overrides = if ($publisher[0].Contains('with')) { $publisher[0].with } else { @{} } +if ($overrides -isnot [System.Collections.IDictionary]) { + throw 'The publisher with block must contain a mapping of inputs.' +} +if ($usesPlan -and -not $overrides.Contains('ReleasePlan')) { + throw 'The staged publisher must take ReleasePlan from the Plan job.' +} +foreach ($override in $overrides.GetEnumerator()) { + $key = $override.Key + $value = $override.Value + if ($key -ceq 'ReleasePlan') { + if (-not $usesPlan -or $value -cne '${{ needs.Plan.outputs.ReleasePlan }}') { + throw 'The staged publisher must take ReleasePlan from the Plan job.' + } + continue + } + $name = @($SettingNames + 'SettingsFilePath').Where({ $_ -eq $key }, 'First')[0] + if (-not $name) { + throw "The publisher has an unsupported workflow input [$key]." + } + if ($inputs.ContainsKey($name)) { + throw "The publisher specifies workflow input [$name] more than once." + } + + if ($value -is [bool]) { + $inputs[$name] = $value.ToString().ToLowerInvariant() + } elseif ($value -is [string] -and -not $value.Contains('${{')) { + $inputs[$name] = $value + } else { + throw "Use a literal string or Boolean for publisher input [$name]." + } +} +$inputs diff --git a/src/Initialize-ReleaseConfiguration.ps1 b/src/Initialize-ReleaseConfiguration.ps1 new file mode 100644 index 0000000..a312f63 --- /dev/null +++ b/src/Initialize-ReleaseConfiguration.ps1 @@ -0,0 +1,184 @@ +#Requires -Version 7.2 + +<# + .SYNOPSIS + Resolve action settings before GitHub-Script starts. + + .DESCRIPTION + Select the repository settings file from the explicitly supplied initial + directory or the workspace. Read the selected file once, then resolve all + settings and write the private startup and release-policy handoff. + + .EXAMPLE + .\Initialize-ReleaseConfiguration.ps1 -WorkspacePath $workspace + + Return the resolved settings. In Actions, also write the step outputs. + + .INPUTS + None + + You can't pipe objects to Initialize-ReleaseConfiguration.ps1. + + .OUTPUTS + System.Management.Automation.PSCustomObject + + The resolved startup and release settings. +#> +[OutputType([PSCustomObject])] +[CmdletBinding()] +param( + # The known caller workspace, independent of the current directory. + [Parameter()] + [string] $WorkspacePath = [Environment]::GetEnvironmentVariable('GITHUB_WORKSPACE'), + + # The runner's output file; local callers can omit it to return settings only. + [Parameter()] + [string] $OutputPath = [Environment]::GetEnvironmentVariable('GITHUB_OUTPUT'), + + # Evaluate this branch's publisher inputs instead of the check's own inputs. + [Parameter()] + [string] $PublisherBranch +) + +$ErrorActionPreference = 'Stop' +$checkPublisher = $PSBoundParameters.ContainsKey('PublisherBranch') + +Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath 'Release-GHRepository.Helpers.psm1') -Force +if ([string]::IsNullOrWhiteSpace($WorkspacePath) -or -not [IO.Path]::IsPathRooted($WorkspacePath) -or + -not (Test-Path -LiteralPath $WorkspacePath -PathType Container)) { + throw 'GITHUB_WORKSPACE must identify an existing absolute workspace directory.' +} +$WorkspacePath = [IO.Path]::GetFullPath($WorkspacePath) + +if (-not (Get-Module -ListAvailable -Name powershell-yaml)) { + for ($attempt = 1; $attempt -le 5; $attempt++) { + try { + Install-PSResource -Name powershell-yaml -TrustRepository -Repository PSGallery -WarningAction SilentlyContinue + break + } catch { + $installationError = $_ + Write-Warning "Installation of powershell-yaml failed: $installationError" + if ($attempt -eq 5) { + throw $installationError + } + Start-Sleep -Seconds 10 + } + } +} +Import-Module -Name powershell-yaml + +Write-Information '::group::Resolve release settings' -InformationAction Continue +try { + $actionDefinitionPath = [IO.Path]::GetFullPath((Join-Path -Path $PSScriptRoot -ChildPath '..\action.yml')) + $metadata = Get-ReleaseSettingSchema -Path $actionDefinitionPath + Write-Information "Reading action release standards [$actionDefinitionPath]" -InformationAction Continue + if ($checkPublisher) { + $publisherParameters = @{ + Path = Join-Path -Path $WorkspacePath -ChildPath '.github\workflows\Release.yml' + TargetBranch = $PublisherBranch + SettingNames = @($metadata.Keys) + } + $publisherReader = Join-Path -Path $PSScriptRoot -ChildPath 'Get-ReleaseWorkflowInputs.ps1' + $inputs = & $publisherReader @publisherParameters + $settingsFilePath = $inputs.SettingsFilePath + } else { + $inputs = @{} + foreach ($name in $metadata.Keys) { + $inputs[$name] = [Environment]::GetEnvironmentVariable("PSMODULE_AUTO_RELEASE_INPUT_$name") + } + $settingsFilePath = [Environment]::GetEnvironmentVariable('PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath') + } + $explicitPublisherFile = $checkPublisher -and $inputs.ContainsKey('SettingsFilePath') + if ($explicitPublisherFile) { + $inputs.Remove('SettingsFilePath') + } + + $initialDirectory = $WorkspacePath + if (-not [string]::IsNullOrEmpty($inputs.WorkingDirectory)) { + $initialParameters = @{ + Name = 'WorkingDirectory' + Type = $metadata.WorkingDirectory.Type + Value = $inputs.WorkingDirectory + WorkspacePath = $WorkspacePath + } + $initialDirectory = ConvertTo-ReleaseSettingValue @initialParameters + } + if ($null -eq $settingsFilePath) { + $actionDefinition = ConvertFrom-Yaml -Yaml ([IO.File]::ReadAllText($actionDefinitionPath)) + $settingsFilePath = $actionDefinition.inputs.SettingsFilePath.default + } + $pathParameters = @{ + Name = 'SettingsFilePath' + Path = $settingsFilePath + BaseDirectory = $initialDirectory + } + $settingsFilePath = Resolve-ReleaseFileSystemPath @pathParameters + if ($checkPublisher) { + $relativePath = [IO.Path]::GetRelativePath($WorkspacePath, $settingsFilePath) + if ([IO.Path]::IsPathRooted($relativePath) -or $relativePath -match '\A\.\.(?:[\\/]|$)') { + throw 'The publisher SettingsFilePath must be inside the candidate checkout.' + } + } + if (Test-Path -LiteralPath $settingsFilePath -PathType Container) { + throw 'SettingsFilePath must select a file, not a directory.' + } + $loggedPath = ConvertTo-Json -InputObject $settingsFilePath -Compress + $configuration = @{} + if (Test-Path -LiteralPath $settingsFilePath -PathType Leaf) { + Write-Information "Reading settings file [$loggedPath]" -InformationAction Continue + $configuration = ConvertFrom-Yaml -Yaml ([IO.File]::ReadAllText($settingsFilePath)) + if ($null -eq $configuration) { + throw "Release settings file [$loggedPath] must be a mapping of supported settings." + } + } elseif ($explicitPublisherFile) { + throw "The publisher settings file [$loggedPath] was not found in the candidate checkout." + } else { + Write-Information "Settings file not found at [$loggedPath]" -InformationAction Continue + } + + $configurationParameters = @{ + Metadata = $metadata + WorkspacePath = $WorkspacePath + Inputs = $inputs + Configuration = $configuration + } + $settings = Resolve-ReleaseConfiguration @configurationParameters + if ($checkPublisher) { + if ($settings.Mode -cne 'publish') { + throw 'The effective publisher Mode must be publish.' + } + $settings.Mode = 'calculate' + } + $outputs = [ordered]@{} + $releaseSettings = [ordered]@{} + foreach ($name in $metadata.Keys) { + if ($metadata[$name].Phase -eq 'Startup') { + $value = $settings.$name + if ($value -is [bool]) { + $value = $value.ToString().ToLowerInvariant() + } + $outputs[$name] = $value + } else { + $releaseSettings[$name] = $settings.$name + } + } + $releaseSettings.DefaultBumpSource = $settings.DefaultBumpSource + $outputs.ReleaseSettings = ConvertTo-Json -InputObject $releaseSettings -Compress + Write-Information ("Resolved startup settings: {0}" -f (ConvertTo-Json -InputObject $outputs -Compress)) -InformationAction Continue + + if (-not [string]::IsNullOrEmpty($OutputPath)) { + $outputParameters = @{ + Name = 'GITHUB_OUTPUT' + Path = $OutputPath + BaseDirectory = $WorkspacePath + } + $outputFilePath = Resolve-ReleaseFileSystemPath @outputParameters + foreach ($name in $outputs.Keys) { + $delimiter = [guid]::NewGuid().ToString('N') + [IO.File]::AppendAllText($outputFilePath, "$name<<$delimiter`n$($outputs[$name])`n$delimiter`n") + } + } + $settings +} finally { + Write-Information '::endgroup::' -InformationAction Continue +} diff --git a/src/Release-GHRepository.Helpers.psm1 b/src/Release-GHRepository.Helpers.psm1 new file mode 100644 index 0000000..e23357b --- /dev/null +++ b/src/Release-GHRepository.Helpers.psm1 @@ -0,0 +1,884 @@ +$ErrorActionPreference = 'Stop' + +$resourceGetModule = Import-Module -Name Microsoft.PowerShell.PSResourceGet -PassThru +$versioningPath = Join-Path -Path $resourceGetModule.ModuleBase -ChildPath 'dependencies\NuGet.Versioning.dll' +$script:versionRangeType = [Reflection.Assembly]::LoadFrom($versioningPath).GetType('NuGet.Versioning.VersionRange', $true) + +function Get-ReleaseSettingSchema { + <# + .SYNOPSIS + Read the private setting schema from the action's own metadata. + + .DESCRIPTION + Require one complete schema for the named settings. Keep the file + selector separate from the setting types, standards, and destinations. + + .EXAMPLE + Get-ReleaseSettingSchema -Path $actionPath + + Return the action's validated setting definitions. + + .INPUTS + None + + You can't pipe objects to Get-ReleaseSettingSchema. + + .OUTPUTS + System.Collections.IDictionary + + The private setting definitions. + #> + [OutputType([System.Collections.IDictionary])] + [CmdletBinding()] + param( + # The full path to the action's own metadata. + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $Path + ) + + $actionDefinition = ConvertFrom-Yaml -Yaml ([IO.File]::ReadAllText($Path)) + $metadataYaml = $actionDefinition.runs.steps[0].env.PSMODULE_AUTO_RELEASE_SETTING_METADATA + if ($metadataYaml -isnot [string] -or [string]::IsNullOrWhiteSpace($metadataYaml)) { + throw 'The action release standards must be a nonempty YAML mapping.' + } + $metadata = ConvertFrom-Yaml -Yaml $metadataYaml -Ordered + if ($metadata -isnot [System.Collections.IDictionary]) { + throw 'The action release standards must be a mapping of setting definitions.' + } + $validTypes = @('Boolean', 'Text', 'Bump', 'DateTimeFormat', 'VersionConstraint', 'DirectoryPath', 'ReleaseMode', 'PullRequestSelector') + $runtimeInputs = @('SettingsFilePath', 'ReleasePlan') + $settingNames = @($actionDefinition.inputs.Keys | Where-Object { $_ -notin $runtimeInputs }) + foreach ($name in $settingNames) { + if ($metadata.Keys -notcontains $name) { + throw "Release standard defaults are missing required setting [$name]." + } + } + foreach ($name in $metadata.Keys) { + if ($settingNames -notcontains $name) { + throw "Unsupported release setting [$name] in the action metadata." + } + $definition = $metadata[$name] + if ($definition -isnot [System.Collections.IDictionary] -or + $definition.Keys -notcontains 'Default' -or $definition.Keys -notcontains 'Type' -or + $definition.Keys -notcontains 'Phase' -or $definition.Count -ne 3) { + throw "Invalid metadata for release setting [$name]. Supply Type, Default, and Phase." + } + if ($validTypes -cnotcontains $definition.Type) { + throw "Invalid metadata type for release setting [$name]." + } + if (@('Startup', 'Release') -cnotcontains $definition.Phase) { + throw "Invalid metadata phase for release setting [$name]. Use Startup or Release." + } + } + $metadata +} + +function Resolve-ReleaseFileSystemPath { + <# + .SYNOPSIS + Resolve a literal file-system path from a known directory. + + .DESCRIPTION + Resolve relative paths without using the process's current directory. + Reject non-file-system providers and invalid path characters. + + .EXAMPLE + Resolve-ReleaseFileSystemPath -Name 'SettingsFilePath' -Path '.github\auto-release.yml' -BaseDirectory $workspace + + Return the selected absolute file-system path. + + .INPUTS + None + + You can't pipe objects to Resolve-ReleaseFileSystemPath. + + .OUTPUTS + System.String + + The absolute literal path. + #> + [OutputType([string])] + [CmdletBinding()] + param( + # The setting name used in path diagnostics. + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $Name, + + # The literal path to resolve. + [Parameter(Mandatory)] + [AllowEmptyString()] + [string] $Path, + + # The absolute directory for relative paths. + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $BaseDirectory + ) + + if ([string]::IsNullOrWhiteSpace($Path)) { + throw "$Name must be a nonempty path." + } + $candidate = $Path + if (-not [IO.Path]::IsPathRooted($Path) -and $Path -notmatch '\A[^\\/]+:') { + $candidate = Join-Path -Path $BaseDirectory -ChildPath $Path + } + $provider = $null + $drive = $null + $fullPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath( + $candidate, [ref] $provider, [ref] $drive + ) + if ($provider.Name -ne 'FileSystem') { + throw "$Name must use a FileSystem path." + } + $fullPath = [IO.Path]::GetFullPath($fullPath) + $relativePart = $fullPath.Substring([IO.Path]::GetPathRoot($fullPath).Length) + foreach ($part in $relativePart -split '[\\/]') { + if ($part.IndexOfAny([IO.Path]::GetInvalidFileNameChars()) -ge 0) { + throw "$Name must use a valid FileSystem path." + } + } + $fullPath +} + +function ConvertTo-ReleaseSettingValue { + <# + .SYNOPSIS + Validate and convert one supplied release-setting value. + + .DESCRIPTION + Use the private schema type to validate text, booleans, bumps, date + formats, dependency versions, and execution directories. + + .EXAMPLE + ConvertTo-ReleaseSettingValue -Name 'AutoCleanup' -Type Boolean -Value 'false' -WorkspacePath $workspace + + Return the Boolean false value. + + .INPUTS + None + + You can't pipe objects to ConvertTo-ReleaseSettingValue. + + .OUTPUTS + System.Boolean + + A validated Boolean setting. + + .OUTPUTS + System.String + + A validated text setting. + #> + [OutputType([bool], [string])] + [CmdletBinding()] + param( + # The supported release-setting name. + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $Name, + + # The type supplied by the action's private schema. + [Parameter(Mandatory)] + [ValidateSet('Boolean', 'Text', 'Bump', 'DateTimeFormat', 'VersionConstraint', 'DirectoryPath', 'ReleaseMode', 'PullRequestSelector')] + [string] $Type, + + # The supplied value, including null so invalid values can be diagnosed. + [Parameter(Mandatory)] + [AllowNull()] + [AllowEmptyString()] + [object] $Value, + + # The known workspace for relative execution-directory values. + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $WorkspacePath + ) + + if ($Type -eq 'Boolean') { + if ($Value -is [bool]) { + $Value + } elseif ($Value -is [string] -and @('true', 'false') -contains $Value) { + $Value -eq 'true' + } else { + throw "Invalid release setting [$Name]. Use true or false." + } + return + } + if ($Value -isnot [string]) { + throw "Invalid release setting [$Name]. Use a string value." + } + if ($Type -eq 'Bump') { + $null = ConvertTo-ReleaseBump -DefaultBump $Value + } + if ($Type -eq 'ReleaseMode' -and $Value -cnotin @('publish', 'calculate')) { + throw 'Invalid Mode. Use exactly publish or calculate.' + } + if ($Type -eq 'PullRequestSelector' -and $Value) { + $selectorPattern = '\A[A-Za-z0-9][A-Za-z0-9-]*/(?!\.{1,2}#)[A-Za-z0-9_.-]+#(?[1-9][0-9]*)\z' + $number = 0 + if ($Value -cnotmatch $selectorPattern -or -not [int]::TryParse($Matches.Number, [ref] $number)) { + throw 'Invalid PullRequest. Use OWNER/REPO#NUMBER with a positive pull request number.' + } + } + if ($Type -eq 'DateTimeFormat' -and -not [string]::IsNullOrEmpty($Value)) { + try { + $null = [datetime]::new(2000, 1, 1).ToString($Value, [Globalization.CultureInfo]::InvariantCulture) + } catch [FormatException] { + throw 'Invalid DatePrereleaseFormat. Use a valid .NET date and time format string.' + } + } + if ($Type -eq 'VersionConstraint' -and -not [string]::IsNullOrEmpty($Value)) { + $versionRange = $null + if (-not $script:versionRangeType::TryParse($Value, [ref] $versionRange)) { + throw "Invalid release setting [$Name]. Use an exact dependency version or a NuGet version range." + } + } + if ($Type -eq 'DirectoryPath') { + $pathParameters = @{ + Name = $Name + Path = $Value + BaseDirectory = $WorkspacePath + } + $Value = Resolve-ReleaseFileSystemPath @pathParameters + if (-not (Test-Path -LiteralPath $Value -PathType Container)) { + throw "Invalid release setting [$Name]. Use an existing directory." + } + } + $Value +} + +function Resolve-ReleaseConfiguration { + <# + .SYNOPSIS + Resolve validated release settings from action standards and inputs. + + .DESCRIPTION + Apply repository settings over the private schema standards, then + nonempty named action inputs. Validate every supplied layer so invalid + values cannot be masked. Preserve explicit false and file empty text + values, and record the effective default-bump source. + + .EXAMPLE + $parameters = @{ + Metadata = $settingMetadata + WorkspacePath = $workspace + Configuration = @{ DefaultBump = 'major' } + Inputs = @{ DefaultBump = 'minor' } + } + Resolve-ReleaseConfiguration @parameters + + Return the effective release settings with DefaultBump set to minor. + + .INPUTS + None + + You can't pipe objects to Resolve-ReleaseConfiguration. + + .OUTPUTS + System.Management.Automation.PSCustomObject + + The validated effective release settings. + #> + [OutputType([PSCustomObject])] + [CmdletBinding()] + param( + # Types and standards parsed from the action's private metadata declaration. + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Metadata, + + # The known workspace for all relative WorkingDirectory values. + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $WorkspacePath, + + # Named runtime inputs; null and empty strings do not override file policy. + [Parameter()] + [AllowNull()] + [System.Collections.IDictionary] $Inputs, + + # The parsed configuration file, which must be a mapping when supplied. + [Parameter()] + [AllowNull()] + [object] $Configuration + ) + + if ($null -ne $Configuration -and $Configuration -isnot [System.Collections.IDictionary]) { + throw 'Release configuration must be a mapping of supported settings.' + } + $defaults = [ordered]@{} + foreach ($name in $Metadata.Keys) { + $defaults[$name] = $Metadata[$name].Default + } + $retiredSettings = @('AutoPatching', 'IgnoreLabels', 'MajorLabels', 'MinorLabels', 'PatchLabels') + $layers = @( + [PSCustomObject]@{ Source = 'SharedDefault'; Values = $defaults } + [PSCustomObject]@{ Source = 'RepositorySetting'; Values = $Configuration } + [PSCustomObject]@{ Source = 'ActionInput'; Values = $Inputs } + ) + $settings = [ordered]@{} + $defaultBumpSource = 'SharedDefault' + foreach ($layer in $layers) { + if ($null -eq $layer.Values) { + continue + } + foreach ($name in $layer.Values.Keys) { + if ($retiredSettings -contains $name) { + throw "Release setting [$name] was removed. Use DefaultBump and the release: labels defined by this action." + } + if ($Metadata.Keys -notcontains $name) { + throw "Unsupported release setting [$name]. Use the documented release settings." + } + $value = $layer.Values[$name] + $isEmpty = $null -eq $value -or ($value -is [string] -and $value.Length -eq 0) + if ($layer.Source -eq 'ActionInput' -and $isEmpty) { + continue + } + $valueParameters = @{ + Name = $name + Type = $Metadata[$name].Type + Value = $value + WorkspacePath = $WorkspacePath + } + $settings[$name] = ConvertTo-ReleaseSettingValue @valueParameters + if ($name -eq 'DefaultBump') { + $defaultBumpSource = $layer.Source + } + } + } + + $null = ConvertTo-ReleaseBump -DefaultBump $settings.DefaultBump + $settings.DefaultBumpSource = $defaultBumpSource + [PSCustomObject] $settings +} + +function Get-ReleaseLabelDefinition { + <# + .SYNOPSIS + Return the namespaced release labels that Release-GHRepository manages. + + .DESCRIPTION + Return the name, color, and description for each supported release label. + + .EXAMPLE + Get-ReleaseLabelDefinition + + Return all canonical release-label definitions. + + .INPUTS + None + + You can't pipe objects to Get-ReleaseLabelDefinition. + + .OUTPUTS + System.Management.Automation.PSCustomObject + + A canonical release-label definition. + #> + [OutputType([PSCustomObject])] + [CmdletBinding()] + param() + + [PSCustomObject]@{ + Name = 'release:patch' + Color = '5ac3a5' + Description = 'Publish a patch release.' + } + [PSCustomObject]@{ + Name = 'release:minor' + Color = '616f09' + Description = 'Publish a minor release.' + } + [PSCustomObject]@{ + Name = 'release:major' + Color = 'b60205' + Description = 'Publish a major release.' + } + [PSCustomObject]@{ + Name = 'release:prerelease' + Color = '8d7bdf' + Description = 'Publish a prerelease from this open pull request.' + } + [PSCustomObject]@{ + Name = 'release:skip' + Color = 'ededed' + Description = 'Validate this change without publishing a release.' + } +} + +function Get-PrereleaseCleanupCandidate { + <# + .SYNOPSIS + Return prereleases that belong to a pull-request prerelease identifier. + + .DESCRIPTION + Select only releases marked as prereleases whose effective prefix is + followed by a valid version core and the exact case-sensitive identifier. + Retain releases under other historical prefixes. The identifier must + end the tag or be followed by a dot; later hyphens never select it. + + .EXAMPLE + Get-PrereleaseCleanupCandidate -Releases $releases -PrereleaseName 'feature123' -VersionPrefix 'v' + + Return prereleases tagged with -feature123 or -feature123.. + + .INPUTS + None + + You can't pipe objects to Get-PrereleaseCleanupCandidate. + + .OUTPUTS + System.Management.Automation.PSCustomObject + + A prerelease that belongs to the requested identifier. + #> + [OutputType([PSCustomObject])] + [CmdletBinding()] + param( + # The GitHub release records to inspect. + [Parameter(Mandatory)] + [AllowEmptyCollection()] + [AllowNull()] + [PSCustomObject[]] $Releases, + + # The normalized pull-request prerelease identifier. + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $PrereleaseName, + + # The effective prefix that locates the actual version boundary. + [Parameter(Mandatory)] + [AllowEmptyString()] + [string] $VersionPrefix + ) + + $escapedPrereleaseName = [regex]::Escape($PrereleaseName) + $identifierPattern = "\A$escapedPrereleaseName(?:\.|\z)" + $versionPattern = '\A(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)-' + + $Releases | Where-Object { + if ($_.isPrerelease -ne $true) { + return $false + } + $tagName = [string] $_.tagName + if (-not $tagName.StartsWith($VersionPrefix, [StringComparison]::Ordinal)) { + return $false + } + $versionTag = $tagName.Substring($VersionPrefix.Length) + $separator = [regex]::Match($versionTag, $versionPattern) + if (-not $separator.Success) { + return $false + } + $identifier = $versionTag.Substring($separator.Length) + $identifier -cmatch $identifierPattern + } +} + +function ConvertTo-ReleaseBump { + <# + .SYNOPSIS + Convert a configured default bump into the internal release-bump value. + + .DESCRIPTION + Validate DefaultBump with case-sensitive matching and return the + corresponding internal None, Patch, Minor, or Major value. Require the + configured value rather than choosing a policy default. + + .EXAMPLE + ConvertTo-ReleaseBump -DefaultBump 'minor' + + Return Minor. + + .INPUTS + None + + You can't pipe objects to ConvertTo-ReleaseBump. + + .OUTPUTS + System.String + + The validated internal release-bump value. + #> + [OutputType([string])] + [CmdletBinding()] + param( + # The validated effective bump supplied by the settings resolver. + [Parameter()] + [AllowNull()] + [AllowEmptyString()] + [string] $DefaultBump + ) + + $validDefaultBumps = @('none', 'patch', 'minor', 'major') + if ($validDefaultBumps -cnotcontains $DefaultBump) { + throw "Invalid DefaultBump [$DefaultBump]. Use exactly one of: none, patch, minor, major." + } + + switch -CaseSensitive ($DefaultBump) { + 'none' { 'None' } + 'patch' { 'Patch' } + 'minor' { 'Minor' } + 'major' { 'Major' } + } +} + +function Resolve-ReleaseDecision { + <# + .SYNOPSIS + Resolve a release decision from canonical pull-request labels. + + .DESCRIPTION + Evaluate only the five namespaced release labels that the action defines. + An explicit bump label overrides DefaultBump. The release:prerelease label + selects prerelease mode. The release:skip label prevents publication. + Reject conflicting release labels. If DefaultBump is none, require + a bump label or release:skip. + + .EXAMPLE + Resolve-ReleaseDecision -Labels @('release:minor') -DefaultBump 'major' + + Return a Minor stable-release decision. + + .EXAMPLE + Resolve-ReleaseDecision -Labels @('release:patch', 'release:prerelease') -DefaultBump 'minor' + + Return a Patch prerelease decision. + + .EXAMPLE + Resolve-ReleaseDecision -Labels @() -DefaultBump 'minor' + + Return a Minor stable-release decision from the configured default. + + .INPUTS + None + + You can't pipe objects to Resolve-ReleaseDecision. + + .OUTPUTS + System.Management.Automation.PSCustomObject + + The validated release decision. + #> + [OutputType([PSCustomObject])] + [CmdletBinding()] + param( + # All labels currently applied to the pull request. + [Parameter(Mandatory)] + [AllowEmptyCollection()] + [AllowNull()] + [string[]] $Labels, + + # The validated effective bump supplied by the settings resolver. + [Parameter()] + [AllowNull()] + [AllowEmptyString()] + [string] $DefaultBump, + + # The validated settings layer that supplies the effective default. + [Parameter()] + [ValidateSet('SharedDefault', 'ActionInput', 'RepositorySetting')] + [string] $DefaultBumpSource = 'SharedDefault' + ) + + $resolvedDefaultBump = ConvertTo-ReleaseBump -DefaultBump $DefaultBump + $bumpLabelTypes = [ordered]@{ + 'release:patch' = 'Patch' + 'release:minor' = 'Minor' + 'release:major' = 'Major' + } + $supportedLabelNames = @($bumpLabelTypes.Keys) + @('release:prerelease', 'release:skip') + $appliedReleaseLabels = [System.Collections.Generic.HashSet[string]]::new( + [System.StringComparer]::Ordinal + ) + + foreach ($label in $Labels) { + if ($supportedLabelNames -ccontains $label) { + $null = $appliedReleaseLabels.Add($label) + } + } + + $hasSkip = $appliedReleaseLabels.Contains('release:skip') + $hasPrerelease = $appliedReleaseLabels.Contains('release:prerelease') + $bumpLabels = @($bumpLabelTypes.Keys | Where-Object { $appliedReleaseLabels.Contains($_) }) + + if ($hasSkip) { + if ($appliedReleaseLabels.Count -ne 1) { + throw 'Invalid release labels: release:skip must not be combined with another release label.' + } + + [PSCustomObject]@{ + Bump = 'None' + Prerelease = $false + Skip = $true + DefaultBumpApplied = $false + BumpSource = 'release:skip' + } + return + } + + if ($bumpLabels.Count -gt 1) { + throw "Conflicting release bump labels: [$($bumpLabels -join ', ')]. Apply exactly one bump label." + } + + $defaultBumpApplied = $bumpLabels.Count -eq 0 + if ($defaultBumpApplied -and $resolvedDefaultBump -eq 'None') { + throw 'No release bump. Apply one of release:patch, release:minor, or release:major, set DefaultBump, or use release:skip.' + } + + $bump = if ($defaultBumpApplied) { + $resolvedDefaultBump + } else { + $bumpLabelTypes[$bumpLabels[0]] + } + + [PSCustomObject]@{ + Bump = $bump + Prerelease = $hasPrerelease + Skip = $false + DefaultBumpApplied = $defaultBumpApplied + BumpSource = if ($defaultBumpApplied) { $DefaultBumpSource } else { $bumpLabels[0] } + } +} + +function Resolve-PullRequestReleaseContext { + <# + .SYNOPSIS + Resolve branch-derived naming and the immutable target for a pull request. + + .DESCRIPTION + Keep the pull-request head branch for prerelease naming while selecting + the exact head commit SHA as the release target. + + .EXAMPLE + $pullRequest = [PSCustomObject]@{ + head = [PSCustomObject]@{ + ref = 'feature/example' + sha = '0123456789012345678901234567890123456789' + } + } + Resolve-PullRequestReleaseContext -PullRequest $pullRequest + + Return a prerelease name of featureexample and the supplied commit SHA as + the prerelease target. + + .INPUTS + None + + You can't pipe objects to Resolve-PullRequestReleaseContext. + + .OUTPUTS + System.Management.Automation.PSCustomObject + + The validated pull-request release context. + #> + [OutputType([PSCustomObject])] + [CmdletBinding()] + param( + # The pull request from the GitHub event payload. + [Parameter(Mandatory)] + [PSCustomObject] $PullRequest, + + # Permit non-prerelease contexts whose branch cannot name a prerelease. + [Parameter()] + [switch] $AllowEmptyPrereleaseName + ) + + $headRef = [string] $PullRequest.head.ref + $headSha = [string] $PullRequest.head.sha + + if ([string]::IsNullOrWhiteSpace($headRef)) { + throw 'Pull request head ref is required.' + } + if ([string]::IsNullOrWhiteSpace($headSha)) { + throw 'Pull request head SHA is required.' + } + if ($headSha -notmatch '\A[0-9a-fA-F]{40}\z') { + throw 'Pull request head SHA must be a 40-character hexadecimal commit.' + } + + $prereleaseName = $headRef -replace '[^a-zA-Z0-9]' + if ([string]::IsNullOrWhiteSpace($prereleaseName) -and -not $AllowEmptyPrereleaseName) { + throw "Pull request head ref [$headRef] does not contain a valid prerelease identifier." + } + + [PSCustomObject]@{ + HeadRef = $headRef + PrereleaseName = $prereleaseName + PrereleaseTarget = $headSha + } +} + +function Test-PrereleaseCreation { + <# + .SYNOPSIS + Test whether the current pull-request event may create a prerelease. + + .DESCRIPTION + Return true only when a validated release decision requests a prerelease + and the pull request remains open. + + .EXAMPLE + $decision = Resolve-ReleaseDecision -Labels @('release:patch', 'release:prerelease') -DefaultBump 'minor' + Test-PrereleaseCreation -ReleaseDecision $decision + + Return true for an open pull request carrying a valid prerelease decision. + + .EXAMPLE + $decision = Resolve-ReleaseDecision -Labels @('release:patch', 'release:prerelease') -DefaultBump 'minor' + Test-PrereleaseCreation -ReleaseDecision $decision -PullRequestClosed + + Return false after the pull request closes. + + .INPUTS + None + + You can't pipe objects to Test-PrereleaseCreation. + + .OUTPUTS + System.Boolean + + Whether the event may create a prerelease. + #> + [OutputType([bool])] + [CmdletBinding()] + param( + # The validated canonical release decision. + [Parameter(Mandatory)] + [PSCustomObject] $ReleaseDecision, + + # Indicate that the pull request is closed, whether merged or abandoned. + [Parameter()] + [switch] $PullRequestClosed + ) + + $ReleaseDecision.Prerelease -and -not $ReleaseDecision.Skip -and -not $PullRequestClosed +} + +function Get-ReleaseVersionPlan { + <# + .SYNOPSIS + Calculate a release version without changing repository state. + + .DESCRIPTION + Apply the resolved bump to the stable baseline, or to 0.0.0 when + there is no baseline. Use the same version rules for publication and + calculation. Return a skip decision without a version. + + .EXAMPLE + Get-ReleaseVersionPlan -ReleaseDecision $decision -Settings $settings -BaselineTag 'v2.0.3' + + Return the unprefixed version and the version object for its tag. + + .INPUTS + None + + You can't pipe objects to Get-ReleaseVersionPlan. + + .OUTPUTS + System.Management.Automation.PSCustomObject + + The decision, unprefixed version, tag version, and applicable UTC instant. + #> + [OutputType([PSCustomObject])] + [CmdletBinding()] + param( + # The validated release decision, including the bump or skip. + [Parameter(Mandatory)] + [PSCustomObject] $ReleaseDecision, + + # The resolved settings for version prefixes and prerelease suffixes. + [Parameter(Mandatory)] + [PSCustomObject] $Settings, + + # The latest stable release tag. Omit it only when no stable release exists. + [Parameter()] + [AllowEmptyString()] + [string] $BaselineTag = '', + + # The normalized branch identifier. Omit it to calculate a stable version. + [Parameter()] + [AllowEmptyString()] + [string] $PrereleaseName = '', + + # The instant to use for date-dependent prereleases. + [Parameter()] + [datetime] $CalculationTime = [datetime]::UtcNow + ) + + if ($ReleaseDecision.Skip) { + [PSCustomObject]@{ Decision = 'skip'; ReleaseVersion = $null; TagVersion = $null; CalculatedAt = $null } + return + } + + $baseline = $BaselineTag + $versionPrefix = [string] $Settings.VersionPrefix + if ($baseline) { + $baselineCandidates = @( + if ($versionPrefix -and $BaselineTag.StartsWith($versionPrefix, [StringComparison]::Ordinal)) { + $BaselineTag.Substring($versionPrefix.Length) + } + $BaselineTag -creplace '\A[A-Za-z]+' + ) + $baseline = $null + foreach ($candidate in $baselineCandidates) { + $parsed = $null + if ([semver]::TryParse($candidate, [ref] $parsed) -and -not $parsed.PrereleaseLabel -and + $parsed.ToString() -ceq $candidate) { + $baseline = $candidate + break + } + } + if ($null -eq $baseline) { + throw "Invalid release baseline [$BaselineTag]. Use a stable SemVer release tag." + } + } + $version = New-PSSemVer -Version $baseline + $version.Prefix = $versionPrefix + switch ($ReleaseDecision.Bump) { + 'Major' { $version.BumpMajor() } + 'Minor' { $version.BumpMinor() } + 'Patch' { $version.BumpPatch() } + default { throw "Cannot calculate a version for release bump [$($ReleaseDecision.Bump)]." } + } + + $calculatedAt = $null + if ($PrereleaseName) { + $version.Prerelease = $PrereleaseName + if ($Settings.DatePrereleaseFormat) { + $CalculationTime = $CalculationTime.ToUniversalTime() + $date = $CalculationTime.ToString($Settings.DatePrereleaseFormat, [cultureinfo]::InvariantCulture) + $version.Prerelease += ".$date" + $calculatedAt = $CalculationTime.ToString('o', [cultureinfo]::InvariantCulture) + } + if ($Settings.IncrementalPrerelease) { + $version.BumpPrereleaseNumber() + } + } + + $releaseVersion = $version.ToString().Substring($versionPrefix.Length) + $parsed = $null + if (-not [semver]::TryParse($releaseVersion, [ref] $parsed) -or $parsed.ToString() -cne $releaseVersion) { + throw "The calculated version [$releaseVersion] is not valid SemVer." + } + [PSCustomObject]@{ + Decision = 'release' + ReleaseVersion = $releaseVersion + TagVersion = $version + CalculatedAt = $calculatedAt + } +} + +Export-ModuleMember -Function @( + 'ConvertTo-ReleaseBump' + 'ConvertTo-ReleaseSettingValue' + 'Get-PrereleaseCleanupCandidate' + 'Get-ReleaseLabelDefinition' + 'Get-ReleaseSettingSchema' + 'Get-ReleaseVersionPlan' + 'Resolve-ReleaseDecision' + 'Resolve-ReleaseConfiguration' + 'Resolve-ReleaseFileSystemPath' + 'Resolve-PullRequestReleaseContext' + 'Test-PrereleaseCreation' +) diff --git a/src/Test-ReleaseDecisionContext.ps1 b/src/Test-ReleaseDecisionContext.ps1 new file mode 100644 index 0000000..aa344ae --- /dev/null +++ b/src/Test-ReleaseDecisionContext.ps1 @@ -0,0 +1,142 @@ +#Requires -Version 7.2 + +<# + .SYNOPSIS + Confirm that the release check still describes the current pull request. + + .EXAMPLE + .\Test-ReleaseDecisionContext.ps1 + + Check the candidate merge checkout and event labels against GitHub. + + .OUTPUTS + System.Management.Automation.PSCustomObject +#> +[OutputType([PSCustomObject])] +[CmdletBinding()] +param( + # The GitHub Actions pull request event payload. + [Parameter()] + [string] $EventPath = $env:GITHUB_EVENT_PATH, + + # The checked-out candidate merge tree. + [Parameter()] + [string] $Workspace = $env:GITHUB_WORKSPACE, + + # The repository receiving the pull request. + [Parameter()] + [string] $Repository = $env:GITHUB_REPOSITORY, + + # The merge commit selected by the pull_request workflow run. + [Parameter()] + [string] $CandidateSha = $env:GITHUB_SHA, + + # The exact pull request used for calculation, if the caller already read it. + [Parameter()] + [PSCustomObject] $CurrentPullRequest +) + +$ErrorActionPreference = 'Stop' +$shaPattern = '\A[0-9a-f]{40}\z' + +function Get-DecisionSnapshot { + <# + .SYNOPSIS + Require the pull request identity, revisions, and labels used for a decision. + #> + param([object] $PullRequest) + + $snapshot = [PSCustomObject]@{ + Number = $PullRequest.number + State = $PullRequest.state + BaseRepo = $PullRequest.base.repo.full_name + BaseRef = $PullRequest.base.ref + BaseSha = $PullRequest.base.sha + HeadRepo = $PullRequest.head.repo.full_name + HeadRef = $PullRequest.head.ref + HeadSha = $PullRequest.head.sha + Labels = $null + } + + if ($snapshot.Number -isnot [long] -or $snapshot.Number -le 0 -or + $snapshot.State -cnotin @('open', 'closed') -or + -not $snapshot.BaseRepo -or -not $snapshot.BaseRef -or $snapshot.BaseSha -cnotmatch $shaPattern -or + -not $snapshot.HeadRepo -or -not $snapshot.HeadRef -or $snapshot.HeadSha -cnotmatch $shaPattern -or + $PullRequest.labels -isnot [array]) { + throw 'GitHub returned an incomplete pull request snapshot. Rerun the release decision check.' + } + + [string[]] $names = @(foreach ($label in $PullRequest.labels) { + if ($label.name -isnot [string] -or -not $label.name) { + throw 'GitHub returned an incomplete pull request label.' + } + $label.name + }) + [Array]::Sort($names, [StringComparer]::Ordinal) + $snapshot.Labels = ConvertTo-Json -InputObject $names -Compress + $snapshot +} + +if ($Repository -cnotmatch '\A[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+\z' -or + [string]::IsNullOrWhiteSpace($Workspace) -or $CandidateSha -cnotmatch $shaPattern) { + throw 'The release decision check needs a repository, workspace, and candidate merge SHA.' +} + +$eventPayload = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($EventPath)) -AsHashtable +$original = Get-DecisionSnapshot -PullRequest $eventPayload.pull_request +if ($original.State -cne 'open' -or $original.BaseRepo -ine $Repository -or $eventPayload.repository.full_name -ine $Repository) { + throw 'The release decision check requires an open pull request to this repository.' +} + +$checkedSha = git -C $Workspace rev-parse --verify HEAD +if ($LASTEXITCODE -ne 0 -or $checkedSha -cne $CandidateSha) { + throw 'The candidate merge checkout does not match the workflow run SHA.' +} + +# Read the commit headers so the parent check also works with a shallow checkout. +$commit = git -C $Workspace cat-file commit HEAD +if ($LASTEXITCODE -ne 0) { + throw 'Could not read the candidate merge commit.' +} +$parents = @(foreach ($line in $commit) { + if ($line -ceq '') { + break + } + if ($line.StartsWith('parent ', [StringComparison]::Ordinal)) { + $line.Substring(7) + } + }) +if ($parents.Count -ne 2 -or $parents[0] -cne $original.BaseSha -or $parents[1] -cne $original.HeadSha) { + throw 'The candidate merge parents do not match the event base and head. Run the check for the current revisions.' +} + +if (-not $PSBoundParameters.ContainsKey('CurrentPullRequest')) { + $json = gh api --method GET "repos/$Repository/pulls/$($original.Number)" + if ($LASTEXITCODE -ne 0) { + throw "Could not read pull request [$($original.Number)]." + } + $CurrentPullRequest = ConvertFrom-Json -InputObject ($json -join "`n") +} +$current = Get-DecisionSnapshot -PullRequest $CurrentPullRequest +if ($current.Number -ne $original.Number -or $current.State -cne 'open') { + throw 'The pull request is not open or does not match the event.' +} +if ($current.BaseRepo -ine $original.BaseRepo -or $current.BaseRef -cne $original.BaseRef -or + $current.BaseSha -cne $original.BaseSha) { + throw 'The pull request target changed. Run the check for the current base.' +} +if ($current.HeadRepo -ine $original.HeadRepo -or $current.HeadRef -cne $original.HeadRef -or + $current.HeadSha -cne $original.HeadSha) { + throw 'The pull request source changed. Run the check for the current head.' +} +if ($current.Labels -cne $original.Labels) { + throw 'The pull request labels changed. Use the result for the current labels.' +} + +[PSCustomObject]@{ + Number = $original.Number + BaseRef = $original.BaseRef + BaseSha = $original.BaseSha + HeadSha = $original.HeadSha + MergeSha = $checkedSha +} diff --git a/src/main.ps1 b/src/main.ps1 index 089a75f..2c96dc3 100644 --- a/src/main.ps1 +++ b/src/main.ps1 @@ -1,388 +1,299 @@ -[Diagnostics.CodeAnalysis.SuppressMessageAttribute( - 'PSAvoidLongLines', '', Justification = 'Long ternary operators are used for readability.' -)] -[Diagnostics.CodeAnalysis.SuppressMessageAttribute( - 'PSUseDeclaredVarsMoreThanAssignments', '', - Justification = 'Parameter is used in dynamic parameter validation.' -)] -[CmdletBinding()] -param() +#Requires -Version 7.2 -LogGroup 'Loading libraries' { - 'powershell-yaml', 'PSSemVer' | ForEach-Object { - $name = $_ - Write-Output "Installing module: $name" - $count = 5 - $delay = 10 - for ($i = 1; $i -le $count; $i++) { - try { - Install-PSResource -Name $name -WarningAction SilentlyContinue -TrustRepository -Repository PSGallery - break - } catch { - Write-Warning "Installation of $name failed with error: $_" - if ($i -eq $count) { - throw $_ - } - Write-Warning "Retrying in $delay seconds..." - Start-Sleep -Seconds $delay - } - } - Import-Module -Name $name - } -} +<# + .SYNOPSIS + Run Release-GHRepository for the current GitHub Actions event. -LogGroup 'Set configuration' { - if (-not (Test-Path -Path $env:PSMODULE_AUTO_RELEASE_INPUT_ConfigurationFile -PathType Leaf)) { - Write-Output "Configuration file not found at [$env:PSMODULE_AUTO_RELEASE_INPUT_ConfigurationFile]" - } else { - Write-Output "Reading from configuration file [$env:PSMODULE_AUTO_RELEASE_INPUT_ConfigurationFile]" - $configuration = ConvertFrom-Yaml -Yaml (Get-Content $env:PSMODULE_AUTO_RELEASE_INPUT_ConfigurationFile -Raw) - } + .DESCRIPTION + Return Calculate outputs or execute the validated Publish plan. - $autoCleanup = ![string]::IsNullOrEmpty($configuration.AutoCleanup) ? $configuration.AutoCleanup -eq 'true' : $env:PSMODULE_AUTO_RELEASE_INPUT_AutoCleanup -eq 'true' - $autoPatching = ![string]::IsNullOrEmpty($configuration.AutoPatching) ? $configuration.AutoPatching -eq 'true' : $env:PSMODULE_AUTO_RELEASE_INPUT_AutoPatching -eq 'true' - $createMajorTag = ![string]::IsNullOrEmpty($configuration.CreateMajorTag) ? $configuration.CreateMajorTag -EQ 'true' : $env:PSMODULE_AUTO_RELEASE_INPUT_CreateMajorTag -EQ 'true' - $createMinorTag = ![string]::IsNullOrEmpty($configuration.CreateMinorTag) ? $configuration.CreateMinorTag -eq 'true' : $env:PSMODULE_AUTO_RELEASE_INPUT_CreateMinorTag -eq 'true' - $datePrereleaseFormat = ![string]::IsNullOrEmpty($configuration.DatePrereleaseFormat) ? $configuration.DatePrereleaseFormat : $env:PSMODULE_AUTO_RELEASE_INPUT_DatePrereleaseFormat - $incrementalPrerelease = ![string]::IsNullOrEmpty($configuration.IncrementalPrerelease) ? $configuration.IncrementalPrerelease -eq 'true' : $env:PSMODULE_AUTO_RELEASE_INPUT_IncrementalPrerelease -eq 'true' - $usePRBodyAsReleaseNotes = ![string]::IsNullOrEmpty($configuration.UsePRBodyAsReleaseNotes) ? $configuration.UsePRBodyAsReleaseNotes -eq 'true' : $env:PSMODULE_AUTO_RELEASE_INPUT_UsePRBodyAsReleaseNotes -eq 'true' - $usePRTitleAsReleaseName = ![string]::IsNullOrEmpty($configuration.UsePRTitleAsReleaseName) ? $configuration.UsePRTitleAsReleaseName -eq 'true' : $env:PSMODULE_AUTO_RELEASE_INPUT_UsePRTitleAsReleaseName -eq 'true' - $usePRTitleAsNotesHeading = ![string]::IsNullOrEmpty($configuration.UsePRTitleAsNotesHeading) ? $configuration.UsePRTitleAsNotesHeading -eq 'true' : $env:PSMODULE_AUTO_RELEASE_INPUT_UsePRTitleAsNotesHeading -eq 'true' - $versionPrefix = ![string]::IsNullOrEmpty($configuration.VersionPrefix) ? $configuration.VersionPrefix : $env:PSMODULE_AUTO_RELEASE_INPUT_VersionPrefix - $whatIf = ![string]::IsNullOrEmpty($configuration.WhatIf) ? $configuration.WhatIf -eq 'true' : $env:PSMODULE_AUTO_RELEASE_INPUT_WhatIf -eq 'true' + .EXAMPLE + .\main.ps1 -Settings $releaseSettings - $ignoreLabels = (![string]::IsNullOrEmpty($configuration.IgnoreLabels) ? $configuration.IgnoreLabels : $env:PSMODULE_AUTO_RELEASE_INPUT_IgnoreLabels) -split ',' | ForEach-Object { $_.Trim() } - $majorLabels = (![string]::IsNullOrEmpty($configuration.MajorLabels) ? $configuration.MajorLabels : $env:PSMODULE_AUTO_RELEASE_INPUT_MajorLabels) -split ',' | ForEach-Object { $_.Trim() } - $minorLabels = (![string]::IsNullOrEmpty($configuration.MinorLabels) ? $configuration.MinorLabels : $env:PSMODULE_AUTO_RELEASE_INPUT_MinorLabels) -split ',' | ForEach-Object { $_.Trim() } - $patchLabels = (![string]::IsNullOrEmpty($configuration.PatchLabels) ? $configuration.PatchLabels : $env:PSMODULE_AUTO_RELEASE_INPUT_PatchLabels) -split ',' | ForEach-Object { $_.Trim() } + Run the action in the mode selected by the resolved settings. - Write-Output '-------------------------------------------------' - Write-Output "Auto cleanup enabled: [$autoCleanup]" - Write-Output "Auto patching enabled: [$autoPatching]" - Write-Output "Create major tag enabled: [$createMajorTag]" - Write-Output "Create minor tag enabled: [$createMinorTag]" - Write-Output "Date-based prerelease format: [$datePrereleaseFormat]" - Write-Output "Incremental prerelease enabled: [$incrementalPrerelease]" - Write-Output "Use PR body as release notes: [$usePRBodyAsReleaseNotes]" - Write-Output "Use PR title as release name: [$usePRTitleAsReleaseName]" - Write-Output "Use PR title as notes heading: [$usePRTitleAsNotesHeading]" - Write-Output "Version prefix: [$versionPrefix]" - Write-Output "What if mode: [$whatIf]" - Write-Output '' - Write-Output "Ignore labels: [$($ignoreLabels -join ', ')]" - Write-Output "Major labels: [$($majorLabels -join ', ')]" - Write-Output "Minor labels: [$($minorLabels -join ', ')]" - Write-Output "Patch labels: [$($patchLabels -join ', ')]" - Write-Output '-------------------------------------------------' -} + .INPUTS + None -LogGroup 'Event information - JSON' { - $githubEventJson = Get-Content $env:GITHUB_EVENT_PATH - $githubEventJson | Format-List | Out-String -} + You can't pipe objects to main.ps1. -LogGroup 'Event information - Object' { - $githubEvent = $githubEventJson | ConvertFrom-Json - if (-not $githubEvent.pull_request) { - Write-GitHubWarning 'This is not run for a pull request. Exiting.' - exit - } - $pull_request = $githubEvent.pull_request - $githubEvent | Format-List | Out-String -} + .OUTPUTS + System.String -$defaultBranchName = (gh repo view --json defaultBranchRef | ConvertFrom-Json | Select-Object -ExpandProperty defaultBranchRef).name -$isPullRequest = $githubEvent.PSObject.Properties.Name -Contains 'pull_request' -if (-not ($isPullRequest -or $whatIf)) { - Write-Warning '⚠️ A release should not be created in this context. Exiting.' - exit + Operational logs for the current GitHub Actions run. +#> +[CmdletBinding()] +param( + # The release policy resolved before GitHub-Script starts. + [Parameter(Mandatory)] + [ValidateNotNull()] + [PSCustomObject] $Settings, + + # The unchanged, source-bound ReleasePlan from Calculate. + [Parameter()] + [string] $ReleasePlan +) + +$ErrorActionPreference = 'Stop' +$PSNativeCommandUseErrorActionPreference = $false + +$planParameters = @{ Settings = $Settings } +if ($ReleasePlan) { + if ($Settings.Mode -cne 'publish') { + throw 'ReleasePlan requires Mode: publish.' + } + $fields = $ReleasePlan.Split('|') + if ($fields.Count -ne 2 -or $fields[0] -cnotmatch '\A[0-9A-F]{64}\z') { + throw 'Invalid ReleasePlan. Pass the unchanged output from Calculate.' + } + $planParameters.PlanFingerprint = $fields[0] + if ($fields[1]) { + $calculationTime = [datetime]::MinValue + $parsedTime = [datetime]::TryParseExact( + $fields[1], 'o', [cultureinfo]::InvariantCulture, [Globalization.DateTimeStyles]::RoundtripKind, [ref] $calculationTime + ) + if (-not $parsedTime -or $calculationTime.Kind -ne [DateTimeKind]::Utc) { + throw 'Invalid ReleasePlan calculation time. Pass the unchanged output from Calculate.' + } + $planParameters.CalculationTime = $calculationTime + } } -$actionType = $githubEvent.action -$isMerged = ($pull_request.merged).ToString() -eq 'True' -$prIsClosed = $pull_request.state -eq 'closed' -$prBaseRef = $pull_request.base.ref -$prHeadRef = $pull_request.head.ref -$targetIsDefaultBranch = $pull_request.base.ref -eq $defaultBranchName -Write-Output '-------------------------------------------------' -Write-Output "Default branch: [$defaultBranchName]" -Write-Output "Is a pull request event: [$isPullRequest]" -Write-Output "Action type: [$actionType]" -Write-Output "PR Merged: [$isMerged]" -Write-Output "PR Closed: [$prIsClosed]" -Write-Output "PR Base Ref: [$prBaseRef]" -Write-Output "PR Head Ref: [$prHeadRef]" -Write-Output "Target is default branch: [$targetIsDefaultBranch]" -Write-Output '-------------------------------------------------' +$helperModulePath = Join-Path -Path $PSScriptRoot -ChildPath 'Release-GHRepository.Helpers.psm1' +$planPath = Join-Path -Path $PSScriptRoot -ChildPath 'Get-EventReleasePlan.ps1' +Import-Module -Name $helperModulePath -Force -LogGroup 'Pull request - details' { - $pull_request | Format-List | Out-String +LogGroup 'Loading libraries' { + for ($attempt = 1; $attempt -le 5; $attempt++) { + try { + Install-PSResource -Name PSSemVer -WarningAction SilentlyContinue -TrustRepository -Repository PSGallery + break + } catch { + $installationError = $_ + Write-Warning "Installation of PSSemVer failed: $installationError" + if ($attempt -eq 5) { + throw $installationError + } + Start-Sleep -Seconds 10 + } + } + Import-Module -Name PSSemVer } -LogGroup 'Pull request - Labels' { - $labels = @() - $labels += $pull_request.labels.name - $labels | Format-List | Out-String +if ($Settings.Mode -ceq 'calculate') { + $plan = & $planPath @planParameters + if ($env:PSMODULE_AUTO_RELEASE_CHECK_PUBLISHER -ceq 'true' -and $env:GITHUB_EVENT_NAME -ceq 'pull_request') { + $contextCheck = Join-Path -Path $PSScriptRoot -ChildPath 'Test-ReleaseDecisionContext.ps1' + $null = & $contextCheck -CurrentPullRequest $plan.PullRequest + } + Set-GitHubOutput -Name Decision -Value $plan.Decision + Set-GitHubOutput -Name BumpSource -Value $plan.ReleaseDecision.BumpSource + if ($plan.Decision -ceq 'release') { + Set-GitHubOutput -Name ReleaseVersion -Value $plan.ReleaseVersion + Set-GitHubOutput -Name ReleasePlan -Value $plan.ReleasePlan + if ($plan.CalculatedAt) { + Set-GitHubOutput -Name CalculatedAt -Value $plan.CalculatedAt + } + } + return } -$createRelease = $isMerged -and $targetIsDefaultBranch -$closedPullRequest = $prIsClosed -and -not $isMerged -$createPrerelease = $labels -Contains 'prerelease' -and -not $createRelease -and -not $closedPullRequest -$prereleaseName = $prHeadRef -replace '[^a-zA-Z0-9]' - -$ignoreRelease = ($labels | Where-Object { $ignoreLabels -contains $_ }).Count -gt 0 -if ($ignoreRelease) { - Write-Output 'Ignoring release creation.' +$whatIf = $Settings.WhatIf +$eventName = $env:GITHUB_EVENT_NAME +$githubEvent = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($env:GITHUB_EVENT_PATH)) +$isPullRequest = $eventName -ceq 'pull_request' +$isBranchPush = $eventName -ceq 'push' -and $githubEvent.deleted -ne $true -and $githubEvent.ref -cnotlike 'refs/tags/*' +if (-not $isPullRequest -and -not $isBranchPush) { + if ($ReleasePlan) { + throw 'ReleasePlan was supplied, but this event is not eligible for publication.' + } + Write-GitHubWarning 'This event is not eligible for publication or pull request cleanup.' return } -$majorRelease = ($labels | Where-Object { $majorLabels -contains $_ }).Count -gt 0 -$minorRelease = ($labels | Where-Object { $minorLabels -contains $_ }).Count -gt 0 -and -not $majorRelease -$patchRelease = (($labels | Where-Object { $patchLabels -contains $_ }).Count -gt 0 -or $autoPatching) -and -not $majorRelease -and -not $minorRelease +$planParameters.GitHubEvent = $githubEvent +$plan = & $planPath @planParameters +if ($null -eq $plan) { + Write-GitHubWarning 'No open pull request matches this branch push. No release will be published.' + return +} -Write-Output '-------------------------------------------------' -Write-Output "Create a release: [$createRelease]" +$pullRequest = $plan.PullRequest +$targetRepository = $plan.TargetRepository +$repositoryArgument = "$($plan.Hostname)/$targetRepository" +$decision = $plan.ReleaseDecision +$createPrerelease = $plan.ReleaseVersion -and -not $plan.Stable + +Write-Output "Auto cleanup enabled: [$($Settings.AutoCleanup)]" +Write-Output "Default bump: [$($Settings.DefaultBump)]" +Write-Output "Default bump source: [$($Settings.DefaultBumpSource)]" +Write-Output "Default bump applied: [$($decision.DefaultBumpApplied)]" +Write-Output "Bump source: [$($decision.BumpSource)]" +Write-Output "Date-based prerelease format: [$($Settings.DatePrereleaseFormat)]" +Write-Output "Use PR body as release notes: [$($Settings.UsePRBodyAsReleaseNotes)]" +Write-Output "Version prefix: [$($Settings.VersionPrefix)]" +Write-Output "What if mode: [$whatIf]" +Write-Output "Skip release: [$($decision.Skip)]" Write-Output "Create a prerelease: [$createPrerelease]" -Write-Output "Create a major release: [$majorRelease]" -Write-Output "Create a minor release: [$minorRelease]" -Write-Output "Create a patch release: [$patchRelease]" -Write-Output "Closed pull request: [$closedPullRequest]" -Write-Output '-------------------------------------------------' -LogGroup 'Get releases' { - $releases = gh release list --json 'createdAt,isDraft,isLatest,isPrerelease,name,publishedAt,tagName' | ConvertFrom-Json - if ($LASTEXITCODE -ne 0) { - Write-Error 'Failed to list all releases for the repo.' - exit $LASTEXITCODE +$prereleasesToCleanup = @() +if ($plan.CleanupOnly -and $Settings.AutoCleanup) { + $pullRequestContext = Resolve-PullRequestReleaseContext -PullRequest $pullRequest -AllowEmptyPrereleaseName + if ($pullRequestContext.PrereleaseName) { + $recordsJson = gh release list --repo $repositoryArgument --json 'isPrerelease,tagName' + if ($LASTEXITCODE -ne 0) { + throw "Failed to read prereleases for cleanup in $targetRepository. gh exited with code [$LASTEXITCODE]." + } + $releases = ConvertFrom-Json -InputObject ($recordsJson -join "`n") -NoEnumerate + if ($releases -isnot [array]) { + throw "GitHub returned an invalid release list for $targetRepository." + } + $cleanupParameters = @{ + Releases = $releases + PrereleaseName = $pullRequestContext.PrereleaseName + VersionPrefix = $Settings.VersionPrefix + } + $prereleasesToCleanup = @(Get-PrereleaseCleanupCandidate @cleanupParameters) + } else { + Write-Output 'This branch has no prerelease identifier; cleanup has no candidates.' } - $releases | Select-Object -Property name, isPrerelease, isLatest, publishedAt | Format-Table | Out-String } -LogGroup 'Get latest version' { - $latestRelease = $releases | Where-Object { $_.isLatest -eq $true } - $latestRelease | Format-List | Out-String - $latestVersionString = $latestRelease.tagName - if (![string]::IsNullOrEmpty($latestVersionString)) { - $latestVersion = $latestVersionString | ConvertTo-PSSemVer - Write-Output '-------------------------------------------------' - Write-Output 'Latest version:' - $latestVersion | Format-Table - $latestVersion = $latestVersion.ToString() +if ($isPullRequest) { + foreach ($definition in Get-ReleaseLabelDefinition) { + $arguments = @( + 'label', 'create', $definition.Name, '--repo', $repositoryArgument + '--color', $definition.Color, '--description', $definition.Description, '--force' + ) + if ($whatIf) { + Write-Output "WhatIf: gh $($arguments -join ' ')" + } else { + gh @arguments + if ($LASTEXITCODE -ne 0) { + throw "Failed to provision canonical label [$($definition.Name)]. gh exited with code [$LASTEXITCODE]." + } + } } } -Write-Output '-------------------------------------------------' -Write-Output "Latest version: [$latestVersion]" -Write-Output '-------------------------------------------------' - -if ($createPrerelease -or $createRelease -or $whatIf) { - LogGroup 'Calculate new version' { - $latestVersion = New-PSSemVer -Version $latestVersion - $newVersion = New-PSSemVer -Version $latestVersion - $newVersion.Prefix = $versionPrefix - if ($majorRelease) { - Write-Output 'Incrementing major version.' - $newVersion.BumpMajor() - } elseif ($minorRelease) { - Write-Output 'Incrementing minor version.' - $newVersion.BumpMinor() - } elseif ($patchRelease) { - Write-Output 'Incrementing patch version.' - $newVersion.BumpPatch() - } else { - Write-Output 'Skipping release creation, exiting.' - return +if ($plan.ReleaseVersion) { + $tag = $plan.TagVersion.ToString() + $target = $plan.CommitSha + $aliasPush = @() + if ($plan.Stable -and ($Settings.CreateMajorTag -or $Settings.CreateMinorTag)) { + $remote = "$($env:GITHUB_SERVER_URL.TrimEnd('/'))/$targetRepository.git" + $aliasPush = @('push', '--no-follow-tags', $remote) + if ($Settings.CreateMajorTag) { + $aliasPush += "+${target}:refs/tags/$($plan.TagVersion.Prefix)$($plan.TagVersion.Major)" } - - Write-Output "Partial new version: [$newVersion]" - - if ($createPrerelease) { - Write-Output "Adding a prerelease tag to the version using the branch name [$prereleaseName]." - $newVersion.Prerelease = $prereleaseName - Write-Output "Partial new version: [$newVersion]" - - if (![string]::IsNullOrEmpty($datePrereleaseFormat)) { - Write-Output "Using date-based prerelease: [$datePrereleaseFormat]." - $newVersion.Prerelease += ".$(Get-Date -Format $datePrereleaseFormat)" - Write-Output "Partial new version: [$newVersion]" - } - - if ($incrementalPrerelease) { - $newVersion.BumpPrereleaseNumber() + if ($Settings.CreateMinorTag) { + $aliasPush += "+${target}:refs/tags/$($plan.TagVersion.Prefix)$($plan.TagVersion.Major).$($plan.TagVersion.Minor)" + } + if ($whatIf) { + Write-Output "WhatIf: git fetch --no-tags $remote $target" + } else { + git fetch --no-tags $remote $target + if ($LASTEXITCODE -ne 0) { + throw "Failed to fetch release target [$target]. git exited with code [$LASTEXITCODE]." } } } - Write-Output '-------------------------------------------------' - Write-Output "New version: [$newVersion]" - Write-Output '-------------------------------------------------' - - LogGroup "Create new release [$newVersion]" { - if ($createPrerelease) { - $releaseExists = $releases.tagName -Contains $newVersion - if ($releaseExists -and -not $incrementalPrerelease) { - Write-Output 'Release already exists, recreating.' - if ($whatIf) { - Write-Output "WhatIf: gh release delete $newVersion --cleanup-tag --yes" - } else { - gh release delete $newVersion --cleanup-tag --yes - if ($LASTEXITCODE -ne 0) { - Write-Error "Failed to delete the release [$newVersion]." - exit $LASTEXITCODE - } - } - } - - # Build release creation command with options - $releaseCreateCommand = @('release', 'create', "$newVersion") - - # Add title parameter - if ($usePRTitleAsReleaseName) { - $prTitle = $pull_request.title - $releaseCreateCommand += @('--title', "$prTitle") - Write-Output "Using PR title as release name: [$prTitle]" - } else { - $releaseCreateCommand += @('--title', "$newVersion") - } - - # Add notes parameter - $notes = '' - if ($usePRTitleAsNotesHeading) { - $prTitle = $pull_request.title - $prNumber = $pull_request.number - $notes += "# $prTitle (#$prNumber)`n`n" - } - if ($usePRBodyAsReleaseNotes) { - $prBody = $pull_request.body - $notes += $prBody - } - if (-not [string]::IsNullOrWhiteSpace($notes)) { - $releaseCreateCommand += @('--notes', $notes) - } else { - $releaseCreateCommand += '--generate-notes' - } - - # Add remaining parameters - $releaseCreateCommand += @('--target', $prHeadRef, '--prerelease') - Write-Output "gh $($releaseCreateCommand -join ' ')" - if (-not $whatIf) { - # Execute the command and capture the output - $releaseURL = gh @releaseCreateCommand - if ($LASTEXITCODE -ne 0) { - Write-Error "Failed to create the release [$newVersion]." - exit $LASTEXITCODE - } - } - - if ($whatIf) { - Write-Output 'WhatIf: gh pr comment $pull_request.number -b "The release [$newVersion] has been created."' - } else { - gh pr comment $pull_request.number -b "The release [$newVersion]($releaseURL) has been created." - if ($LASTEXITCODE -ne 0) { - Write-Error 'Failed to comment on the pull request.' - exit $LASTEXITCODE - } - } + if ($plan.ReplacePrerelease) { + $releaseDelete = @('release', 'delete', $tag, '--repo', $repositoryArgument, '--yes') + if (-not $plan.TagExists) { + $releaseDelete += '--cleanup-tag' + } + if ($whatIf) { + Write-Output "WhatIf: gh $($releaseDelete -join ' ')" } else { - # Build release creation command with options - $releaseCreateCommand = @('release', 'create', "$newVersion") - - # Add title parameter - if ($usePRTitleAsReleaseName) { - $prTitle = $pull_request.title - $releaseCreateCommand += @('--title', "$prTitle") - Write-Output "Using PR title as release name: [$prTitle]" - } else { - $releaseCreateCommand += @('--title', "$newVersion") + gh @releaseDelete + if ($LASTEXITCODE -ne 0) { + throw "Failed to replace prerelease [$tag]. gh exited with code [$LASTEXITCODE]." } + } + } - # Add notes parameter - $notes = '' - if ($usePRTitleAsNotesHeading) { - $prTitle = $pull_request.title - $prNumber = $pull_request.number - $notes += "# $prTitle (#$prNumber)`n`n" - } - if ($usePRBodyAsReleaseNotes) { - $prBody = $pull_request.body - $notes += $prBody - } - if (-not [string]::IsNullOrWhiteSpace($notes)) { - $releaseCreateCommand += @('--notes', $notes) - } else { - $releaseCreateCommand += '--generate-notes' + if (-not $plan.TagExists) { + # Create the ref without force so a tag created after preflight cannot change the release target. + $tagCreate = @('api', "repos/$targetRepository/git/refs", '--hostname', $plan.Hostname, '--method', 'POST') + $tagCreate += @('-f', "ref=refs/tags/$tag", '-f', "sha=$target") + if ($whatIf) { + Write-Output "WhatIf: gh $($tagCreate -join ' ')" + } else { + $null = gh @tagCreate + if ($LASTEXITCODE -ne 0) { + throw "Failed to create release tag [$tag] at [$target]. gh exited with code [$LASTEXITCODE]." } + } + } - Write-Output "gh $($releaseCreateCommand -join ' ')" - if (-not $whatIf) { - gh @releaseCreateCommand - if ($LASTEXITCODE -ne 0) { - Write-Error "Failed to create the release [$newVersion]." - exit $LASTEXITCODE - } - } + $title = $tag + if ($pullRequest -and $Settings.UsePRTitleAsReleaseName) { + $title = $pullRequest.title + } + $notes = '' + if ($pullRequest -and $Settings.UsePRTitleAsNotesHeading) { + $notes = "# $($pullRequest.title) (#$($pullRequest.number))`n`n" + } + if ($pullRequest -and $Settings.UsePRBodyAsReleaseNotes) { + $notes += $pullRequest.body + } + $releaseCreate = @('release', 'create', $tag, '--repo', $repositoryArgument, '--title', $title, '--verify-tag') + if ([string]::IsNullOrWhiteSpace($notes)) { + $releaseCreate += '--generate-notes' + } else { + $releaseCreate += @('--notes', $notes) + } + $releaseCreate += @('--target', $target) + if ($createPrerelease) { + $releaseCreate += '--prerelease' + } - if ($createMajorTag) { - $majorTag = ('{0}{1}' -f $newVersion.Prefix, $newVersion.Major) - if ($whatIf) { - Write-Output "WhatIf: git tag -f $majorTag 'main'" - } else { - git tag -f $majorTag 'main' - if ($LASTEXITCODE -ne 0) { - Write-Error "Failed to create major tag [$majorTag]." - exit $LASTEXITCODE - } - } - } + if ($whatIf) { + Write-Output "WhatIf: gh $($releaseCreate -join ' ')" + } else { + $releaseUrl = gh @releaseCreate + if ($LASTEXITCODE -ne 0) { + throw "Failed to create release [$tag]. gh exited with code [$LASTEXITCODE]." + } + } - if ($createMinorTag) { - $minorTag = ('{0}{1}.{2}' -f $newVersion.Prefix, $newVersion.Major, $newVersion.Minor) - if ($whatIf) { - Write-Output "WhatIf: git tag -f $minorTag 'main'" - } else { - git tag -f $minorTag 'main' - if ($LASTEXITCODE -ne 0) { - Write-Error "Failed to create minor tag [$minorTag]." - exit $LASTEXITCODE - } - } + if ($createPrerelease) { + if ($whatIf) { + Write-Output "WhatIf: gh pr comment $($pullRequest.number) --repo $repositoryArgument" + } else { + gh pr comment $pullRequest.number --repo $repositoryArgument --body "The release [$tag]($releaseUrl) has been created." + if ($LASTEXITCODE -ne 0) { + throw "Failed to comment on the pull request. gh exited with code [$LASTEXITCODE]." } - - if ($whatIf) { - Write-Output 'WhatIf: git push origin --tags --force' - } else { - git push origin --tags --force - if ($LASTEXITCODE -ne 0) { - Write-Error 'Failed to push tags.' - exit $LASTEXITCODE - } + } + } + if ($aliasPush.Count -gt 0) { + if ($whatIf) { + Write-Output "WhatIf: git $($aliasPush -join ' ')" + } else { + git @aliasPush + if ($LASTEXITCODE -ne 0) { + throw "Failed to update the enabled aliases for [$tag]. git exited with code [$LASTEXITCODE]." } } } - Write-GitHubNotice -Title 'Release created' -Message $newVersion + if (-not $whatIf) { + Write-GitHubNotice -Title 'Release created' -Message $tag + } } else { Write-Output 'Skipping release creation.' } -LogGroup 'List prereleases using the same name' { - $prereleasesToCleanup = $releases | Where-Object { $_.tagName -like "*$prereleaseName*" } - $prereleasesToCleanup | Select-Object -Property name, publishedAt, isPrerelease, isLatest | Format-Table | Out-String -} - -if ((($closedPullRequest -or $createRelease) -and $autoCleanup) -or $whatIf) { - LogGroup "Cleanup prereleases for [$prereleaseName]" { - foreach ($rel in $prereleasesToCleanup) { - $relTagName = $rel.tagName - Write-Output "Deleting prerelease: [$relTagName]." - if ($whatIf) { - Write-Output "WhatIf: gh release delete $($rel.tagName) --cleanup-tag --yes" - } else { - gh release delete $rel.tagName --cleanup-tag --yes - if ($LASTEXITCODE -ne 0) { - Write-Error "Failed to delete release [$relTagName]." - exit $LASTEXITCODE - } - } +foreach ($release in $prereleasesToCleanup) { + $deleteArguments = @('release', 'delete', $release.tagName, '--cleanup-tag', '--yes', '--repo', $repositoryArgument) + if ($whatIf) { + Write-Output "WhatIf: gh $($deleteArguments -join ' ')" + } else { + gh @deleteArguments + if ($LASTEXITCODE -ne 0) { + throw "Failed to clean up prerelease [$($release.tagName)]. gh exited with code [$LASTEXITCODE]." } } } diff --git a/tests/Get-ReleaseWorkflowInputs.Tests.ps1 b/tests/Get-ReleaseWorkflowInputs.Tests.ps1 new file mode 100644 index 0000000..d909848 --- /dev/null +++ b/tests/Get-ReleaseWorkflowInputs.Tests.ps1 @@ -0,0 +1,163 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute( + 'PSUseDeclaredVarsMoreThanAssignments', '', + Justification = 'The Pester cases share the workflow reader and fixture.' +)] +[CmdletBinding()] +param() + +BeforeAll { + Import-Module -Name powershell-yaml -RequiredVersion 0.4.12 + $reader = Join-Path -Path $PSScriptRoot -ChildPath '..\src\Get-ReleaseWorkflowInputs.ps1' + $workflowFixture = @' +name: Release +on: + push: + branches: [main] +jobs: + PublishStable: + if: ${{ github.event_name == 'push' && github.ref_name == github.event.repository.default_branch }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@example + - uses: ./ + +'@ + $read = { + param( + [string] $Inputs, + [string] $Target = 'main', + [string] $Workflow = $workflowFixture + ) + $path = Join-Path -Path $TestDrive -ChildPath 'Release.yml' + $Workflow.Replace('', $Inputs) | Set-Content -LiteralPath $path + & $reader -Path $path -TargetBranch $Target -SettingNames @('Mode', 'DefaultBump', 'WhatIf', 'Version') + } +} + +Describe 'Reading the invoked release settings' { + It 'reads literal publisher overrides in the same form as action inputs' { + $inputs = & $read @' + with: + DefaultBump: minor + SettingsFilePath: .github/branch-release.yml + WhatIf: false + Version: '[0.43.1]' +'@ + + $inputs.DefaultBump | Should -BeExactly 'minor' + $inputs.SettingsFilePath | Should -BeExactly '.github/branch-release.yml' + $inputs.WhatIf | Should -BeExactly 'false' + $inputs.Version | Should -BeExactly '[0.43.1]' + } + + It 'leaves settings to the usual resolver when the publisher omits with' { + $inputs = & $read '' + + $inputs | Should -BeOfType ([System.Collections.IDictionary]) + $inputs.Count | Should -Be 0 + } + + It 'keeps an explicit Publish mode so it can override the file' { + $inputs = & $read " with:`n Mode: publish`n DefaultBump: patch" + + $inputs.Mode | Should -BeExactly 'publish' + $inputs.DefaultBump | Should -BeExactly 'patch' + } + + It 'reads the stable publisher overrides rather than treating the Plan output as policy' { + $staged = $workflowFixture.Replace(' runs-on:', ' needs: [Plan, CI]' + "`n runs-on:") + $staged = $staged.Replace("default_branch }}", "default_branch && needs.Plan.outputs.Decision == 'release' }}") + + $inputs = & $read -Workflow $staged -Inputs @' + with: + Mode: publish + DefaultBump: minor + ReleasePlan: ${{ needs.Plan.outputs.ReleasePlan }} +'@ + + $inputs.DefaultBump | Should -BeExactly 'minor' + $inputs.ContainsKey('ReleasePlan') | Should -BeFalse + } + + It 'rejects a staged publisher that does not consume its calculated plan' { + $staged = $workflowFixture.Replace(' runs-on:', ' needs: [Plan, CI]' + "`n runs-on:") + $staged = $staged.Replace("default_branch }}", "default_branch && needs.Plan.outputs.Decision == 'release' }}") + + { & $read -Workflow $staged -Inputs '' } | Should -Throw '*ReleasePlan*Plan job*' + } + + It 'uses the repository pipeline to validate the real stable publisher' { + $workflow = Join-Path -Path $PSScriptRoot -ChildPath '..\.github\workflows\Release.yml' + + $inputs = & $reader -Path $workflow -TargetBranch 'main' -SettingNames @('Mode', 'DefaultBump', 'WhatIf', 'Version') + + $inputs.Mode | Should -BeExactly 'publish' + } + + It 'runs the release decision on PR sync and waits for CI before publishing on a push' { + $path = Join-Path -Path $PSScriptRoot -ChildPath '..\.github\workflows\Release.yml' + $pipeline = ConvertFrom-Yaml -Yaml ([IO.File]::ReadAllText($path)) + + $pipeline.on.pull_request.types | Should -Contain 'synchronize' + $pipeline.jobs.PublishStable.needs | Should -Contain 'Plan' + $pipeline.jobs.PublishStable.needs | Should -Contain 'CI' + } + + It 'rejects a target that the publisher does not handle' { + { & $read '' 'release-v2' } | Should -Throw '*does not handle*release-v2*' + } + + It 'rejects a branch exclusion even when an earlier filter names the target' { + $workflow = $workflowFixture.Replace('[main]', "[main, '!main']") + + { & $read '' -Workflow $workflow } | Should -Throw '*unsupported*branch*filter*' + } + + It 'rejects a publisher with a PR trigger instead of a branch push' { + $workflow = $workflowFixture.Replace(' push:', ' pull_request:') + + { & $read '' -Workflow $workflow } | Should -Throw '*push trigger*' + } + + It 'rejects a publisher that runs on a path filter' { + $workflow = $workflowFixture.Replace('branches: [main]', "branches: [main]`n paths: ['src/**']") + + { & $read '' -Workflow $workflow } | Should -Throw '*unsupported*filter*' + } + + It 'rejects a different conditional publisher route' { + $workflow = $workflowFixture.Replace('github.ref_name == github.event.repository.default_branch', 'false') + + { & $read '' -Workflow $workflow } | Should -Throw '*conditional*publisher*' + } + + It 'rejects a publisher that checks out a different ref' { + $checkout = " - uses: actions/checkout@example`n with:`n ref: refs/heads/maintenance" + $workflow = $workflowFixture.Replace(' - uses: actions/checkout@example', $checkout) + + { & $read '' -Workflow $workflow } | Should -Throw '*publisher checkout*ref*' + } + + It 'rejects settings routed to a different repository' { + $checkout = " - uses: actions/checkout@example`n with:`n repository: example/other" + $workflow = $workflowFixture.Replace(' - uses: actions/checkout@example', $checkout) + + { & $read '' -Workflow $workflow } | Should -Throw '*publisher checkout*repository*' + } + + It 'rejects an unsupported input even if it is named Keys' { + $inputs = " with:`n Keys: DefaultBump`n DefaultBump: minor" + + { & $read $inputs } | Should -Throw '*unsupported*Keys*' + } + + It 'rejects instead of falling back to defaults' -ForEach @( + @{ Case = 'a dynamic bump'; Key = 'DefaultBump'; Value = '${{ vars.RELEASE_BUMP }}'; ErrorText = '*literal*DefaultBump*' } + @{ Case = 'an unknown setting'; Key = 'DefaultBunp'; Value = 'major'; ErrorText = '*unsupported*DefaultBunp*' } + @{ Case = 'a null override'; Key = 'Version'; Value = 'null'; ErrorText = '*literal*Version*' } + ) { + $inputBlock = " with:`n ${Key}: $Value" + + { & $read $inputBlock } | Should -Throw $ErrorText + } +} diff --git a/tests/Release-GHRepository.Calculation.Tests.ps1 b/tests/Release-GHRepository.Calculation.Tests.ps1 new file mode 100644 index 0000000..af643d5 --- /dev/null +++ b/tests/Release-GHRepository.Calculation.Tests.ps1 @@ -0,0 +1,821 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute( + 'PSUseDeclaredVarsMoreThanAssignments', '', + Justification = 'Variables are assigned in Pester setup and used by tests and mocks.' +)] +[CmdletBinding()] +param() + +$ErrorActionPreference = 'Stop' + +BeforeAll { + Import-Module -Name GitHub, powershell-yaml, PSSemVer + $actionDirectory = Split-Path -Path $PSScriptRoot -Parent + $actionPath = Join-Path -Path $actionDirectory -ChildPath 'action.yml' + $bootstrapPath = Join-Path -Path $actionDirectory -ChildPath 'src\Initialize-ReleaseConfiguration.ps1' + $helperPath = Join-Path -Path $actionDirectory -ChildPath 'src\Release-GHRepository.Helpers.psm1' + $action = ConvertFrom-Yaml -Yaml ([IO.File]::ReadAllText($actionPath)) + $scriptStep = $action.runs.steps | Where-Object { $_.uses -like 'PSModule/GitHub-Script@*' } + $runAction = [scriptblock]::Create($scriptStep.with.Script) + $runActionStep = { + $githubEvent | ConvertTo-Json -Depth 20 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH + [IO.File]::WriteAllText($bootstrapOutput, '') + $null = & $bootstrapPath -OutputPath $bootstrapOutput + $settingsRecord = Select-String -LiteralPath $bootstrapOutput -Pattern '^ReleaseSettings<<' -Context 0, 1 + if (-not $settingsRecord.Context.PostContext) { + throw 'The settings step did not write the release settings.' + } + $env:PSMODULE_AUTO_RELEASE_RESOLVED_SETTINGS = $settingsRecord.Context.PostContext[0] + & $runAction + } + $runCalculation = { + $null = & $runActionStep + (Get-GitHubOutput -AsHashtable).result + } + $calculateForPublish = { + $env:PSMODULE_AUTO_RELEASE_INPUT_Mode = 'calculate' + $result = & $runCalculation + $env:PSMODULE_AUTO_RELEASE_INPUT_Mode = 'publish' + $result + } + $expectFailure = { + param([string] $Message) + + { & $runCalculation } | Should -Throw $Message + [IO.File]::ReadAllText($env:GITHUB_OUTPUT) | Should -BeExactly '' + } + $expectNoRepositoryWrites = { + Should -Invoke git -Times 0 -Exactly -ParameterFilter { $args[0] -cne 'check-ref-format' } + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { + $args[0] -cin @('pr', 'label') -or + ($args[0] -ceq 'release' -and $args[1] -cne 'list') -or + ($args[0] -ceq 'api' -and ($args -ccontains 'POST' -or $args -ccontains 'PATCH' -or $args -ccontains 'DELETE')) + } + } + $headSha = '0123456789012345678901234567890123456789' + $mergeSha = 'fedcba9876543210fedcba9876543210fedcba98' + $targetRepository = 'example/project' +} + +Describe 'Release-GHRepository event release plans' { + BeforeEach { + $environmentNames = @( + 'GITHUB_ACTION' + 'GITHUB_EVENT_NAME' + 'GITHUB_EVENT_PATH' + 'GITHUB_OUTPUT' + 'GITHUB_REPOSITORY' + 'GITHUB_RUN_ID' + 'GITHUB_SERVER_URL' + 'GITHUB_WORKSPACE' + 'PSMODULE_AUTO_RELEASE_ACTION_PATH' + 'PSMODULE_AUTO_RELEASE_INPUT_Mode' + 'PSMODULE_AUTO_RELEASE_INPUT_PullRequest' + 'PSMODULE_AUTO_RELEASE_INPUT_ReleasePlan' + 'PSMODULE_AUTO_RELEASE_RESOLVED_SETTINGS' + 'PSMODULE_GITHUB_SCRIPT' + ) + @($action.inputs.Keys | ForEach-Object { "PSMODULE_AUTO_RELEASE_INPUT_$_" }) + $savedEnvironment = @{} + foreach ($name in $environmentNames | Select-Object -Unique) { + $savedEnvironment[$name] = [Environment]::GetEnvironmentVariable($name) + [Environment]::SetEnvironmentVariable($name, $null) + } + + $workspace = Join-Path -Path $TestDrive -ChildPath ([guid]::NewGuid().ToString('N')) + $null = New-Item -Path $workspace -ItemType Directory + $bootstrapOutput = Join-Path -Path $workspace -ChildPath 'settings.out' + $env:GITHUB_OUTPUT = Join-Path -Path $workspace -ChildPath 'result.out' + [IO.File]::WriteAllText($env:GITHUB_OUTPUT, '') + $env:GITHUB_ACTION = 'release' + $env:GITHUB_EVENT_NAME = 'pull_request' + $env:GITHUB_EVENT_PATH = Join-Path -Path $workspace -ChildPath 'event.json' + $env:GITHUB_REPOSITORY = $targetRepository + $env:GITHUB_RUN_ID = '12345' + $env:GITHUB_SERVER_URL = 'https://github.com' + $env:GITHUB_WORKSPACE = $workspace + $env:PSMODULE_AUTO_RELEASE_ACTION_PATH = $actionDirectory + $env:PSMODULE_AUTO_RELEASE_INPUT_Mode = 'calculate' + $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath = Join-Path -Path $workspace -ChildPath 'settings.yml' + $env:PSMODULE_GITHUB_SCRIPT = 'true' + + $repository = @{ full_name = $targetRepository; default_branch = 'trunk'; fork = $false } + $head = @{ ref = 'feature/calc'; sha = $headSha; repo = @{ full_name = $targetRepository } } + $base = @{ ref = 'trunk'; repo = @{ full_name = $targetRepository } } + $currentPullRequest = @{ + number = 42; state = 'open'; head = $head; base = $base + labels = @(@{ name = 'release:minor' }) + } + $eventPullRequest = $currentPullRequest.Clone() + $eventPullRequest.labels = @(@{ name = 'release:major' }) + $githubEvent = @{ repository = $repository; pull_request = $eventPullRequest; number = 42; action = 'synchronize' } + $push = @{ repository = $repository; ref = 'refs/heads/feature/calc'; after = $headSha; deleted = $false } + $defaultPush = @{ repository = $repository; ref = 'refs/heads/trunk'; after = $mergeSha; deleted = $false } + $openPages = , (, $currentPullRequest) + $associatedPages = , @() + $latest = @{ tagName = 'v2.0.3'; isDraft = $false; isPrerelease = $false } + $historyResponse = @{ data = @{ repository = @{ nameWithOwner = $targetRepository; latestRelease = $latest } } } + $historyExitCode = 0 + $lookupExitCode = 0 + $liveDefaultBranch = 'trunk' + $tagExitCode = 0 + $tagReferences = @() + $releaseRecords = @() + $allowSimulatedWrites = $false + + # Simulate API responses so these tests need no token and cannot change a repository. + Mock Install-PSResource {} + Mock git { + if (-not $allowSimulatedWrites) { + throw 'Calculate must not run git.' + } + $global:LASTEXITCODE = 0 + } + Mock gh { + $global:LASTEXITCODE = 0 + if ($args[0] -ceq 'api' -and $args[1] -ceq 'graphql' -and + $args -contains 'owner=example' -and $args -contains 'name=project' -and + $args -clike 'query=query*latestRelease*') { + $global:LASTEXITCODE = $historyExitCode + ConvertTo-Json -InputObject $historyResponse -Depth 20 -Compress + } elseif ($args[0] -ceq 'api' -and $args -contains 'GET') { + switch -Wildcard ($args[1]) { + "repos/$targetRepository/pulls/42" { + ConvertTo-Json -InputObject $currentPullRequest -Depth 20 -Compress + } + "repos/$targetRepository/pulls" { + $global:LASTEXITCODE = $lookupExitCode + ConvertTo-Json -InputObject $openPages -Depth 20 -Compress + } + "repos/$targetRepository/commits/$mergeSha/pulls" { + $global:LASTEXITCODE = $lookupExitCode + ConvertTo-Json -InputObject $associatedPages -Depth 20 -Compress + } + "repos/$targetRepository" { + @{ full_name = $targetRepository; default_branch = $liveDefaultBranch } | ConvertTo-Json -Compress + } + "repos/$targetRepository/git/matching-refs/tags/*" { + $global:LASTEXITCODE = $tagExitCode + ConvertTo-Json -InputObject $tagReferences -Depth 20 -Compress + } + default { throw "Unexpected GitHub read: gh $($args -join ' ')" } + } + } elseif ($args[0] -ceq 'repo' -and $args[1] -ceq 'view') { + '{"defaultBranchRef":{"name":"trunk"}}' + } elseif ($args[0] -ceq 'release' -and $args[1] -ceq 'list') { + ConvertTo-Json -InputObject $releaseRecords -Depth 20 -Compress + } elseif ($allowSimulatedWrites -and $args[0] -ceq 'release' -and $args[1] -ceq 'create') { + 'https://github.com/example/project/releases/tag/test' + } elseif ($allowSimulatedWrites -and ( + $args[0] -cin @('label', 'pr') -or + ($args[0] -ceq 'release' -and $args[1] -ceq 'delete') -or + ($args[0] -ceq 'api' -and $args[1] -ceq "repos/$targetRepository/git/refs" -and $args -ccontains 'POST') + )) { + return + } else { + throw "Unexpected GitHub command: gh $($args -join ' ')" + } + } + } + + AfterEach { + foreach ($name in $savedEnvironment.Keys) { + [Environment]::SetEnvironmentVariable($name, $savedEnvironment[$name]) + } + if (-not $allowSimulatedWrites) { + Should -Invoke git -Times 0 -Exactly + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[0] -cne 'api' } + } + } + + It 'uses current PR labels for a prerelease without a publication label when WhatIf is ' -ForEach @( + @{ WhatIf = 'false' } + @{ WhatIf = 'true' } + ) { + $env:PSMODULE_AUTO_RELEASE_INPUT_WhatIf = $WhatIf + + $result = & $runCalculation + + $result.Decision | Should -BeExactly 'release' + $result.BumpSource | Should -BeExactly 'release:minor' + $result.ReleaseVersion | Should -BeExactly '2.1.0-featurecalc.1' + $result.ReleasePlan | Should -Not -BeNullOrEmpty + } + + It 'uses the configured default for an unlabeled PR synchronize event' { + $currentPullRequest.labels = @() + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'minor' + + $result = & $runCalculation + + $result.Decision | Should -BeExactly 'release' + $result.BumpSource | Should -BeExactly 'ActionInput' + $result.ReleaseVersion | Should -BeExactly '2.1.0-featurecalc.1' + } + + It 'returns the UTC instant used to format a date-dependent prerelease' { + $env:PSMODULE_AUTO_RELEASE_INPUT_DatePrereleaseFormat = 'yyyy-MM-dd' + $env:PSMODULE_AUTO_RELEASE_INPUT_IncrementalPrerelease = 'false' + $before = [datetime]::UtcNow + + $result = & $runCalculation + + [IO.File]::ReadAllText($env:GITHUB_OUTPUT) | Should -Match '"CalculatedAt"\s*:\s*"[0-9T:.-]+Z"' + $instant = ([datetimeoffset] $result.CalculatedAt).UtcDateTime + $instant | Should -BeGreaterOrEqual $before + $instant | Should -BeLessOrEqual ([datetime]::UtcNow) + $date = $instant.ToString('yyyy-MM-dd', [cultureinfo]::InvariantCulture) + $result.ReleaseVersion | Should -BeExactly "2.1.0-featurecalc.$date" + } + + It 'replays the same date-dependent version from a supplied UTC instant' { + Import-Module -Name $helperPath -Force + $decision = Resolve-ReleaseDecision -Labels @('release:minor') -DefaultBump 'none' + $timestamp = '2026-01-03T02:05:06.0000000Z' + $calculationTime = ([datetimeoffset]::Parse($timestamp, [cultureinfo]::InvariantCulture)).UtcDateTime + $planParameters = @{ + ReleaseDecision = $decision + Settings = [PSCustomObject]@{ + DatePrereleaseFormat = 'yyyy-MM-dd' + IncrementalPrerelease = $true + VersionPrefix = 'product-' + } + BaselineTag = 'v2.0.3' + PrereleaseName = 'featurecalc' + CalculationTime = $calculationTime + } + + $plan = Get-ReleaseVersionPlan @planParameters + + $plan.ReleaseVersion | Should -BeExactly '2.1.0-featurecalc.2026-01-03.1' + $plan.TagVersion.ToString() | Should -BeExactly 'product-2.1.0-featurecalc.2026-01-03.1' + $plan.CalculatedAt | Should -BeExactly $timestamp + } + + It 'returns a successful skip without a version or a release history read' { + $currentPullRequest.labels = @(@{ name = 'release:skip' }) + + $result = & $runCalculation + + $result.Decision | Should -BeExactly 'skip' + $result.BumpSource | Should -BeExactly 'release:skip' + $result.Keys | Should -Not -Contain 'ReleaseVersion' + $result.Keys | Should -Not -Contain 'ReleasePlan' + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[1] -ceq 'graphql' } + } + + It 'requires a valid release decision: ' -ForEach @( + @{ Case = 'no labels or default'; Labels = @(); Message = '*No release bump*' } + @{ Case = 'prerelease alone'; Labels = @('release:prerelease'); Message = '*No release bump*' } + @{ Case = 'two bumps'; Labels = @('release:patch', 'release:major'); Message = '*Conflicting release bump labels*' } + @{ Case = 'conflicting skip'; Labels = @('release:skip', 'release:minor'); Message = '*release:skip must not be combined*' } + ) { + $currentPullRequest.labels = @($Labels | ForEach-Object { @{ name = $_ } }) + + & $expectFailure -Message $Message + } + + It 'rejects a stale PR event even if the current labels would allow a release' { + $currentPullRequest.head = $head.Clone() + $currentPullRequest.head.sha = $mergeSha + + & $expectFailure -Message '*no longer matches*' + } + + It 'requires the PR event to identify the source repository' { + $eventPullRequest.head = @{ ref = $head.ref; sha = $headSha } + + & $expectFailure -Message '*pull request event*exact source repository*' + Should -Invoke gh -Times 0 -Exactly + } + + It 'uses the exact source repository, case-sensitive branch and pushed SHA for a feature push' { + $env:GITHUB_EVENT_NAME = 'push' + $githubEvent = $push + $other = $currentPullRequest.Clone() + $other.number = 43 + $other.head = @{ ref = $head.ref; sha = $headSha; repo = @{ full_name = 'example/other' } } + $openPages = , @($other, $currentPullRequest) + + $result = & $runCalculation + + $result.ReleaseVersion | Should -BeExactly '2.1.0-featurecalc.1' + } + + It 'does not guess a feature push PR when ' -ForEach @( + @{ Case = 'there is no open PR'; Message = '*No open pull request matches*' } + @{ Case = 'the listed PR has a newer SHA'; Message = '*No open pull request matches*' } + @{ Case = 'the listed PR has a different ref case'; Message = '*No open pull request matches*' } + @{ Case = 'the PR changes after lookup'; Message = '*no longer matches*' } + @{ Case = 'the lookup fails'; Message = '*read open pull requests*' } + @{ Case = 'two pages contain an exact match'; Message = '*More than one open pull request*PullRequest*' } + ) { + $env:GITHUB_EVENT_NAME = 'push' + $githubEvent = $push + $other = $currentPullRequest.Clone() + $other.number = 43 + $other.head = $head.Clone() + switch ($Case) { + 'there is no open PR' { $openPages = , @() } + 'the listed PR has a newer SHA' { + $other.head.sha = $mergeSha + $openPages = , (, $other) + } + 'the listed PR has a different ref case' { + $other.head.ref = 'Feature/calc' + $openPages = , (, $other) + } + 'the PR changes after lookup' { + $openPages = , (, $currentPullRequest.Clone()) + $currentPullRequest.head = @{ ref = $head.ref; sha = $mergeSha; repo = $head.repo } + } + 'the lookup fails' { $lookupExitCode = 1 } + 'two pages contain an exact match' { $openPages = @((, $currentPullRequest), (, $other)) } + } + + & $expectFailure -Message $Message + } + + It 'uses a qualified PR selector instead of guessing when a branch has multiple PRs' { + $env:GITHUB_EVENT_NAME = 'push' + $githubEvent = $push + $env:PSMODULE_AUTO_RELEASE_INPUT_PullRequest = "$targetRepository#42" + $lookupExitCode = 1 + + $result = & $runCalculation + + $result.ReleaseVersion | Should -BeExactly '2.1.0-featurecalc.1' + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[1] -ceq "repos/$targetRepository/pulls" } + } + + It 'uses the target repository for a fork push, including a push to the fork default branch' { + $env:GITHUB_EVENT_NAME = 'push' + $env:GITHUB_REPOSITORY = 'contributor/fork' + $env:PSMODULE_AUTO_RELEASE_INPUT_PullRequest = "$targetRepository#42" + $githubEvent = $push + $githubEvent.repository = @{ full_name = $env:GITHUB_REPOSITORY; default_branch = 'trunk'; fork = $true } + $githubEvent.ref = 'refs/heads/trunk' + $head.ref = 'trunk' + $head.repo.full_name = $env:GITHUB_REPOSITORY + + $result = & $runCalculation + + $result.ReleaseVersion | Should -BeExactly '2.1.0-trunk.1' + } + + It 'requires an explicit selector for a fork push' { + $env:GITHUB_EVENT_NAME = 'push' + $env:GITHUB_REPOSITORY = 'contributor/fork' + $githubEvent = $push + $githubEvent.repository = @{ full_name = $env:GITHUB_REPOSITORY; default_branch = 'trunk'; fork = $true } + + & $expectFailure -Message '*fork push*PullRequest*' + } + + It 'does not accept an explicitly selected PR with a stale head SHA' { + $env:GITHUB_EVENT_NAME = 'push' + $githubEvent = $push + $env:PSMODULE_AUTO_RELEASE_INPUT_PullRequest = "$targetRepository#42" + $head.sha = $mergeSha + + & $expectFailure -Message '*no longer matches*' + } + + It 'rejects a push that does not supply a current branch commit' -ForEach @( + @{ Ref = 'refs/tags/v3.0.0'; Deleted = $false } + @{ Ref = 'refs/heads/feature/calc'; Deleted = $true } + ) { + $env:GITHUB_EVENT_NAME = 'push' + $githubEvent = $push + $githubEvent.ref = $Ref + $githubEvent.deleted = $Deleted + + & $expectFailure -Message '*branch push*' + Should -Invoke gh -Times 0 -Exactly + } + + It 'does not use a configured bump as authority for a direct default-branch push' { + $env:GITHUB_EVENT_NAME = 'push' + $githubEvent = $defaultPush + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'patch' + + $result = & $runCalculation + + $result.Decision | Should -BeExactly 'skip' + $result.BumpSource | Should -BeExactly 'no-reviewed-pull-request' + $result.Keys | Should -Not -Contain 'ReleaseVersion' + $result.Keys | Should -Not -Contain 'ReleasePlan' + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[1] -ceq 'graphql' } + } + + It 'does not borrow a decision from a PR merged at another commit' { + $env:GITHUB_EVENT_NAME = 'push' + $githubEvent = $defaultPush + $currentPullRequest.state = 'closed' + $currentPullRequest.merged_at = '2026-01-03T00:00:00Z' + $currentPullRequest.merge_commit_sha = $headSha + $associatedPages = , (, $currentPullRequest) + + $result = & $runCalculation + + $result.Decision | Should -BeExactly 'skip' + $result.Keys | Should -Not -Contain 'ReleaseVersion' + } + + It 'uses labels only from the PR merged to the exact default-branch push' { + $env:GITHUB_EVENT_NAME = 'push' + $githubEvent = $defaultPush + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'patch' + $currentPullRequest.state = 'closed' + $currentPullRequest.merged_at = '2026-01-03T00:00:00Z' + $currentPullRequest.merge_commit_sha = $mergeSha + $currentPullRequest.labels = @(@{ name = 'release:minor' }, @{ name = 'release:prerelease' }) + $wrongBranch = $currentPullRequest.Clone() + $wrongBranch.number = 43 + $wrongBranch.base = @{ ref = 'other'; repo = $base.repo } + $wrongRepository = $currentPullRequest.Clone() + $wrongRepository.number = 44 + $wrongRepository.base = @{ ref = $base.ref; repo = @{ full_name = 'example/other' } } + $associatedPages = , @($wrongBranch, $wrongRepository, $currentPullRequest) + + $result = & $runCalculation + + $result.ReleaseVersion | Should -BeExactly '2.1.0' + } + + It 'uses a configured default for an exact merged PR with no labels' { + $env:GITHUB_EVENT_NAME = 'push' + $githubEvent = $defaultPush + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'patch' + $currentPullRequest.state = 'closed' + $currentPullRequest.merged_at = '2026-01-03T00:00:00Z' + $currentPullRequest.merge_commit_sha = $mergeSha + $currentPullRequest.labels = @() + $associatedPages = , (, $currentPullRequest) + + $result = & $runCalculation + + $result.Decision | Should -BeExactly 'release' + $result.BumpSource | Should -BeExactly 'ActionInput' + $result.ReleaseVersion | Should -BeExactly '2.0.4' + } + + It 'fails a stable push when the exact merged PR has no decision and there is no default' { + $env:GITHUB_EVENT_NAME = 'push' + $githubEvent = $defaultPush + $currentPullRequest.state = 'closed' + $currentPullRequest.merged_at = '2026-01-03T00:00:00Z' + $currentPullRequest.merge_commit_sha = $mergeSha + $currentPullRequest.labels = @() + $associatedPages = , (, $currentPullRequest) + + & $expectFailure -Message '*No release bump*' + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[1] -ceq 'graphql' } + } + + It 'fails when merged PR association lookup fails even with a configured bump' { + $env:GITHUB_EVENT_NAME = 'push' + $githubEvent = $defaultPush + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'patch' + $lookupExitCode = 1 + + & $expectFailure -Message '*read pull requests associated*' + } + + It 'uses the zero baseline only when the repository has no qualifying release' { + $historyResponse.data.repository.latestRelease = $null + + $result = & $runCalculation + + $result.ReleaseVersion | Should -BeExactly '0.1.0-featurecalc.1' + } + + It 'returns an unprefixed version for a ' -ForEach @( + @{ TagCase = 'custom-prefixed baseline'; Prefix = 'product-1.0.0-'; Tag = 'product-1.0.0-2.0.3' } + @{ TagCase = 'baseline from before a prefix change'; Prefix = 'v2.'; Tag = 'v2.0.3' } + ) { + $env:PSMODULE_AUTO_RELEASE_INPUT_VersionPrefix = $Prefix + $latest.tagName = $Tag + + $result = & $runCalculation + + $result.ReleaseVersion | Should -BeExactly '2.1.0-featurecalc.1' + } + + It 'does not expose a decision or version when ' -ForEach @( + @{ Case = 'the history request fails'; Message = '*read release history*' } + @{ Case = 'the history response is missing its baseline field'; Message = '*invalid release history*' } + @{ Case = 'the baseline is not full SemVer'; Message = '*baseline*SemVer*' } + @{ Case = 'the configured date produces invalid SemVer'; Message = '*calculated*not valid SemVer*' } + @{ Case = 'the default bump setting is invalid'; Message = '*Invalid DefaultBump*' } + @{ Case = 'the mode is invalid'; Message = '*Invalid Mode*' } + @{ Case = 'the selector is invalid'; Message = '*Invalid PullRequest*' } + ) { + switch ($Case) { + 'the history request fails' { $historyExitCode = 1 } + 'the history response is missing its baseline field' { $historyResponse.data.repository.Remove('latestRelease') } + 'the baseline is not full SemVer' { $latest.tagName = 'v2.0' } + 'the configured date produces invalid SemVer' { $env:PSMODULE_AUTO_RELEASE_INPUT_DatePrereleaseFormat = 'yyyy/MM' } + 'the default bump setting is invalid' { $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'Patch' } + 'the mode is invalid' { $env:PSMODULE_AUTO_RELEASE_INPUT_Mode = 'unknown' } + 'the selector is invalid' { $env:PSMODULE_AUTO_RELEASE_INPUT_PullRequest = "$targetRepository#-42" } + } + + & $expectFailure -Message $Message + } + + Context 'Publish mode' { + BeforeEach { + $allowSimulatedWrites = $true + $env:PSMODULE_AUTO_RELEASE_INPUT_Mode = 'publish' + $currentPullRequest.labels = @(@{ name = 'release:minor' }, @{ name = 'release:prerelease' }) + $eventPullRequest.labels = $currentPullRequest.labels + $releaseRecords = @($latest.Clone()) + $releaseRecords[0].isLatest = $true + $githubEvent.action = 'opened' + } + + It 'publishes the Calculate plan with the configured prefix at the exact PR head' { + $env:PSMODULE_AUTO_RELEASE_INPUT_VersionPrefix = 'product-' + $result = & $calculateForPublish + $result.ReleaseVersion | Should -BeExactly '2.1.0-featurecalc.1' + $env:PSMODULE_AUTO_RELEASE_INPUT_ReleasePlan = $result.ReleasePlan + + $null = & $runActionStep + + Should -Invoke gh -Times 1 -Exactly -ParameterFilter { + $args[0] -ceq 'release' -and $args[1] -ceq 'create' -and $args -ccontains 'product-2.1.0-featurecalc.1' -and + $args -ccontains '--prerelease' -and $args -ccontains $headSha -and $args -ccontains "github.com/$targetRepository" + } + Should -Invoke gh -Times 1 -Exactly -ParameterFilter { + $args[0] -ceq 'api' -and $args -ccontains 'POST' -and + $args -ccontains 'ref=refs/tags/product-2.1.0-featurecalc.1' -and $args -ccontains "sha=$headSha" + } + } + + It 'calculates on demand with current PR labels when ReleasePlan is omitted' { + $eventPullRequest.labels = @(@{ name = 'release:patch' }) + + $null = & $runActionStep + + Should -Invoke gh -Times 1 -Exactly -ParameterFilter { + $args[0] -ceq 'release' -and $args[1] -ceq 'create' -and $args -ccontains 'v2.1.0-featurecalc.1' -and + $args -ccontains $headSha + } + } + + It 'does not write tags or releases for if label provisioning fails' -ForEach @( + @{ Case = 'a new prerelease'; Replacing = $false } + @{ Case = 'an unnumbered replacement'; Replacing = $true } + ) { + if ($Replacing) { + $env:PSMODULE_AUTO_RELEASE_INPUT_IncrementalPrerelease = 'false' + $tag = 'v2.1.0-featurecalc' + $tagReferences = @(@{ ref = "refs/tags/$tag"; object = @{ sha = $mergeSha; type = 'commit' } }) + $releaseRecords += @{ tagName = $tag; isPrerelease = $true; isDraft = $false } + } + Mock gh { $global:LASTEXITCODE = 1 } -ParameterFilter { $args[0] -ceq 'label' -and $args[1] -ceq 'create' } + + { & $runActionStep } | Should -Throw '*Failed to provision canonical label*' + + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { + ($args[0] -ceq 'release' -and $args[1] -cin @('create', 'delete')) -or + ($args[0] -ceq 'api' -and $args -ccontains 'POST') -or + $args[0] -ceq 'pr' + } + } + + It 'reuses the calculation time in the plan after midnight' { + $clock = [datetime]::new(2026, 1, 3, 23, 59, 0, [DateTimeKind]::Utc) + Mock Get-Date { $clock } -ParameterFilter { $AsUTC } + $env:PSMODULE_AUTO_RELEASE_INPUT_DatePrereleaseFormat = 'yyyy-MM-dd' + $result = & $calculateForPublish + $result.ReleaseVersion | Should -BeExactly '2.1.0-featurecalc.2026-01-03.1' + $timestamp = [regex]::Match([IO.File]::ReadAllText($env:GITHUB_OUTPUT), '"CalculatedAt":\s*"([^"]+)"').Groups[1].Value + $timestamp | Should -BeExactly '2026-01-03T23:59:00.0000000Z' + $env:PSMODULE_AUTO_RELEASE_INPUT_ReleasePlan = $result.ReleasePlan + $clock = $clock.AddMinutes(2) + + $null = & $runActionStep + + Should -Invoke gh -Times 1 -Exactly -ParameterFilter { + $args[0] -ceq 'release' -and $args[1] -ceq 'create' -and + $args -ccontains 'v2.1.0-featurecalc.2026-01-03.1' -and $args -ccontains $headSha + } + } + + It 'rejects before any repository writes' -ForEach @( + @{ Case = 'a malformed plan'; Message = '*Invalid ReleasePlan*' } + @{ Case = 'changed labels'; Message = '*ReleasePlan*does not match*' } + @{ Case = 'changed stable history'; Message = '*ReleasePlan*does not match*' } + @{ Case = 'a changed prefix with the same version'; Message = '*ReleasePlan*does not match*' } + @{ Case = 'a new head with the same version'; Message = '*ReleasePlan*does not match*' } + @{ Case = 'edited notes with the same version'; Message = '*ReleasePlan*does not match*' } + @{ Case = 'another workflow run'; Message = '*ReleasePlan*does not match*' } + @{ Case = 'a stale head'; Message = '*no longer matches*' } + @{ Case = 'a PR without the publication label'; Message = '*release:prerelease*' } + @{ Case = 'a skipped PR'; Message = '*ReleasePlan*release:skip*' } + @{ Case = 'a release request on a PR close'; Message = '*ReleasePlan*not eligible*' } + @{ Case = 'a release request on manual dispatch'; Message = '*ReleasePlan*not eligible*' } + @{ Case = 'an exact tag at a different SHA'; Message = '*tag*v2.1.0-featurecalc.1*target*' } + @{ Case = 'an exact annotated tag'; Message = '*tag*v2.1.0-featurecalc.1*target*' } + @{ Case = 'an unreadable tag'; Message = '*read*tag*v2.1.0-featurecalc.1*' } + @{ Case = 'a malformed tag result'; Message = '*invalid reference*release tag*' } + ) { + $result = & $calculateForPublish + $env:PSMODULE_AUTO_RELEASE_INPUT_ReleasePlan = $result.ReleasePlan + switch ($Case) { + 'a malformed plan' { $env:PSMODULE_AUTO_RELEASE_INPUT_ReleasePlan = '2.1.0-featurecalc.1' } + 'changed labels' { $currentPullRequest.labels = @(@{ name = 'release:major' }, @{ name = 'release:prerelease' }) } + 'changed stable history' { $latest.tagName = 'v2.1.0' } + 'a changed prefix with the same version' { $env:PSMODULE_AUTO_RELEASE_INPUT_VersionPrefix = 'product-' } + 'a new head with the same version' { $head.sha = $mergeSha } + 'edited notes with the same version' { $currentPullRequest.body = 'Edited after Calculate.' } + 'another workflow run' { $env:GITHUB_RUN_ID = '12346' } + 'a stale head' { + $currentPullRequest.head = $head.Clone() + $currentPullRequest.head.sha = $mergeSha + } + 'a PR without the publication label' { $currentPullRequest.labels = @(@{ name = 'release:minor' }) } + 'a skipped PR' { $currentPullRequest.labels = @(@{ name = 'release:skip' }) } + 'a release request on a PR close' { + $githubEvent.action = 'closed' + $eventPullRequest.state = 'closed' + $eventPullRequest.merged = $true + $eventPullRequest.merge_commit_sha = $mergeSha + } + 'a release request on manual dispatch' { + $env:GITHUB_EVENT_NAME = 'workflow_dispatch' + $githubEvent = @{ repository = $repository } + } + 'an exact tag at a different SHA' { + $tagReferences = @(@{ ref = 'refs/tags/v2.1.0-featurecalc.1'; object = @{ sha = $mergeSha; type = 'commit' } }) + } + 'an exact annotated tag' { + $tagReferences = @(@{ ref = 'refs/tags/v2.1.0-featurecalc.1'; object = @{ sha = $headSha; type = 'tag' } }) + } + 'an unreadable tag' { $tagExitCode = 1 } + 'a malformed tag result' { $tagReferences = @(@{ object = @{ sha = $headSha; type = 'commit' } }) } + } + + { & $runActionStep } | Should -Throw $Message + & $expectNoRepositoryWrites + } + + It 'does not confuse a longer ref with the exact version tag' { + $result = & $calculateForPublish + $env:PSMODULE_AUTO_RELEASE_INPUT_ReleasePlan = $result.ReleasePlan + $tagReferences = @(@{ ref = 'refs/tags/v2.1.0-featurecalc.10'; object = @{ sha = $mergeSha; type = 'commit' } }) + + $null = & $runActionStep + + Should -Invoke gh -Times 1 -Exactly -ParameterFilter { + $args[0] -ceq 'release' -and $args[1] -ceq 'create' -and $args -ccontains 'v2.1.0-featurecalc.1' + } + } + + It 'enforces the target when replacing an unnumbered prerelease: ' -ForEach @( + @{ Case = 'same target with exact input'; Supplied = $true; SameTarget = $true } + @{ Case = 'different target without exact input'; Supplied = $false; SameTarget = $false } + @{ Case = 'different target with exact input'; Supplied = $true; SameTarget = $false } + ) { + $env:PSMODULE_AUTO_RELEASE_INPUT_IncrementalPrerelease = 'false' + if ($Supplied) { + $result = & $calculateForPublish + $env:PSMODULE_AUTO_RELEASE_INPUT_ReleasePlan = $result.ReleasePlan + } + $tag = 'v2.1.0-featurecalc' + $existingSha = if ($SameTarget) { $headSha } else { $mergeSha } + $tagReferences = @(@{ ref = "refs/tags/$tag"; object = @{ sha = $existingSha; type = 'commit' } }) + $releaseRecords += @{ tagName = $tag; isPrerelease = $true; isDraft = $false } + + if ($Supplied -and -not $SameTarget) { + { & $runActionStep } | Should -Throw '*Release tag*v2.1.0-featurecalc*validated target*' + & $expectNoRepositoryWrites + return + } + + $null = & $runActionStep + + Should -Invoke gh -Times 1 -Exactly -ParameterFilter { + $args[0] -ceq 'release' -and $args[1] -ceq 'delete' -and $args -ccontains $tag -and + ($args -ccontains '--cleanup-tag') -eq (-not $SameTarget) + } + Should -Invoke gh -Times 1 -Exactly -ParameterFilter { + $args[0] -ceq 'release' -and $args[1] -ceq 'create' -and $args -ccontains $tag -and + $args -ccontains '--verify-tag' -and $args -ccontains $headSha + } + } + + It 'skips publication without a version and without release history' { + $currentPullRequest.labels = @(@{ name = 'release:skip' }) + $historyExitCode = 1 + + $null = & $runActionStep + + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[0] -cin @('release', 'pr') -or $args[1] -ceq 'graphql' } + Should -Invoke git -Times 0 -Exactly + [IO.File]::ReadAllText($env:GITHUB_OUTPUT) | Should -BeExactly '' + } + + It 'publishes the exact default-branch push and its merged PR decision in mode' -ForEach @( + @{ Path = 'single-step'; Staged = $false } + @{ Path = 'staged'; Staged = $true } + ) { + $env:GITHUB_EVENT_NAME = 'push' + $githubEvent = $defaultPush + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'patch' + $currentPullRequest.state = 'closed' + $currentPullRequest.merged_at = '2026-01-03T00:00:00Z' + $currentPullRequest.merge_commit_sha = $mergeSha + $currentPullRequest.title = 'Pin the action and update the release labels' + $currentPullRequest.body = @' +Replace the legacy labels. + +
+Migration guide + +Pin the new action. + +
+'@ + $unrelated = $currentPullRequest.Clone() + $unrelated.number = 43 + $unrelated.merge_commit_sha = $headSha + $associatedPages = , @($unrelated, $currentPullRequest) + if ($Staged) { + $result = & $calculateForPublish + $result.ReleaseVersion | Should -BeExactly '2.1.0' + $env:PSMODULE_AUTO_RELEASE_INPUT_ReleasePlan = $result.ReleasePlan + } + + $null = & $runActionStep + + $expectedNotes = "# $($currentPullRequest.title) (#42)`n`n$($currentPullRequest.body)" + Should -Invoke gh -Times 1 -Exactly -ParameterFilter { + $notesIndex = [array]::IndexOf($args, '--notes') + $targetIndex = [array]::IndexOf($args, '--target') + $args[0] -ceq 'release' -and $args[1] -ceq 'create' -and $args -ccontains 'v2.1.0' -and + $targetIndex -ge 0 -and $args[$targetIndex + 1] -ceq $mergeSha -and $args -cnotcontains '--prerelease' -and + $notesIndex -ge 0 -and $args[$notesIndex + 1] -ceq $expectedNotes + } + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[0] -cin @('label', 'pr') } + } + + It 'does not publish a direct push even when a default bump is configured' { + $env:GITHUB_EVENT_NAME = 'push' + $githubEvent = $defaultPush + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'patch' + $null = & $runActionStep + + & $expectNoRepositoryWrites + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[1] -ceq 'graphql' } + } + + It 'rejects for a push before any repository writes' -ForEach @( + @{ Case = 'a PR plan on a default-branch push'; Message = '*ReleasePlan*does not match*' } + @{ Case = 'a changed default branch'; Message = '*no longer matches the repository default branch*' } + @{ Case = 'a plan on a push with no matching merged PR'; Message = '*ReleasePlan*no*merged pull request*' } + @{ Case = 'a plan on a push with no open PR'; Message = '*ReleasePlan*not eligible*' } + ) { + $result = & $calculateForPublish + $env:PSMODULE_AUTO_RELEASE_INPUT_ReleasePlan = $result.ReleasePlan + $env:GITHUB_EVENT_NAME = 'push' + $githubEvent = $defaultPush + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'patch' + switch ($Case) { + 'a PR plan on a default-branch push' { + $currentPullRequest.state = 'closed' + $currentPullRequest.merged_at = '2026-01-03T00:00:00Z' + $currentPullRequest.merge_commit_sha = $mergeSha + $associatedPages = , (, $currentPullRequest) + } + 'a changed default branch' { $liveDefaultBranch = 'renamed' } + 'a plan on a push with no open PR' { + $githubEvent = $push + $openPages = , @() + } + } + + { & $runActionStep } | Should -Throw $Message + & $expectNoRepositoryWrites + } + + It 'cleans a closed PR prerelease without a bump or a default' { + $githubEvent.action = 'closed' + $eventPullRequest.state = 'closed' + $eventPullRequest.merged = $true + $eventPullRequest.merge_commit_sha = $mergeSha + $eventPullRequest.labels = @() + $releaseRecords += @{ tagName = 'v2.1.0-featurecalc.1'; isPrerelease = $true } + + $null = & $runActionStep + + Should -Invoke gh -Times 1 -Exactly -ParameterFilter { + $args[0] -ceq 'release' -and $args[1] -ceq 'delete' -and $args -ccontains 'v2.1.0-featurecalc.1' + } + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { + $args[0] -ceq 'release' -and $args[1] -ceq 'create' + } + Should -Invoke git -Times 0 -Exactly + } + } +} diff --git a/tests/Release-GHRepository.Helpers.Tests.ps1 b/tests/Release-GHRepository.Helpers.Tests.ps1 new file mode 100644 index 0000000..4869873 --- /dev/null +++ b/tests/Release-GHRepository.Helpers.Tests.ps1 @@ -0,0 +1,1051 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute( + 'PSUseDeclaredVarsMoreThanAssignments', '', + Justification = 'Variables are assigned in BeforeAll and used inside It blocks.' +)] +[CmdletBinding()] +param() + +BeforeAll { + Import-Module -Name powershell-yaml, PSSemVer + $modulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\src\Release-GHRepository.Helpers.psm1' + Import-Module -Name $modulePath -Force + $actionPath = Join-Path -Path $PSScriptRoot -ChildPath '..\action.yml' + $settingMetadata = Get-ReleaseSettingSchema -Path $actionPath + $standardSettings = @{} + foreach ($name in $settingMetadata.Keys) { + $standardSettings[$name] = $settingMetadata[$name].Default + } +} + +Describe 'Resolve-ReleaseConfiguration' { + BeforeAll { + $resolveConfiguration = @{ + Metadata = $settingMetadata + WorkspacePath = $TestDrive + } + } + + It 'resolves the startup setting from repository settings' -ForEach @( + @{ Name = 'Debug'; Value = $true } + @{ Name = 'Verbose'; Value = $true } + @{ Name = 'Prerelease'; Value = $true } + @{ Name = 'Version'; Value = '[0.43.0, 1.0.0)' } + @{ Name = 'WorkingDirectory'; Value = 'TestDrive' } + ) { + if ($Name -eq 'WorkingDirectory') { + $Value = $TestDrive + } + + $result = Resolve-ReleaseConfiguration @resolveConfiguration -Configuration @{ $Name = $Value } + + $result.$Name | Should -Be $Value + $result.$Name.GetType() | Should -Be $Value.GetType() + } + + It 'retains a startup file setting when its input is ' -ForEach @( + @{ InputState = 'null'; InputValue = $null } + @{ InputState = 'empty'; InputValue = '' } + ) { + $configuration = @{ + Debug = $true + Verbose = $true + Prerelease = $true + Version = '[0.43.0, 1.0.0)' + WorkingDirectory = $TestDrive + } + $inputs = @{} + foreach ($name in $configuration.Keys) { + $inputs[$name] = $InputValue + } + + $result = Resolve-ReleaseConfiguration @resolveConfiguration -Configuration $configuration -Inputs $inputs + + foreach ($name in $configuration.Keys) { + $result.$name | Should -Be $configuration[$name] + } + } + + It 'applies false and nonempty startup overrides even when equal to standards' { + $configuration = @{ + Debug = $true + Verbose = $true + Prerelease = $true + Version = '[0.43.0, 1.0.0)' + WorkingDirectory = Join-Path -Path $TestDrive -ChildPath 'execution' + } + $null = New-Item -Path $configuration.WorkingDirectory -ItemType Directory -Force + $inputs = @{ + Debug = 'false' + Verbose = $false + Prerelease = 'FALSE' + Version = '0.43.1' + WorkingDirectory = $TestDrive + } + + $result = Resolve-ReleaseConfiguration @resolveConfiguration -Configuration $configuration -Inputs $inputs + + $result.Debug | Should -BeFalse + $result.Verbose | Should -BeFalse + $result.Prerelease | Should -BeFalse + $result.Version | Should -BeExactly '0.43.1' + $result.WorkingDirectory | Should -BeExactly $TestDrive + } + + It 'applies every documented controller default when settings are omitted' { + $result = Resolve-ReleaseConfiguration @resolveConfiguration + $expected = [ordered]@{ + Mode = 'publish' + PullRequest = '' + AutoCleanup = $true + DefaultBump = 'none' + CreateMajorTag = $true + CreateMinorTag = $true + DatePrereleaseFormat = '' + IncrementalPrerelease = $true + UsePRTitleAsReleaseName = $false + UsePRBodyAsReleaseNotes = $true + UsePRTitleAsNotesHeading = $true + VersionPrefix = 'v' + WhatIf = $false + Debug = $false + Verbose = $false + WorkingDirectory = $TestDrive + Version = '' + Prerelease = $false + } + + $result.PSObject.Properties.Name | Should -Be (@($expected.Keys) + 'DefaultBumpSource') + $result.DefaultBumpSource | Should -BeExactly 'SharedDefault' + foreach ($name in $expected.Keys) { + $result.$name | Should -Be $expected[$name] -Because "[$name] has a documented default" + $result.$name.GetType() | Should -Be $expected[$name].GetType() + } + } + + It 'uses a caller DefaultBump when the file omits it' { + $result = Resolve-ReleaseConfiguration @resolveConfiguration -Inputs @{ DefaultBump = 'minor' } -Configuration @{} + $decision = Resolve-ReleaseDecision -Labels @() -DefaultBump $result.DefaultBump + + $decision.Bump | Should -BeExactly 'Minor' + $decision.DefaultBumpApplied | Should -BeTrue + } + + It 'lets named inputs override repository settings without mutating either mapping' { + $inputs = @{ DefaultBump = 'patch'; AutoCleanup = 'true'; VersionPrefix = 'v' } + $configuration = [ordered]@{ DefaultBump = 'major'; AutoCleanup = $false; VersionPrefix = '' } + + $result = Resolve-ReleaseConfiguration @resolveConfiguration -Inputs $inputs -Configuration $configuration + $decision = Resolve-ReleaseDecision -Labels @() -DefaultBump $result.DefaultBump + + $decision.Bump | Should -BeExactly 'Patch' + $result.DefaultBumpSource | Should -BeExactly 'ActionInput' + $result.AutoCleanup | Should -BeTrue + $result.VersionPrefix | Should -BeExactly 'v' + $inputs.DefaultBump | Should -BeExactly 'patch' + $inputs.AutoCleanup | Should -BeExactly 'true' + $configuration.DefaultBump | Should -BeExactly 'major' + $configuration.AutoCleanup | Should -BeFalse + $configuration.Count | Should -Be 3 + } + + It 'lets release:minor override the effective configured default' { + $result = Resolve-ReleaseConfiguration @resolveConfiguration -Configuration @{ DefaultBump = 'major' } + $decision = Resolve-ReleaseDecision -Labels @('release:minor') -DefaultBump $result.DefaultBump + + $decision.Bump | Should -BeExactly 'Minor' + $decision.DefaultBumpApplied | Should -BeFalse + } + + It 'keeps file text when the named input is empty for ' -ForEach @( + @{ Name = 'VersionPrefix'; Configured = 'repo-' } + @{ Name = 'DatePrereleaseFormat'; Configured = 'yyyyMMdd' } + ) { + $result = Resolve-ReleaseConfiguration @resolveConfiguration -Inputs @{ $Name = '' } -Configuration @{ $Name = $Configured } + + $result.$Name | Should -BeExactly $Configured + } + + It 'preserves an empty repository value when the named input is omitted for ' -ForEach @( + @{ Name = 'VersionPrefix' } + @{ Name = 'DatePrereleaseFormat' } + ) { + $result = Resolve-ReleaseConfiguration @resolveConfiguration -Configuration @{ $Name = '' } -Inputs @{ $Name = '' } + + $result.$Name | Should -BeExactly '' + } + + It 'accepts boolean values and case-insensitive true/false strings for every boolean setting' { + $names = @( + 'AutoCleanup' + 'CreateMajorTag' + 'CreateMinorTag' + 'IncrementalPrerelease' + 'UsePRTitleAsReleaseName' + 'UsePRBodyAsReleaseNotes' + 'UsePRTitleAsNotesHeading' + 'WhatIf' + 'Debug' + 'Verbose' + 'Prerelease' + ) + + foreach ($name in $names) { + foreach ($value in @($true, $false, 'true', 'false', 'TRUE', 'FALSE')) { + $result = Resolve-ReleaseConfiguration @resolveConfiguration -Configuration @{ $name = $value } + + $result.$name | Should -BeOfType ([bool]) + $result.$name | Should -Be ($value.ToString() -eq 'true') + } + } + } + + It 'rejects invalid boolean setting []' -ForEach @( + @{ Value = '' } + @{ Value = 'yes' } + @{ Value = ' true ' } + @{ Value = 1 } + @{ Value = $null } + @{ Value = @('true', 'false') } + ) { + { Resolve-ReleaseConfiguration @resolveConfiguration -Configuration @{ WhatIf = $Value } } | + Should -Throw '*WhatIf*true or false*' + } + + It 'rejects an explicit invalid DefaultBump []' -ForEach @( + @{ Value = '' } + @{ Value = $null } + @{ Value = 'Patch' } + @{ Value = 'date' } + @{ Value = 'NONE' } + @{ Value = 1 } + @{ Value = @('patch', 'minor') } + ) { + { Resolve-ReleaseConfiguration @resolveConfiguration -Configuration @{ DefaultBump = $Value } } | + Should -Throw '*DefaultBump*' + } + + It 'rejects an invalid named input' { + { Resolve-ReleaseConfiguration @resolveConfiguration -Inputs @{ DefaultBump = 'invalid' } } | + Should -Throw '*DefaultBump*' + } + + It 'rejects an invalid named input even when the repository value is valid' { + $parameters = @{ + Inputs = @{ DefaultBump = 'invalid' } + Configuration = @{ DefaultBump = 'minor' } + } + { Resolve-ReleaseConfiguration @resolveConfiguration @parameters } | + Should -Throw '*DefaultBump*' + } + + It 'lets a named DefaultBump override repository settings' { + $parameters = @{ + Inputs = @{ DefaultBump = 'minor' } + Configuration = @{ DefaultBump = 'major' } + } + + $result = Resolve-ReleaseConfiguration @resolveConfiguration @parameters + + $result.DefaultBump | Should -BeExactly 'minor' + $result.DefaultBumpSource | Should -BeExactly 'ActionInput' + } + + It 'inherits repository settings when no named input is supplied' { + $parameters = @{ + Inputs = @{} + Configuration = @{ DefaultBump = 'major' } + } + + $result = Resolve-ReleaseConfiguration @resolveConfiguration @parameters + + $result.DefaultBump | Should -BeExactly 'major' + $result.DefaultBumpSource | Should -BeExactly 'RepositorySetting' + } + + It 'keeps repository policy when the named bump is ' -ForEach @( + @{ InputState = 'null'; InputValue = $null } + @{ InputState = 'empty'; InputValue = '' } + ) { + $parameters = @{ + Inputs = @{ DefaultBump = $InputValue } + Configuration = @{ DefaultBump = 'major' } + } + + $result = Resolve-ReleaseConfiguration @resolveConfiguration @parameters + + $result.DefaultBump | Should -BeExactly 'major' + $result.DefaultBumpSource | Should -BeExactly 'RepositorySetting' + } + + It 'records the action input as the default source even when it equals the shared default' { + $result = Resolve-ReleaseConfiguration @resolveConfiguration -Inputs @{ DefaultBump = 'none' } + + $result.DefaultBump | Should -BeExactly 'none' + $result.DefaultBumpSource | Should -BeExactly 'ActionInput' + } + + It 'lets a caller supply a bump when the settings file selects none' { + $result = Resolve-ReleaseConfiguration @resolveConfiguration -Configuration @{ DefaultBump = 'none' } -Inputs @{ DefaultBump = 'minor' } + $decisionParameters = @{ + Labels = @('release:prerelease') + DefaultBump = $result.DefaultBump + DefaultBumpSource = $result.DefaultBumpSource + } + $decision = Resolve-ReleaseDecision @decisionParameters + + $decision.Bump | Should -BeExactly 'Minor' + $decision.BumpSource | Should -BeExactly 'ActionInput' + $decision.Prerelease | Should -BeTrue + } + + It 'records a nondefault named input as the decision source' { + $result = Resolve-ReleaseConfiguration @resolveConfiguration -Inputs @{ DefaultBump = 'minor' } + + $result.DefaultBump | Should -BeExactly 'minor' + $result.DefaultBumpSource | Should -BeExactly 'ActionInput' + } + + It 'preserves explicit false while null and empty inputs keep file text' { + $parameters = @{ + Configuration = @{ AutoCleanup = $true; VersionPrefix = 'v'; DatePrereleaseFormat = 'yyyyMMdd' } + Inputs = @{ AutoCleanup = $false; VersionPrefix = $null; DatePrereleaseFormat = '' } + } + + $result = Resolve-ReleaseConfiguration @resolveConfiguration @parameters + + $result.AutoCleanup | Should -BeFalse + $result.VersionPrefix | Should -BeExactly 'v' + $result.DatePrereleaseFormat | Should -BeExactly 'yyyyMMdd' + } + + It 'rejects an invalid repository value even when the caller supplies a valid override' { + $parameters = @{ + Configuration = @{ DefaultBump = 'invalid' } + Inputs = @{ DefaultBump = 'patch' } + } + + { Resolve-ReleaseConfiguration @resolveConfiguration @parameters } | + Should -Throw '*DefaultBump*' + } + + It 'rejects named input settings []' -ForEach @( + @{ Name = 'DefaultBump'; Value = ' '; Message = '*DefaultBump*' } + @{ Name = 'DefaultBump'; Value = 'date'; Message = '*DefaultBump*' } + @{ Name = 'DefaultBump'; Value = 'inherit'; Message = '*DefaultBump*' } + @{ Name = 'AutoCleanup'; Value = 'invalid'; Message = '*AutoCleanup*true or false*' } + @{ Name = 'AutoCleanup'; Value = ' '; Message = '*AutoCleanup*true or false*' } + @{ Name = 'AutoCleanup'; Value = 'inherit'; Message = '*AutoCleanup*true or false*' } + @{ Name = 'AutoCleanup'; Value = 0; Message = '*AutoCleanup*true or false*' } + @{ Name = 'AutoPatching'; Value = $true; Message = '*AutoPatching*removed*' } + @{ Name = 'AutoPatching'; Value = $null; Message = '*AutoPatching*removed*' } + @{ Name = 'DefaultBunp'; Value = 'minor'; Message = '*Unsupported release setting*' } + @{ Name = 'DefaultBunp'; Value = ''; Message = '*Unsupported release setting*' } + ) { + { Resolve-ReleaseConfiguration @resolveConfiguration -Inputs @{ $Name = $Value } } | + Should -Throw $Message + } + + It 'rejects literal inherit as an invalid repository bump even with a valid input' { + $parameters = @{ + Configuration = @{ DefaultBump = 'inherit' } + Inputs = @{ DefaultBump = 'minor' } + } + + { Resolve-ReleaseConfiguration @resolveConfiguration @parameters } | + Should -Throw '*Invalid DefaultBump*' + } + + It 'rejects null and non-string text settings instead of coercing them' -ForEach @( + @{ Name = 'VersionPrefix'; Value = $null } + @{ Name = 'VersionPrefix'; Value = 1 } + @{ Name = 'DatePrereleaseFormat'; Value = $false } + @{ Name = 'DatePrereleaseFormat'; Value = @{ format = 'yyyyMMdd' } } + ) { + { Resolve-ReleaseConfiguration @resolveConfiguration -Configuration @{ $Name = $Value } } | + Should -Throw "*$Name*string*" + } + + It 'rejects an invalid prerelease date format before publication is considered' { + { Resolve-ReleaseConfiguration @resolveConfiguration -Configuration @{ DatePrereleaseFormat = '%' } } | + Should -Throw '*DatePrereleaseFormat*format*' + } + + It 'rejects the retired setting with migration guidance' -ForEach @( + @{ Name = 'AutoPatching' } + @{ Name = 'IgnoreLabels' } + @{ Name = 'MajorLabels' } + @{ Name = 'MinorLabels' } + @{ Name = 'PatchLabels' } + ) { + { Resolve-ReleaseConfiguration @resolveConfiguration -Configuration @{ $Name = 'legacy' } } | + Should -Throw "*$Name*removed*DefaultBump*release:*" + } + + It 'rejects an unknown setting instead of silently ignoring a typo' { + { Resolve-ReleaseConfiguration @resolveConfiguration -Configuration @{ DefaultBunp = 'minor' } } | + Should -Throw '*Unsupported release setting*DefaultBunp*' + } + + It 'rejects a configuration root that is not a mapping' -ForEach @( + @{ Configuration = 'DefaultBump: minor' } + @{ Configuration = @('patch', 'minor') } + @{ Configuration = $true } + ) { + { Resolve-ReleaseConfiguration @resolveConfiguration -Configuration $Configuration } | + Should -Throw '*configuration must be a mapping*' + } +} + +Describe 'Get-ReleaseLabelDefinition' { + BeforeAll { + $definitions = @(Get-ReleaseLabelDefinition) + } + + It 'returns exactly the five canonical labels' { + $definitions.Name | Should -Be @( + 'release:patch' + 'release:minor' + 'release:major' + 'release:prerelease' + 'release:skip' + ) + } + + It 'returns a unique name for every definition' { + @($definitions.Name | Sort-Object -Unique).Count | Should -Be $definitions.Count + } + + It 'returns valid repository metadata for ' -ForEach @( + @{ Name = 'release:patch' } + @{ Name = 'release:minor' } + @{ Name = 'release:major' } + @{ Name = 'release:prerelease' } + @{ Name = 'release:skip' } + ) { + $definition = $definitions | Where-Object Name -CEQ $Name + + $definition.Color | Should -Match '^[0-9a-f]{6}$' + $definition.Description | Should -Not -BeNullOrEmpty + $definition.Description.Length | Should -BeLessOrEqual 100 + } +} + +Describe 'Get-PrereleaseCleanupCandidate' { + BeforeAll { + $releases = @( + [PSCustomObject]@{ + tagName = 'v1.2.3-123.1' + isPrerelease = $true + } + [PSCustomObject]@{ + tagName = 'v1.2.3-123' + isPrerelease = $true + } + [PSCustomObject]@{ + tagName = 'v1.2.3-1234.1' + isPrerelease = $true + } + [PSCustomObject]@{ + tagName = 'v1.2.3-other.123.1' + isPrerelease = $true + } + [PSCustomObject]@{ + tagName = 'v1.2.3' + isPrerelease = $false + } + [PSCustomObject]@{ + tagName = 'v123.0.0' + isPrerelease = $false + } + [PSCustomObject]@{ + tagName = 'v1.2.3-123.2' + isPrerelease = $false + } + ) + } + + It 'returns only prereleases with the exact numeric identifier segment' { + $result = @(Get-PrereleaseCleanupCandidate -Releases $releases -PrereleaseName '123' -VersionPrefix 'v') + + $result.tagName | Should -Be @('v1.2.3-123.1', 'v1.2.3-123') + } + + It 'uses the actual version boundary for ' -ForEach @( + @{ + PrefixCase = 'an own-branch release after version-like prefix text' + Prefix = 'release-1.2.3-' + Branch = 'feature' + ExpectedTag = 'release-1.2.3-2.0.4-feature.1' + ExpectedCount = 1 + } + @{ + PrefixCase = 'another branch after identifier-like prefix text' + Prefix = 'release-1.2.3-feature.extra-' + Branch = 'other' + ExpectedTag = 'release-1.2.3-feature.extra-2.0.4-other.1' + ExpectedCount = 0 + } + ) { + $parameters = @{ + Metadata = $settingMetadata + WorkspacePath = $TestDrive + Configuration = @{ VersionPrefix = $Prefix } + } + $settings = Resolve-ReleaseConfiguration @parameters + $version = New-PSSemVer -Version '2.0.4' + $version.Prefix = $settings.VersionPrefix + $version.Prerelease = $Branch + $version.BumpPrereleaseNumber() + $tagName = $version.ToString() + $tagName | Should -BeExactly $ExpectedTag + $records = @([PSCustomObject]@{ tagName = $tagName; isPrerelease = $true }) + + $result = @( + Get-PrereleaseCleanupCandidate -Releases $records -PrereleaseName 'feature' -VersionPrefix $settings.VersionPrefix + ) + + $result.Count | Should -Be $ExpectedCount + if ($ExpectedCount -eq 1) { + $result[0].tagName | Should -BeExactly $ExpectedTag + } + } + + It 'never returns stable releases whose versions overlap the identifier' { + $result = @(Get-PrereleaseCleanupCandidate -Releases $releases -PrereleaseName '123' -VersionPrefix 'v') + + $result | Where-Object { -not $_.isPrerelease } | Should -BeNullOrEmpty + $result.tagName | Should -Not -Contain 'v1.2.3' + $result.tagName | Should -Not -Contain 'v123.0.0' + $result.tagName | Should -Not -Contain 'v1.2.3-123.2' + } + + It 'does not match a longer or later prerelease identifier segment' { + $result = @(Get-PrereleaseCleanupCandidate -Releases $releases -PrereleaseName '123' -VersionPrefix 'v') + + $result.tagName | Should -Not -Contain 'v1.2.3-1234.1' + $result.tagName | Should -Not -Contain 'v1.2.3-other.123.1' + } + + It 'escapes regular-expression characters in the identifier' { + $regexReleases = @( + [PSCustomObject]@{ + tagName = 'v1.2.3-feature.test.1' + isPrerelease = $true + } + [PSCustomObject]@{ + tagName = 'v1.2.3-featureXtest.1' + isPrerelease = $true + } + ) + + $result = @( + Get-PrereleaseCleanupCandidate -Releases $regexReleases -PrereleaseName 'feature.test' -VersionPrefix 'v' + ) + + $result.tagName | Should -Be @('v1.2.3-feature.test.1') + } + + It 'never matches a name after the first SemVer prerelease separator' { + $tagNames = @( + 'v1.2.3-other-feature.1' + 'v1.2.3-other.1-feature.2' + 'v1.2.3-other-v4.5.6-feature.1' + 'v1.2.3-feature.1' + ) + $records = @($tagNames | ForEach-Object { [PSCustomObject]@{ tagName = $_; isPrerelease = $true } }) + + $result = @(Get-PrereleaseCleanupCandidate -Releases $records -PrereleaseName 'feature' -VersionPrefix 'v') + + $result.tagName | Should -Be @('v1.2.3-feature.1') + } + + It 'distinguishes case-sensitive branch identifiers' { + $records = @( + [PSCustomObject]@{ tagName = 'v1.2.3-Feature.1'; isPrerelease = $true } + [PSCustomObject]@{ tagName = 'v1.2.3-feature.1'; isPrerelease = $true } + ) + + $result = @(Get-PrereleaseCleanupCandidate -Releases $records -PrereleaseName 'Feature' -VersionPrefix 'v') + + $result.tagName | Should -Be @('v1.2.3-Feature.1') + } + + It 'ignores non-version tags and invalid version cores' { + $records = @( + [PSCustomObject]@{ tagName = 'notes-feature.1'; isPrerelease = $true } + [PSCustomObject]@{ tagName = 'v01.2.3-feature.1'; isPrerelease = $true } + ) + + @(Get-PrereleaseCleanupCandidate -Releases $records -PrereleaseName 'feature' -VersionPrefix 'v') | + Should -BeNullOrEmpty + } + + It 'retains cleanup with the effective prefix' -ForEach @( + @{ PrefixCase = 'empty'; Prefix = ''; ExpectedTag = '1.2.3-feature.1' } + @{ PrefixCase = 'hyphenated'; Prefix = 'release-v'; ExpectedTag = 'release-v1.2.3-feature.2' } + ) { + $records = @( + [PSCustomObject]@{ tagName = '1.2.3-feature.1'; isPrerelease = $true } + [PSCustomObject]@{ tagName = 'release-v1.2.3-feature.2'; isPrerelease = $true } + ) + + $result = @(Get-PrereleaseCleanupCandidate -Releases $records -PrereleaseName 'feature' -VersionPrefix $Prefix) + + $result.tagName | Should -Be @($ExpectedTag) + } + + It 'retains releases under historical prefixes rather than guessing their version boundary' { + $records = @( + [PSCustomObject]@{ tagName = 'v1.2.3-feature.1'; isPrerelease = $true } + [PSCustomObject]@{ tagName = 'release-1.2.3-2.0.4-feature.1'; isPrerelease = $true } + ) + + $result = @(Get-PrereleaseCleanupCandidate -Releases $records -PrereleaseName 'feature' -VersionPrefix 'release-1.2.3-') + + $result.tagName | Should -Be @('release-1.2.3-2.0.4-feature.1') + } + + It 'returns no candidates for an empty release list' { + $result = @(Get-PrereleaseCleanupCandidate -Releases @() -PrereleaseName 'feature' -VersionPrefix 'v') + + $result | Should -BeNullOrEmpty + } +} + +Describe 'ConvertTo-ReleaseBump' { + It 'converts to ' -ForEach @( + @{ DefaultBump = 'none'; Expected = 'None' } + @{ DefaultBump = 'patch'; Expected = 'Patch' } + @{ DefaultBump = 'minor'; Expected = 'Minor' } + @{ DefaultBump = 'major'; Expected = 'Major' } + ) { + ConvertTo-ReleaseBump -DefaultBump $DefaultBump | Should -BeExactly $Expected + } + + It 'rejects omitted policy instead of selecting its own patch fallback' { + { ConvertTo-ReleaseBump } | Should -Throw '*Invalid DefaultBump*' + } + + It 'rejects invalid DefaultBump []' -ForEach @( + @{ DefaultBump = '' } + @{ DefaultBump = 'Patch' } + @{ DefaultBump = 'prerelease' } + @{ DefaultBump = 'None' } + @{ DefaultBump = $null } + ) { + { ConvertTo-ReleaseBump -DefaultBump $DefaultBump } | + Should -Throw '*Invalid DefaultBump*patch, minor, major*' + } +} + +Describe 'Resolve-ReleaseDecision' { + It 'resolves ' -ForEach @( + @{ + Name = 'a patch release' + Labels = @('release:patch') + Bump = 'Patch' + Prerelease = $false + Skip = $false + } + @{ + Name = 'a minor release' + Labels = @('release:minor') + Bump = 'Minor' + Prerelease = $false + Skip = $false + } + @{ + Name = 'a major release' + Labels = @('release:major') + Bump = 'Major' + Prerelease = $false + Skip = $false + } + @{ + Name = 'a patch prerelease' + Labels = @('release:patch', 'release:prerelease') + Bump = 'Patch' + Prerelease = $true + Skip = $false + } + @{ + Name = 'a minor prerelease' + Labels = @('release:minor', 'release:prerelease') + Bump = 'Minor' + Prerelease = $true + Skip = $false + } + @{ + Name = 'a major prerelease' + Labels = @('release:major', 'release:prerelease') + Bump = 'Major' + Prerelease = $true + Skip = $false + } + @{ + Name = 'a skipped release' + Labels = @('release:skip') + Bump = 'None' + Prerelease = $false + Skip = $true + } + @{ + Name = 'a bump alongside unrelated labels' + Labels = @('dependencies', 'release:patch', 'release:unknown') + Bump = 'Patch' + Prerelease = $false + Skip = $false + } + @{ + Name = 'a skip alongside unrelated labels' + Labels = @('documentation', 'release:skip', 'release:unknown') + Bump = 'None' + Prerelease = $false + Skip = $true + } + ) { + $result = Resolve-ReleaseDecision -Labels $Labels -DefaultBump $standardSettings.DefaultBump + + $result.Bump | Should -BeExactly $Bump + $result.Prerelease | Should -Be $Prerelease + $result.Skip | Should -Be $Skip + $result.DefaultBumpApplied | Should -BeFalse + } + + It 'rejects ' -ForEach @( + @{ + Name = 'patch and minor bumps' + Labels = @('release:patch', 'release:minor') + Message = '*Conflicting release bump labels*' + } + @{ + Name = 'minor and major bumps' + Labels = @('release:minor', 'release:major') + Message = '*Conflicting release bump labels*' + } + @{ + Name = 'all bump labels' + Labels = @('release:patch', 'release:minor', 'release:major') + Message = '*Conflicting release bump labels*' + } + @{ + Name = 'skip and patch' + Labels = @('release:skip', 'release:patch') + Message = '*release:skip must not be combined*' + } + @{ + Name = 'skip and prerelease' + Labels = @('release:skip', 'release:prerelease') + Message = '*release:skip must not be combined*' + } + ) { + { Resolve-ReleaseDecision -Labels $Labels -DefaultBump $standardSettings.DefaultBump } | Should -Throw $Message + } + + It 'requires resolved policy even with ' -ForEach @( + @{ LabelState = 'no release label'; Labels = @() } + @{ LabelState = 'release:major'; Labels = @('release:major') } + ) { + { Resolve-ReleaseDecision -Labels $Labels } | Should -Throw '*Invalid DefaultBump*' + } + + It 'resolves from with the default' -ForEach @( + @{ + Name = 'an empty label set' + Labels = @() + DefaultBump = 'patch' + Expected = 'Patch' + Prerelease = $false + } + @{ + Name = 'a null label set' + Labels = $null + DefaultBump = 'minor' + Expected = 'Minor' + Prerelease = $false + } + @{ + Name = 'legacy bare labels' + Labels = @('Major', 'Minor', 'Patch', 'Prerelease', 'NoRelease') + DefaultBump = 'major' + Expected = 'Major' + Prerelease = $false + } + @{ + Name = 'lowercase bare labels' + Labels = @('major', 'minor', 'patch', 'prerelease') + DefaultBump = 'patch' + Expected = 'Patch' + Prerelease = $false + } + @{ + Name = 'noncanonical casing' + Labels = @('Release:Patch') + DefaultBump = 'minor' + Expected = 'Minor' + Prerelease = $false + } + @{ + Name = 'an unknown release label' + Labels = @('release:unknown') + DefaultBump = 'major' + Expected = 'Major' + Prerelease = $false + } + @{ + Name = 'the retired release:pre-release label' + Labels = @('release:pre-release') + DefaultBump = 'patch' + Expected = 'Patch' + Prerelease = $false + } + @{ + Name = 'prerelease without an explicit bump' + Labels = @('release:prerelease') + DefaultBump = 'minor' + Expected = 'Minor' + Prerelease = $true + } + ) { + $result = Resolve-ReleaseDecision -Labels $Labels -DefaultBump $DefaultBump + + $result.Bump | Should -BeExactly $Expected + $result.Prerelease | Should -Be $Prerelease + $result.Skip | Should -BeFalse + $result.DefaultBumpApplied | Should -BeTrue + } + + It 'applies each valid default to unlabeled and prerelease-only decisions' { + $expectedBumps = @{ + patch = 'Patch' + minor = 'Minor' + major = 'Major' + } + + foreach ($defaultBump in @('patch', 'minor', 'major')) { + foreach ($labels in @(@(), @('release:prerelease'))) { + $result = Resolve-ReleaseDecision -Labels $labels -DefaultBump $defaultBump + + $result.Bump | Should -BeExactly $expectedBumps[$defaultBump] + $result.Prerelease | Should -Be ($labels -ccontains 'release:prerelease') + $result.DefaultBumpApplied | Should -BeTrue + } + } + } + + It 'lets every explicit bump label override every valid default' { + $explicitBumps = [ordered]@{ + 'release:patch' = 'Patch' + 'release:minor' = 'Minor' + 'release:major' = 'Major' + } + + foreach ($defaultBump in @('patch', 'minor', 'major')) { + foreach ($entry in $explicitBumps.GetEnumerator()) { + $result = Resolve-ReleaseDecision -Labels @($entry.Key) -DefaultBump $defaultBump + + $result.Bump | Should -BeExactly $entry.Value + $result.DefaultBumpApplied | Should -BeFalse + } + } + } + + It 'lets release:skip override every valid default' { + foreach ($defaultBump in @('patch', 'minor', 'major')) { + $result = Resolve-ReleaseDecision -Labels @('release:skip') -DefaultBump $defaultBump + + $result.Bump | Should -BeExactly 'None' + $result.Skip | Should -BeTrue + $result.DefaultBumpApplied | Should -BeFalse + } + } + + It 'validates DefaultBump before applying an explicit decision' { + { Resolve-ReleaseDecision -Labels @('release:patch') -DefaultBump 'Patch' } | + Should -Throw '*Invalid DefaultBump*' + } + + It 'accepts exactly the nine valid subsets for every default bump' { + $supportedReleaseLabels = @( + 'release:patch' + 'release:minor' + 'release:major' + 'release:prerelease' + 'release:skip' + ) + $validSubsets = @( + '' + 'release:prerelease' + 'release:patch' + 'release:minor' + 'release:major' + 'release:patch,release:prerelease' + 'release:minor,release:prerelease' + 'release:major,release:prerelease' + 'release:skip' + ) + + foreach ($defaultBump in @('patch', 'minor', 'major')) { + for ($mask = 0; $mask -lt (1 -shl $supportedReleaseLabels.Count); $mask++) { + $labels = @( + for ($index = 0; $index -lt $supportedReleaseLabels.Count; $index++) { + if (($mask -band (1 -shl $index)) -ne 0) { + $supportedReleaseLabels[$index] + } + } + ) + $subset = ($labels | Sort-Object) -join ',' + + if ($validSubsets -ccontains $subset) { + { Resolve-ReleaseDecision -Labels $labels -DefaultBump $defaultBump } | + Should -Not -Throw -Because "[$subset] is valid with DefaultBump [$defaultBump]" + } else { + { Resolve-ReleaseDecision -Labels $labels -DefaultBump $defaultBump } | + Should -Throw -Because "[$subset] is not a valid release decision" + } + } + } + } + + Describe 'Resolve-PullRequestReleaseContext' { + It 'uses the branch for naming and the exact head SHA for the release target' { + $headSha = '0123456789012345678901234567890123456789' + $pullRequest = [PSCustomObject]@{ + head = [PSCustomObject]@{ + ref = 'feature/fork-release' + sha = $headSha + } + } + + $result = Resolve-PullRequestReleaseContext -PullRequest $pullRequest + + $result.HeadRef | Should -BeExactly 'feature/fork-release' + $result.PrereleaseName | Should -BeExactly 'featureforkrelease' + $result.PrereleaseTarget | Should -BeExactly $headSha + } + + It 'does not use a colliding base-repository branch name as the release target' { + $headSha = 'abcdefabcdefabcdefabcdefabcdefabcdefabcd' + $pullRequest = [PSCustomObject]@{ + head = [PSCustomObject]@{ + ref = 'main' + sha = $headSha + } + } + + $result = Resolve-PullRequestReleaseContext -PullRequest $pullRequest + + $result.PrereleaseName | Should -BeExactly 'main' + $result.PrereleaseTarget | Should -BeExactly $headSha + $result.PrereleaseTarget | Should -Not -BeExactly $result.HeadRef + } + + It 'rejects a pull request without a head ref' { + $pullRequest = [PSCustomObject]@{ + head = [PSCustomObject]@{ + ref = '' + sha = '0123456789012345678901234567890123456789' + } + } + + { Resolve-PullRequestReleaseContext -PullRequest $pullRequest } | + Should -Throw '*head ref is required*' + } + + It 'rejects a pull request without a head SHA' { + $pullRequest = [PSCustomObject]@{ + head = [PSCustomObject]@{ + ref = 'feature/missing-sha' + sha = '' + } + } + + { Resolve-PullRequestReleaseContext -PullRequest $pullRequest } | + Should -Throw '*head SHA is required*' + } + + It 'rejects a mutable or malformed head SHA []' -ForEach @( + @{ HeadSha = 'main' } + @{ HeadSha = 'abcdef' } + @{ HeadSha = '012345678901234567890123456789012345678g' } + @{ HeadSha = "0123456789012345678901234567890123456789`n" } + ) { + $pullRequest = [PSCustomObject]@{ + head = [PSCustomObject]@{ + ref = 'feature/invalid-sha' + sha = $HeadSha + } + } + + { Resolve-PullRequestReleaseContext -PullRequest $pullRequest } | + Should -Throw '*head SHA must be a 40-character hexadecimal commit*' + } + + It 'rejects a head ref that has no valid prerelease identifier' { + $pullRequest = [PSCustomObject]@{ + head = [PSCustomObject]@{ + ref = '---' + sha = '0123456789012345678901234567890123456789' + } + } + + { Resolve-PullRequestReleaseContext -PullRequest $pullRequest } | + Should -Throw '*does not contain a valid prerelease identifier*' + } + + It 'allows a valid non-prerelease branch without an ASCII prerelease identifier' { + $headRef = ([char] 0x2603).ToString() + $pullRequest = [PSCustomObject]@{ + head = [PSCustomObject]@{ + ref = $headRef + sha = '0123456789012345678901234567890123456789' + } + } + + $result = Resolve-PullRequestReleaseContext -PullRequest $pullRequest -AllowEmptyPrereleaseName + + $result.HeadRef | Should -BeExactly $headRef + $result.PrereleaseName | Should -BeExactly '' + } + } + + Describe 'Test-PrereleaseCreation' { + It 'returns for ' -ForEach @( + @{ + Name = 'an open prerelease pull request' + Labels = @('release:patch', 'release:prerelease') + Closed = $false + Expected = $true + } + @{ + Name = 'a closed prerelease pull request' + Labels = @('release:patch', 'release:prerelease') + Closed = $true + Expected = $false + } + @{ + Name = 'an open stable pull request' + Labels = @('release:patch') + Closed = $false + Expected = $false + } + @{ + Name = 'a closed stable pull request' + Labels = @('release:patch') + Closed = $true + Expected = $false + } + @{ + Name = 'an open skipped pull request' + Labels = @('release:skip') + Closed = $false + Expected = $false + } + ) { + $decision = Resolve-ReleaseDecision -Labels $Labels -DefaultBump $standardSettings.DefaultBump + $result = Test-PrereleaseCreation -ReleaseDecision $decision -PullRequestClosed:$Closed + + $result | Should -Be $Expected + } + } +} diff --git a/tests/Release-GHRepository.Tests.ps1 b/tests/Release-GHRepository.Tests.ps1 new file mode 100644 index 0000000..4fe0a48 --- /dev/null +++ b/tests/Release-GHRepository.Tests.ps1 @@ -0,0 +1,1106 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute( + 'PSUseDeclaredVarsMoreThanAssignments', '', + Justification = 'Variables are assigned in Pester setup and used by tests and mocks.' +)] +[CmdletBinding()] +param() + +$ErrorActionPreference = 'Stop' + +BeforeAll { + Import-Module -Name GitHub, powershell-yaml, PSSemVer + $mainPath = Join-Path -Path $PSScriptRoot -ChildPath '..\src\main.ps1' + $planPath = Join-Path -Path $PSScriptRoot -ChildPath '..\src\Get-EventReleasePlan.ps1' + $bootstrapPath = Join-Path -Path $PSScriptRoot -ChildPath '..\src\Initialize-ReleaseConfiguration.ps1' + $helperPath = Join-Path -Path $PSScriptRoot -ChildPath '..\src\Release-GHRepository.Helpers.psm1' + $actionPath = Join-Path -Path $PSScriptRoot -ChildPath '..\action.yml' + $actionDefinition = ConvertFrom-Yaml -Yaml (Get-Content -LiteralPath $actionPath -Raw) + $readBootstrapOutputs = { + param([string] $Path) + + $outputs = @{} + $reader = [IO.File]::OpenText($Path) + try { + while ($null -ne ($line = $reader.ReadLine())) { + if ($line -match '\A([^=]+)=(.*)\z') { + $outputs[$Matches[1]] = $Matches[2] + } elseif ($line -match '\A([^<]+)<<(.+)\z') { + $name = $Matches[1] + $delimiter = $Matches[2] + $lines = [Collections.Generic.List[string]]::new() + while ($null -ne ($line = $reader.ReadLine()) -and $line -cne $delimiter) { + $lines.Add($line) + } + if ($null -eq $line) { + throw 'The bootstrap output is missing its closing delimiter.' + } + $outputs[$name] = $lines -join "`n" + } else { + throw 'The bootstrap wrote an invalid runner output command.' + } + } + } finally { + $reader.Dispose() + } + $outputs + } + $runRelease = { + param( + [string] $ControllerPath = $mainPath, + [string] $ConfigurationPath = $bootstrapPath + ) + + $null = & $ConfigurationPath + $outputs = & $readBootstrapOutputs -Path $env:GITHUB_OUTPUT + $releaseSettings = ConvertFrom-Json -InputObject $outputs.ReleaseSettings + Push-Location -LiteralPath $outputs.WorkingDirectory + try { + & $ControllerPath -Settings $releaseSettings + } finally { + Pop-Location + } + } + $releaseSettingNames = @( + 'AutoCleanup' + 'DefaultBump' + 'CreateMajorTag' + 'CreateMinorTag' + 'DatePrereleaseFormat' + 'IncrementalPrerelease' + 'UsePRTitleAsReleaseName' + 'UsePRBodyAsReleaseNotes' + 'UsePRTitleAsNotesHeading' + 'VersionPrefix' + 'WhatIf' + ) + $fixtureStandardsYaml = @' +AutoCleanup: false +DefaultBump: minor +CreateMajorTag: true +CreateMinorTag: true +DatePrereleaseFormat: '' +IncrementalPrerelease: true +UsePRTitleAsReleaseName: false +UsePRBodyAsReleaseNotes: true +UsePRTitleAsNotesHeading: true +VersionPrefix: v +WhatIf: false +'@ + $headSha = '0123456789012345678901234567890123456789' + $squashCommitSha = 'fedcba9876543210fedcba9876543210fedcba98' + $authoredBody = @' +This release preserves the source-bound adoption record. + +## Adopting this release + +1. Select the reviewed release. +2. Keep the caller's explicit settings. + + +
+Technical details + +The complete record remains part of the release notes. + +
+ +Resolved release decision: release:major, stable. +'@ +} + +Describe 'Release-GHRepository configuration bootstrap' { + BeforeEach { + $bootstrapEnvironmentNames = @('GITHUB_WORKSPACE', 'GITHUB_OUTPUT') + @( + $actionDefinition.inputs.Keys | ForEach-Object { "PSMODULE_AUTO_RELEASE_INPUT_$_" } + ) + $bootstrapSavedEnvironment = @{} + foreach ($environmentName in $bootstrapEnvironmentNames) { + $bootstrapSavedEnvironment[$environmentName] = [Environment]::GetEnvironmentVariable($environmentName) + [Environment]::SetEnvironmentVariable($environmentName, $null) + } + $workspace = Join-Path -Path $TestDrive -ChildPath ([guid]::NewGuid().ToString('N')) + $null = New-Item -Path $workspace -ItemType Directory + $env:GITHUB_WORKSPACE = $workspace + $env:GITHUB_OUTPUT = Join-Path -Path $workspace -ChildPath 'outputs.txt' + $selectedFile = Join-Path -Path $workspace -ChildPath 'settings [literal path].yml' + $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath = $selectedFile + Mock Install-PSResource { throw 'Bootstrap tests use the installed parsing modules.' } + } + + AfterEach { + foreach ($environmentName in $bootstrapEnvironmentNames) { + [Environment]::SetEnvironmentVariable($environmentName, $bootstrapSavedEnvironment[$environmentName]) + } + } + + It 'resolves all startup standards from the workspace before dependency startup' { + $settings = & $bootstrapPath + + $settings.Debug | Should -BeFalse + $settings.Verbose | Should -BeFalse + $settings.Prerelease | Should -BeFalse + $settings.Version | Should -BeExactly '' + $settings.WorkingDirectory | Should -BeExactly $workspace + $settings.DefaultBump | Should -BeExactly 'none' + $settings.DefaultBumpSource | Should -BeExactly 'SharedDefault' + $outputs = & $readBootstrapOutputs -Path $env:GITHUB_OUTPUT + $outputs.Count | Should -Be 6 + $outputs.Debug | Should -BeExactly 'false' + $outputs.Verbose | Should -BeExactly 'false' + $outputs.Prerelease | Should -BeExactly 'false' + $outputs.Version | Should -BeExactly '' + $outputs.WorkingDirectory | Should -BeExactly $workspace + $releaseSettings = ConvertFrom-Json -InputObject $outputs.ReleaseSettings + $releaseSettings.DefaultBump | Should -BeExactly 'none' + $releaseSettings.VersionPrefix | Should -BeExactly 'v' + $releaseSettings.PSObject.Properties.Name | Should -Not -Contain 'Prerelease' + Should -Invoke Install-PSResource -Times 0 -Exactly + } + + It 'uses all five startup settings from a literal selected file' { + $executionDirectory = Join-Path -Path $workspace -ChildPath 'execution [directory]' + $null = New-Item -Path $executionDirectory -ItemType Directory + @' +Debug: true +Verbose: true +Prerelease: true +Version: '[0.43.0, 1.0.0)' +WorkingDirectory: 'execution [directory]' +DefaultBump: major +'@ | Set-Content -LiteralPath $selectedFile + + $settings = & $bootstrapPath + + $settings.Debug | Should -BeTrue + $settings.Verbose | Should -BeTrue + $settings.Prerelease | Should -BeTrue + $settings.Version | Should -BeExactly '[0.43.0, 1.0.0)' + $settings.WorkingDirectory | Should -BeExactly $executionDirectory + $settings.DefaultBump | Should -BeExactly 'major' + $settings.DefaultBumpSource | Should -BeExactly 'RepositorySetting' + $outputs = & $readBootstrapOutputs -Path $env:GITHUB_OUTPUT + $outputs.Debug | Should -BeExactly 'true' + $outputs.Verbose | Should -BeExactly 'true' + $outputs.Prerelease | Should -BeExactly 'true' + $outputs.Version | Should -BeExactly '[0.43.0, 1.0.0)' + $outputs.WorkingDirectory | Should -BeExactly $executionDirectory + $releaseSettings = ConvertFrom-Json -InputObject $outputs.ReleaseSettings + $releaseSettings.DefaultBump | Should -BeExactly 'major' + $releaseSettings.DefaultBumpSource | Should -BeExactly 'RepositorySetting' + } + + It 'selects a relative file from without rediscovery after file WorkingDirectory' -ForEach @( + @{ InitialDirectory = 'github.workspace'; ExplicitDirectory = $false } + @{ InitialDirectory = 'an explicit WorkingDirectory'; ExplicitDirectory = $true } + ) { + $initialDirectory = $workspace + if ($ExplicitDirectory) { + $initialDirectory = Join-Path -Path $workspace -ChildPath 'initial [directory]' + $null = New-Item -Path $initialDirectory -ItemType Directory + $env:PSMODULE_AUTO_RELEASE_INPUT_WorkingDirectory = 'initial [directory]' + } + $executionDirectory = Join-Path -Path $workspace -ChildPath 'execution [directory]' + $null = New-Item -Path $executionDirectory -ItemType Directory + $relativeFile = 'settings [selected].yml' + @' +WorkingDirectory: 'execution [directory]' +DefaultBump: minor +'@ | Set-Content -LiteralPath (Join-Path -Path $initialDirectory -ChildPath $relativeFile) + 'DefaultBump: invalid' | Set-Content -LiteralPath (Join-Path -Path $executionDirectory -ChildPath $relativeFile) + $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath = $relativeFile + + Push-Location -LiteralPath $TestDrive + try { + $settings = & $bootstrapPath + } finally { + Pop-Location + } + + $settings.DefaultBump | Should -BeExactly 'minor' + $settings.DefaultBumpSource | Should -BeExactly 'RepositorySetting' + if ($ExplicitDirectory) { + $settings.WorkingDirectory | Should -BeExactly $initialDirectory + } else { + $settings.WorkingDirectory | Should -BeExactly $executionDirectory + } + } + + It 'keeps all startup file values when named inputs are ' -ForEach @( + @{ InputState = 'omitted'; InputValue = $null } + @{ InputState = 'empty'; InputValue = '' } + ) { + @' +Debug: true +Verbose: true +Prerelease: true +Version: '[0.43.1]' +WorkingDirectory: '.' +'@ | Set-Content -LiteralPath $selectedFile + foreach ($name in @('Debug', 'Verbose', 'Prerelease', 'Version', 'WorkingDirectory')) { + [Environment]::SetEnvironmentVariable("PSMODULE_AUTO_RELEASE_INPUT_$name", $InputValue) + } + + $settings = & $bootstrapPath + + $settings.Debug | Should -BeTrue + $settings.Verbose | Should -BeTrue + $settings.Prerelease | Should -BeTrue + $settings.Version | Should -BeExactly '[0.43.1]' + $settings.WorkingDirectory | Should -BeExactly $workspace + } + + It 'applies named false and standard-valued startup overrides' { + $executionDirectory = Join-Path -Path $workspace -ChildPath 'execution' + $null = New-Item -Path $executionDirectory -ItemType Directory + @' +Debug: true +Verbose: true +Prerelease: true +Version: '[0.43.0, 1.0.0)' +WorkingDirectory: execution +'@ | Set-Content -LiteralPath $selectedFile + $env:PSMODULE_AUTO_RELEASE_INPUT_Debug = 'false' + $env:PSMODULE_AUTO_RELEASE_INPUT_Verbose = 'FALSE' + $env:PSMODULE_AUTO_RELEASE_INPUT_Prerelease = 'false' + $env:PSMODULE_AUTO_RELEASE_INPUT_Version = '[0.43.1]' + $env:PSMODULE_AUTO_RELEASE_INPUT_WorkingDirectory = $workspace + + $settings = & $bootstrapPath + + $settings.Debug | Should -BeFalse + $settings.Verbose | Should -BeFalse + $settings.Prerelease | Should -BeFalse + $settings.Version | Should -BeExactly '[0.43.1]' + $settings.WorkingDirectory | Should -BeExactly $workspace + } + + It 'accepts empty file Version text as latest dependency selection' { + "Version: ''" | Set-Content -LiteralPath $selectedFile + + $settings = & $bootstrapPath + + $settings.Version | Should -BeExactly '' + } + + It 'rejects an invalid file even when a valid named override would mask it' -ForEach @( + @{ Name = 'Debug'; InvalidValue = 'yes'; InputValue = 'false'; Message = '*Debug*true or false*' } + @{ Name = 'Verbose'; InvalidValue = 'null'; InputValue = 'false'; Message = '*Verbose*true or false*' } + @{ Name = 'Prerelease'; InvalidValue = '1'; InputValue = 'true'; Message = '*Prerelease*true or false*' } + @{ Name = 'Version'; InvalidValue = 'inherit'; InputValue = '[0.43.1]'; Message = '*Version*version*' } + @{ Name = 'WorkingDirectory'; InvalidValue = 'missing'; InputValue = '.'; Message = '*WorkingDirectory*directory*' } + ) { + "$Name`: $InvalidValue" | Set-Content -LiteralPath $selectedFile + [Environment]::SetEnvironmentVariable("PSMODULE_AUTO_RELEASE_INPUT_$Name", $InputValue) + + { & $bootstrapPath } | Should -Throw $Message + Test-Path -LiteralPath $env:GITHUB_OUTPUT | Should -BeFalse + } + + It 'rejects invalid selected paths rather than treating them as absent files' -ForEach @( + @{ PathCase = 'empty'; Value = ''; Message = '*SettingsFilePath*nonempty path*' } + @{ PathCase = 'whitespace'; Value = ' '; Message = '*SettingsFilePath*nonempty path*' } + @{ PathCase = 'directory'; Value = '.'; Message = '*SettingsFilePath*file*' } + @{ PathCase = 'provider'; Value = 'Env:\PATH'; Message = '*SettingsFilePath*path*' } + ) { + [Environment]::SetEnvironmentVariable('PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath', $Value) + + { & $bootstrapPath } | Should -Throw $Message + Test-Path -LiteralPath $env:GITHUB_OUTPUT | Should -BeFalse + } + + It 'rejects invalid named startup before writing the handoff' -ForEach @( + @{ SettingName = 'Debug'; InputValue = ' yes '; Message = '*Debug*true or false*' } + @{ SettingName = 'Verbose'; InputValue = ' '; Message = '*Verbose*true or false*' } + @{ SettingName = 'Prerelease'; InputValue = '1'; Message = '*Prerelease*true or false*' } + @{ SettingName = 'Version'; InputValue = 'latest'; Message = '*Version*version*' } + @{ SettingName = 'Version'; InputValue = '[2.0.0, 1.0.0)'; Message = '*Version*version*' } + @{ SettingName = 'WorkingDirectory'; InputValue = 'missing'; Message = '*WorkingDirectory*directory*' } + ) { + @' +Debug: false +Verbose: false +Prerelease: false +Version: '[0.43.1]' +WorkingDirectory: '.' +'@ | Set-Content -LiteralPath $selectedFile + [Environment]::SetEnvironmentVariable("PSMODULE_AUTO_RELEASE_INPUT_$SettingName", $InputValue) + + { & $bootstrapPath } | Should -Throw $Message + Test-Path -LiteralPath $env:GITHUB_OUTPUT | Should -BeFalse + } + + It 'rejects SettingsFilePath as a settings-file key' { + 'SettingsFilePath: another.yml' | Set-Content -LiteralPath $selectedFile + + { & $bootstrapPath } | Should -Throw '*Unsupported release setting*SettingsFilePath*' + Test-Path -LiteralPath $env:GITHUB_OUTPUT | Should -BeFalse + } +} + +Describe 'Release-GHRepository caller compatibility' { + BeforeEach { + $environmentNames = @( + 'GITHUB_REPOSITORY' + 'GITHUB_SERVER_URL' + 'GITHUB_EVENT_NAME' + 'GITHUB_EVENT_PATH' + 'GITHUB_WORKSPACE' + 'GITHUB_OUTPUT' + 'PSMODULE_AUTO_RELEASE_INPUT_ConfigurationFile' + ) + @($actionDefinition.inputs.Keys | ForEach-Object { "PSMODULE_AUTO_RELEASE_INPUT_$_" }) + $savedEnvironment = @{} + foreach ($name in $environmentNames) { + $savedEnvironment[$name] = [Environment]::GetEnvironmentVariable($name) + if (Test-Path -LiteralPath "Env:\$name") { + Remove-Item -LiteralPath "Env:\$name" + } + } + + $env:GITHUB_REPOSITORY = 'example/repository' + $env:GITHUB_SERVER_URL = 'https://github.com' + $env:GITHUB_EVENT_NAME = 'pull_request' + $env:GITHUB_EVENT_PATH = Join-Path -Path $TestDrive -ChildPath 'event.json' + $env:GITHUB_WORKSPACE = $TestDrive + $env:GITHUB_OUTPUT = Join-Path -Path $TestDrive -ChildPath ('outputs-{0}.txt' -f [guid]::NewGuid().ToString('N')) + $settingsFileName = 'settings [custom path] {0}.yml' -f [guid]::NewGuid().ToString('N') + $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath = Join-Path -Path $TestDrive -ChildPath $settingsFileName + $env:PSMODULE_AUTO_RELEASE_INPUT_WhatIf = 'true' + $githubEvent = @{ + action = 'opened' + repository = @{ full_name = $env:GITHUB_REPOSITORY; default_branch = 'main'; fork = $false } + pull_request = @{ + number = 42 + title = 'The complete authored record is preserved' + body = $authoredBody + merged = $false + state = 'open' + base = @{ ref = 'main'; repo = @{ full_name = $env:GITHUB_REPOSITORY } } + head = @{ ref = 'feature/caller'; sha = $headSha; repo = @{ full_name = $env:GITHUB_REPOSITORY } } + labels = @() + } + } + $githubEvent | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH + + $releaseRecordsJson = '[{"tagName":"v2.0.3","isLatest":true,"isPrerelease":false}]' + $simulateLabelWrites = $false + Mock Install-PSResource {} + Mock Write-GitHubNotice {} + Mock git { + if ($args[0] -cne 'check-ref-format') { + throw 'A caller compatibility test must never mutate Git refs.' + } + $global:LASTEXITCODE = 0 + } + Mock gh { + $global:LASTEXITCODE = 0 + if ($args[0] -ceq 'api' -and $args[1] -ceq 'repos/example/repository/pulls/42') { + $eventRecord = ConvertFrom-Json -InputObject ([IO.File]::ReadAllText($env:GITHUB_EVENT_PATH)) + ConvertTo-Json -InputObject $eventRecord.pull_request -Depth 20 -Compress + } elseif ($args[0] -ceq 'api' -and $args[1] -ceq 'graphql') { + $stable = @{ tagName = 'v2.0.3'; isDraft = $false; isPrerelease = $false } + $history = @{ data = @{ repository = @{ nameWithOwner = 'example/repository'; latestRelease = $stable } } } + ConvertTo-Json -InputObject $history -Depth 5 -Compress + } elseif ($args[0] -ceq 'api' -and $args[1] -clike 'repos/example/repository/git/matching-refs/tags/*') { + '[]' + } elseif ($args[0] -eq 'release' -and $args[1] -eq 'list') { + $releaseRecordsJson + } elseif ($simulateLabelWrites -and $args[0] -eq 'label' -and $args[1] -eq 'create') { + return + } else { + throw "A caller compatibility test must never mutate GitHub: gh $($args -join ' ')" + } + } + } + + AfterEach { + foreach ($name in $environmentNames) { + if ($null -eq $savedEnvironment[$name]) { + if (Test-Path -LiteralPath "Env:\$name") { + Remove-Item -LiteralPath "Env:\$name" + } + } else { + [Environment]::SetEnvironmentVariable($name, $savedEnvironment[$name]) + } + } + } + + It 'uses a bump label without repository settings or injected input defaults' { + $githubEvent.pull_request.labels = @(@{ name = 'release:patch' }, @{ name = 'release:prerelease' }) + $githubEvent | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH + + $output = (& $runRelease) -join "`n" + + $output | Should -Match 'Default bump:\s+\[none\]' + $output | Should -Match 'Bump source:\s+\[release:patch\]' + $output | Should -Match 'Auto cleanup enabled:\s+\[True\]' + $output | Should -Match 'Use PR body as release notes:\s+\[True\]' + $output | Should -Match 'gh release create v2\.0\.4-featurecaller\.1 ' + $output.Contains($authoredBody) | Should -BeTrue + } + + It 'rejects a release with and no configured default' -ForEach @( + @{ LabelState = 'no labels'; Labels = @() } + @{ LabelState = 'only release:prerelease'; Labels = @(@{ name = 'release:prerelease' }) } + ) { + $githubEvent.pull_request.labels = $Labels + $githubEvent | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH + + { & $runRelease } | Should -Throw '*No release bump*release:skip*' + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[0] -in 'label', 'release' } + Should -Invoke git -Times 0 -Exactly + } + + It 'validates metadata-owned standards when they are ' -ForEach @( + @{ StandardsState = 'valid'; Message = $null } + @{ StandardsState = 'missing'; Message = '*action release standards*YAML mapping*' } + @{ StandardsState = 'empty'; Message = '*action release standards*YAML mapping*' } + @{ StandardsState = 'scalar'; Message = '*action release standards*mapping*' } + @{ StandardsState = 'unknown'; Message = '*Unsupported release setting*DefaultBunp*' } + @{ StandardsState = 'null value'; Message = '*WhatIf*true or false*' } + @{ StandardsState = 'invalid bump'; Message = '*Invalid DefaultBump*' } + @{ StandardsState = 'incomplete'; Message = '*standard defaults*missing*WhatIf*' } + @{ StandardsState = 'invalid startup boolean'; Message = '*Debug*true or false*' } + @{ StandardsState = 'invalid startup version'; Message = '*Version*version*' } + @{ StandardsState = 'invalid directory standard'; Message = '*WorkingDirectory*directory*' } + @{ StandardsState = 'nonmapping definition'; Message = '*Invalid metadata*Debug*' } + @{ StandardsState = 'missing default'; Message = '*Invalid metadata*Debug*' } + @{ StandardsState = 'unknown type'; Message = '*Invalid metadata type*Debug*' } + @{ StandardsState = 'unknown phase'; Message = '*Invalid metadata phase*Debug*' } + @{ StandardsState = 'extra definition field'; Message = '*Invalid metadata*Debug*' } + ) { + $fixtureDirectory = Join-Path -Path $TestDrive -ChildPath ([guid]::NewGuid().ToString('N')) + $fixtureSource = Join-Path -Path $fixtureDirectory -ChildPath 'src' + $null = New-Item -Path $fixtureSource -ItemType Directory -Force + Copy-Item -LiteralPath $mainPath, $helperPath, $bootstrapPath, $planPath -Destination $fixtureSource + $fixtureMetadata = ConvertFrom-Yaml -Yaml (Get-Content -LiteralPath $actionPath -Raw) + $standardData = ConvertFrom-Yaml -Yaml $fixtureMetadata.runs.steps[0].env.PSMODULE_AUTO_RELEASE_SETTING_METADATA + $fixtureStandards = ConvertFrom-Yaml -Yaml $fixtureStandardsYaml + foreach ($name in $fixtureStandards.Keys) { + $standardData[$name].Default = $fixtureStandards[$name] + } + switch ($StandardsState) { + 'unknown' { $standardData.DefaultBunp = @{ Type = 'Bump'; Default = 'minor'; Phase = 'Release' } } + 'null value' { $standardData.WhatIf.Default = $null } + 'invalid bump' { $standardData.DefaultBump.Default = 'date' } + 'incomplete' { $standardData.Remove('WhatIf') } + 'invalid startup boolean' { $standardData.Debug.Default = 'yes' } + 'invalid startup version' { $standardData.Version.Default = 'not-a-version' } + 'invalid directory standard' { $standardData.WorkingDirectory.Default = 'missing' } + 'nonmapping definition' { $standardData.Debug = $true } + 'missing default' { $standardData.Debug.Remove('Default') } + 'unknown type' { $standardData.Debug.Type = 'Flag' } + 'unknown phase' { $standardData.Debug.Phase = 'Dependency' } + 'extra definition field' { $standardData.Debug.Unexpected = $true } + } + $standardYaml = ConvertTo-Yaml -Data $standardData + if ($StandardsState -eq 'empty') { + $standardYaml = '' + } elseif ($StandardsState -eq 'scalar') { + $standardYaml = 'minor' + } + $fixtureMetadata.runs.steps[0].env.PSMODULE_AUTO_RELEASE_SETTING_METADATA = $standardYaml + if ($StandardsState -eq 'missing') { + $fixtureMetadata.runs.steps[0].env.Remove('PSMODULE_AUTO_RELEASE_SETTING_METADATA') + } + ConvertTo-Yaml -Data $fixtureMetadata | + Set-Content -LiteralPath (Join-Path -Path $fixtureDirectory -ChildPath 'action.yml') + $fixtureMainPath = Join-Path -Path $fixtureSource -ChildPath 'main.ps1' + $fixtureBootstrapPath = Join-Path -Path $fixtureSource -ChildPath 'Initialize-ReleaseConfiguration.ps1' + + Push-Location -LiteralPath $TestDrive + try { + if ($Message) { + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'patch' + $env:PSMODULE_AUTO_RELEASE_INPUT_Debug = 'false' + $env:PSMODULE_AUTO_RELEASE_INPUT_Version = '[0.43.1]' + $env:PSMODULE_AUTO_RELEASE_INPUT_WorkingDirectory = $TestDrive + { & $runRelease -ControllerPath $fixtureMainPath -ConfigurationPath $fixtureBootstrapPath } | + Should -Throw $Message + Should -Invoke gh -Times 0 -Exactly + } else { + $output = (& $runRelease -ControllerPath $fixtureMainPath -ConfigurationPath $fixtureBootstrapPath) -join "`n" + + $output | Should -Match 'Default bump:\s+\[minor\]' + $output | Should -Match 'Default bump source:\s+\[SharedDefault\]' + $output | Should -Match 'Auto cleanup enabled:\s+\[False\]' + $output | Should -Not -Match 'gh release create' + } + } finally { + Pop-Location + } + Should -Invoke git -Times 0 -Exactly + } + + It 'uses the declared SettingsFilePath default when the file is ' -ForEach @( + @{ + FileState = 'present' + FilePresent = $true + ExpectedBump = 'minor' + ExpectedSource = 'RepositorySetting' + } + @{ + FileState = 'absent' + FilePresent = $false + ExpectedBump = 'none' + ExpectedSource = 'SharedDefault' + } + ) { + $defaultSettingsPath = '.github\auto-release.yml' + $callerDirectory = Join-Path -Path $TestDrive -ChildPath ([guid]::NewGuid().ToString('N')) + $null = New-Item -Path (Join-Path -Path $callerDirectory -ChildPath '.github') -ItemType Directory + if ($FilePresent) { + 'DefaultBump: minor' | Set-Content -LiteralPath (Join-Path -Path $callerDirectory -ChildPath $defaultSettingsPath) + } else { + $githubEvent.pull_request.labels = @(@{ name = 'release:patch' }) + $githubEvent | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH + } + Remove-Item -LiteralPath 'Env:\PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath' + $env:GITHUB_WORKSPACE = $callerDirectory + + Push-Location -LiteralPath $callerDirectory + try { + $output = (& $runRelease) -join "`n" + } finally { + Pop-Location + } + + $output | Should -Match "Default bump:\s+\[$ExpectedBump\]" + $output | Should -Match "Default bump source:\s+\[$ExpectedSource\]" + $output | Should -Not -Match 'gh release create' + Should -Invoke git -Times 0 -Exactly + } + + It 'rejects a SettingsFilePath before contacting GitHub' -ForEach @( + @{ PathDescription = 'blank'; PathValue = '' } + @{ PathDescription = 'whitespace-only'; PathValue = ' ' } + ) { + [Environment]::SetEnvironmentVariable('PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath', $PathValue) + + { & $runRelease } | Should -Throw '*SettingsFilePath must be a nonempty path.*' + Should -Invoke gh -Times 0 -Exactly + Should -Invoke git -Times 0 -Exactly + } + + It 'uses a caller minor default for an unlabeled pull request' { + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'minor' + + $output = (& $runRelease) -join "`n" + + $output | Should -Match 'Default bump:\s+\[minor\]' + $output | Should -Not -Match 'gh release create' + } + + It 'keeps repository policy when the runner supplies empty release inputs' { + foreach ($settingName in $releaseSettingNames) { + [Environment]::SetEnvironmentVariable("PSMODULE_AUTO_RELEASE_INPUT_$settingName", '') + } + $env:PSMODULE_AUTO_RELEASE_INPUT_WhatIf = 'true' + @' +DefaultBump: minor +AutoCleanup: false +DatePrereleaseFormat: '' +VersionPrefix: '' +'@ | Set-Content -LiteralPath $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath + + $output = (& $runRelease) -join "`n" + + $output | Should -Match 'Default bump:\s+\[minor\]' + $output | Should -Match 'Auto cleanup enabled:\s+\[False\]' + $output | Should -Match 'Date-based prerelease format:\s+\[\]' + $output | Should -Not -Match 'gh release create' + Should -Invoke git -Times 0 -Exactly + } + + It 'distinguishes existing file policy from a named bump that is ' -ForEach @( + @{ + InputState = 'omitted' + InputValue = $null + ExpectedBump = 'major' + ExpectedSource = 'RepositorySetting' + } + @{ + InputState = 'empty' + InputValue = '' + ExpectedBump = 'major' + ExpectedSource = 'RepositorySetting' + } + @{ + InputState = 'an explicit patch' + InputValue = 'patch' + ExpectedBump = 'patch' + ExpectedSource = 'ActionInput' + } + ) { + if ($null -ne $InputValue) { + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = $InputValue + } + 'DefaultBump: major' | Set-Content -LiteralPath $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath + + $output = (& $runRelease) -join "`n" + + $output | Should -Match "Default bump:\s+\[$ExpectedBump\]" + $output | Should -Match "Default bump source:\s+\[$ExpectedSource\]" + $output | Should -Not -Match 'gh release create' + Should -Invoke git -Times 0 -Exactly + } + + It 'does not invent a bump when all release inputs are empty' { + foreach ($settingName in $releaseSettingNames) { + [Environment]::SetEnvironmentVariable("PSMODULE_AUTO_RELEASE_INPUT_$settingName", '') + } + $env:PSMODULE_AUTO_RELEASE_INPUT_WhatIf = 'true' + + { & $runRelease } | Should -Throw '*No release bump*' + } + + It 'lets an explicit none clear a file default without preventing a skip' { + 'DefaultBump: major' | Set-Content -LiteralPath $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'none' + + { & $runRelease } | Should -Throw '*No release bump*' + + $githubEvent.pull_request.labels = @(@{ name = 'release:skip' }) + $githubEvent | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH + $output = (& $runRelease) -join "`n" + + $output | Should -Match 'Default bump source:\s+\[ActionInput\]' + $output | Should -Match 'Skip release:\s+\[True\]' + $output | Should -Not -Match 'gh release create|git push' + } + + It 'lets release:major override a file minor default and preserves the complete record' { + 'DefaultBump: minor' | Set-Content -LiteralPath $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath + $githubEvent.pull_request.labels = @( + @{ name = 'release:major' }, @{ name = 'release:prerelease' }, @{ name = 'dependencies' } + ) + $githubEvent | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH + + $output = (& $runRelease) -join "`n" + + $output | Should -Match 'Default bump applied:\s+\[False\]' + $output | Should -Match 'gh release create v3\.0\.0-featurecaller\.1 ' + $output.Contains($authoredBody) | Should -BeTrue + $output | Should -Match '# The complete authored record is preserved \(#42\)' + } + + It 'ignores dependency, retired, and bare labels when using the caller default' { + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'minor' + $githubEvent.pull_request.labels = @( + @{ name = 'major' } + @{ name = 'dependencies' } + @{ name = 'release:pre-release' } + ) + $githubEvent | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH + + $output = (& $runRelease) -join "`n" + + $output | Should -Match 'Default bump applied:\s+\[True\]' + $output | Should -Match 'Create a prerelease:\s+\[False\]' + $output | Should -Not -Match 'gh release create' + } + + It 'lets a named DefaultBump override repository policy' { + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'minor' + 'DefaultBump: major' | Set-Content -LiteralPath $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath + + $output = (& $runRelease) -join "`n" + + $output | Should -Match 'Default bump:\s+\[minor\]' + $output | Should -Match 'Default bump source:\s+\[ActionInput\]' + $output | Should -Match 'Bump source:\s+\[ActionInput\]' + $output | Should -Not -Match 'gh release create' + } + + It 'applies named patch and false while an empty text input keeps file policy' { + @' +DefaultBump: major +AutoCleanup: true +VersionPrefix: v +'@ | Set-Content -LiteralPath $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'patch' + $env:PSMODULE_AUTO_RELEASE_INPUT_AutoCleanup = 'false' + $env:PSMODULE_AUTO_RELEASE_INPUT_VersionPrefix = '' + + $output = (& $runRelease) -join "`n" + + $output | Should -Match 'Default bump:\s+\[patch\]' + $output | Should -Match 'Default bump source:\s+\[ActionInput\]' + $output | Should -Match 'Auto cleanup enabled:\s+\[False\]' + $output | Should -Match 'Version prefix:\s+\[v\]' + $output | Should -Not -Match 'gh release create' + } + + It 'does not mask an invalid file value with a valid explicit caller override' { + 'DefaultBump: invalid' | Set-Content -LiteralPath $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'patch' + + { & $runRelease } | Should -Throw '*DefaultBump*' + Should -Invoke gh -Times 0 -Exactly + } + + It 'keeps validation read-only when explicit WhatIf overrides a false repository setting' { + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'patch' + 'WhatIf: false' | Set-Content -LiteralPath $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath + + $output = (& $runRelease) -join "`n" + + $output | Should -Match 'What if mode:\s+\[True\]' + $output | Should -Match 'WhatIf: gh label create ' + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[0] -ceq 'label' } + Should -Invoke git -Times 0 -Exactly + } + + It 'keeps the configured prerelease date format when its input is empty' { + @' +DatePrereleaseFormat: "'fixed'" +'@ | Set-Content -LiteralPath $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath + $env:PSMODULE_AUTO_RELEASE_INPUT_DatePrereleaseFormat = '' + $githubEvent.pull_request.labels = @(@{ name = 'release:prerelease' }, @{ name = 'release:patch' }) + $githubEvent | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH + + $output = (& $runRelease) -join "`n" + + $output | Should -Match "Date-based prerelease format:\s+\['fixed'\]" + $output | Should -Match 'gh release create v2\.0\.4-featurecaller\.fixed\.1 ' + } + + It 'keeps a true file WhatIf policy when its named input is empty' { + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'patch' + 'WhatIf: true' | Set-Content -LiteralPath $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath + $env:PSMODULE_AUTO_RELEASE_INPUT_WhatIf = '' + + $output = (& $runRelease) -join "`n" + + $output | Should -Match 'What if mode:\s+\[True\]' + $output | Should -Match 'WhatIf: gh label create ' + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[0] -ceq 'label' } + Should -Invoke git -Times 0 -Exactly + } + + It 'treats literal inherit as ordinary prefix text rather than an omission marker' { + 'VersionPrefix: repo-' | Set-Content -LiteralPath $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath + $env:PSMODULE_AUTO_RELEASE_INPUT_VersionPrefix = 'inherit' + $githubEvent.pull_request.labels = @(@{ name = 'release:skip' }) + $githubEvent | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH + + $output = (& $runRelease) -join "`n" + + $output | Should -Match 'Version prefix:\s+\[inherit\]' + $output | Should -Match 'Skipping release creation\.' + Should -Invoke git -Times 0 -Exactly + } + + It 'accepts explicit false for WhatIf as a real override with only simulated label writes' { + 'WhatIf: true' | Set-Content -LiteralPath $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath + $env:PSMODULE_AUTO_RELEASE_INPUT_WhatIf = 'false' + $simulateLabelWrites = $true + $githubEvent.pull_request.labels = @(@{ name = 'release:skip' }) + $githubEvent | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH + + $output = (& $runRelease) -join "`n" + + $output | Should -Match 'What if mode:\s+\[False\]' + $output | Should -Match 'Skipping release creation\.' + Should -Invoke gh -Times 5 -Exactly -ParameterFilter { $args[0] -eq 'label' -and $args[1] -eq 'create' } + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[0] -eq 'release' -and $args[1] -eq 'create' } + Should -Invoke git -Times 0 -Exactly + } + + It 'rejects invalid named inputs before contacting GitHub' -ForEach @( + @{ InputName = 'DefaultBump'; Value = 'date'; Message = '*DefaultBump*' } + @{ InputName = 'DefaultBump'; Value = 'inherit'; Message = '*DefaultBump*' } + @{ InputName = 'DefaultBump'; Value = ' '; Message = '*DefaultBump*' } + @{ InputName = 'WhatIf'; Value = 'invalid'; Message = '*WhatIf*true or false*' } + @{ InputName = 'WhatIf'; Value = 'inherit'; Message = '*WhatIf*true or false*' } + @{ InputName = 'WhatIf'; Value = ' '; Message = '*WhatIf*true or false*' } + ) { + [Environment]::SetEnvironmentVariable("PSMODULE_AUTO_RELEASE_INPUT_$InputName", $Value) + + { & $runRelease } | Should -Throw $Message + Should -Invoke gh -Times 0 -Exactly + } + + It 'validates a merged skipped pull request successfully without planning publication' { + $githubEvent.pull_request.labels = @(@{ name = 'release:skip' }) + $githubEvent.pull_request.merged = $true + $githubEvent.pull_request.state = 'closed' + $githubEvent.action = 'closed' + $githubEvent | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH + + $output = (& $runRelease) -join "`n" + + $output | Should -Match 'Skip release:\s+\[True\]' + $output | Should -Match 'Skipping release creation\.' + $output | Should -Not -Match 'gh release create|git push|git tag' + Should -Invoke Write-GitHubNotice -Times 0 -Exactly + } + + It 'validates cleanup for a skipped branch with no ASCII prerelease identifier' { + $githubEvent.pull_request.head.ref = ([char] 0x2603).ToString() + $githubEvent.pull_request.labels = @(@{ name = 'release:skip' }) + $githubEvent.pull_request.state = 'closed' + $githubEvent.action = 'closed' + $githubEvent | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH + + $output = (& $runRelease) -join "`n" + + $output | Should -Match 'Skip release:\s+\[True\]' + $output | Should -Match 'no prerelease identifier' + Should -Invoke gh -Times 0 -Exactly + Should -Invoke git -Times 0 -Exactly + } + + It 'validates a closed skip without parsing a malformed latest version while retaining cleanup' { + $releaseRecordsJson = @' +[{"tagName":"not-a-semver","isLatest":true,"isPrerelease":false},{"tagName":"v2.0.4-featurecaller.1","isLatest":false,"isPrerelease":true}] +'@ + $githubEvent.pull_request.labels = @(@{ name = 'release:skip' }) + $githubEvent.pull_request.merged = $true + $githubEvent.pull_request.state = 'closed' + $githubEvent.action = 'closed' + $githubEvent | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH + + $output = (& $runRelease) -join "`n" + + $output | Should -Match 'Skipping release creation\.' + $output | Should -Match 'WhatIf: gh release delete v2\.0\.4-featurecaller\.1' + $output | Should -Not -Match 'gh release create|git tag|git push' + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[1] -ceq 'graphql' } + Should -Invoke git -Times 0 -Exactly + } + + It 'keeps the bootstrap policy when files and raw inputs change after resolution' { + @' +DefaultBump: major +WhatIf: true +'@ | Set-Content -LiteralPath $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath + $null = & $bootstrapPath + $outputs = & $readBootstrapOutputs -Path $env:GITHUB_OUTPUT + $releaseSettings = ConvertFrom-Json -InputObject $outputs.ReleaseSettings + 'Version: invalid' | Set-Content -LiteralPath $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'minor' + $env:PSMODULE_AUTO_RELEASE_INPUT_WhatIf = 'false' + + $output = (& $mainPath -Settings $releaseSettings) -join "`n" + + $output | Should -Match 'Default bump:\s+\[major\]' + $output | Should -Match 'Default bump source:\s+\[RepositorySetting\]' + $output | Should -Match 'What if mode:\s+\[True\]' + $output | Should -Not -Match 'gh release create' + Should -Invoke git -Times 0 -Exactly + } + + It 'keeps dependency Prerelease separate from repository prerelease mode' { + @' +DefaultBump: patch +Prerelease: true +Version: '[0.43.0, 1.0.0)' +'@ | Set-Content -LiteralPath $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath + + $output = (& $runRelease) -join "`n" + + $outputs = & $readBootstrapOutputs -Path $env:GITHUB_OUTPUT + $outputs.Prerelease | Should -BeExactly 'true' + $outputs.Version | Should -BeExactly '[0.43.0, 1.0.0)' + $output | Should -Match 'Create a prerelease:\s+\[False\]' + $output | Should -Not -Match 'gh release create|--prerelease' + Should -Invoke git -Times 0 -Exactly + } + + It 'plans cleanup only at the effective prefix boundary for ' -ForEach @( + @{ + PrefixCase = 'the own branch after version-like text' + Prefix = 'release-1.2.3-' + TagName = 'release-1.2.3-2.0.4-feature.1' + DeleteExpected = $true + } + @{ + PrefixCase = 'another branch after identifier-like text' + Prefix = 'release-1.2.3-feature.extra-' + TagName = 'release-1.2.3-feature.extra-2.0.4-other.1' + DeleteExpected = $false + } + ) { + "VersionPrefix: '$Prefix'" | Set-Content -LiteralPath $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath + $releaseRecordsJson = ConvertTo-Json -InputObject @( + @{ tagName = 'v2.0.3'; isLatest = $true; isPrerelease = $false } + @{ tagName = $TagName; isLatest = $false; isPrerelease = $true } + ) + $githubEvent.pull_request.head.ref = 'feature' + $githubEvent.pull_request.labels = @(@{ name = 'release:skip' }) + $githubEvent.pull_request.state = 'closed' + $githubEvent.action = 'closed' + $githubEvent | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH + + $output = (& $runRelease) -join "`n" + + $deleteCommand = "WhatIf: gh release delete $TagName --cleanup-tag --yes" + $output.Contains($deleteCommand) | Should -Be $DeleteExpected + $output | Should -Not -Match 'gh release create|git tag|git push' + Should -Invoke git -Times 0 -Exactly + } + + It 'targets a prerelease at the exact pull-request head without executing publication commands' { + $githubEvent.pull_request.labels = @(@{ name = 'release:prerelease' }, @{ name = 'release:minor' }) + $githubEvent.pull_request.merge_commit_sha = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + $githubEvent | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH + + $output = (& $runRelease) -join "`n" + + $output | Should -Match 'gh release create v2\.1\.0-featurecaller\.1 ' + $output | Should -Match "--target $headSha --prerelease" + $output | Should -Match 'WhatIf: gh pr comment 42 ' + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[0] -cin @('label', 'release', 'pr') -or $args -ccontains 'POST' } + Should -Invoke git -Times 0 -Exactly -ParameterFilter { $args[0] -cne 'check-ref-format' } + } + + Context 'Stable publication from a default-branch push' { + BeforeEach { + $env:GITHUB_EVENT_NAME = 'push' + $mergedPullRequest = $githubEvent.pull_request + $mergedPullRequest.state = 'closed' + $mergedPullRequest.merged_at = '2026-01-03T00:00:00Z' + $mergedPullRequest.merge_commit_sha = $squashCommitSha + $mergedPullRequest.labels = @(@{ name = 'release:major' }) + $githubEvent = @{ + ref = 'refs/heads/main' + after = $squashCommitSha + deleted = $false + repository = $githubEvent.repository + } + $githubEvent | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH + $env:PSMODULE_AUTO_RELEASE_INPUT_WhatIf = 'false' + $stableRemote = 'https://github.com/example/repository.git' + Mock git { $global:LASTEXITCODE = 0 } + Mock gh { + $global:LASTEXITCODE = 0 + switch ($args[1]) { + 'repos/example/repository' { '{"full_name":"example/repository","default_branch":"main"}' } + 'repos/example/repository/pulls/42' { + ConvertTo-Json -InputObject $mergedPullRequest -Depth 10 -Compress + } + "repos/example/repository/commits/$squashCommitSha/pulls" { + ConvertTo-Json -InputObject @(, @($mergedPullRequest)) -Depth 10 -Compress + } + } + } -ParameterFilter { + $args[0] -ceq 'api' -and $args[1] -cin @( + 'repos/example/repository', 'repos/example/repository/pulls/42', "repos/example/repository/commits/$squashCommitSha/pulls" + ) + } + Mock gh { $global:LASTEXITCODE = 0 } -ParameterFilter { + ($args[0] -ceq 'release' -and $args[1] -ceq 'create') -or + ($args[0] -ceq 'api' -and $args[1] -ceq 'repos/example/repository/git/refs' -and $args -ccontains 'POST') + } + } + + It 'points the version tag and both enabled aliases at the squash commit' { + $null = & $runRelease + + Should -Invoke git -Times 1 -Exactly -ParameterFilter { + ($args -join ' ') -ceq "fetch --no-tags $stableRemote $squashCommitSha" + } + Should -Invoke gh -Times 1 -Exactly -ParameterFilter { + $args[0] -ceq 'api' -and $args -ccontains 'POST' -and + $args -ccontains 'ref=refs/tags/v3.0.0' -and $args -ccontains "sha=$squashCommitSha" + } + Should -Invoke gh -Times 1 -Exactly -ParameterFilter { + $args[0] -eq 'release' -and $args[1] -eq 'create' -and $args[2] -eq 'v3.0.0' -and + $args -contains '--verify-tag' -and $args[-1] -ceq $squashCommitSha -and + $args -notcontains '--prerelease' + } + Should -Invoke git -Times 1 -Exactly -ParameterFilter { + $expected = "push --no-follow-tags $stableRemote +${squashCommitSha}:refs/tags/v3 +${squashCommitSha}:refs/tags/v3.0" + ($args -join ' ') -ceq $expected + } + } + + It 'does not update disabled aliases' { + $env:PSMODULE_AUTO_RELEASE_INPUT_CreateMajorTag = 'false' + $env:PSMODULE_AUTO_RELEASE_INPUT_CreateMinorTag = 'false' + + $null = & $runRelease + + Should -Invoke git -Times 0 -Exactly -ParameterFilter { $args[0] -cin @('push', 'fetch') } + Should -Invoke gh -Times 1 -Exactly -ParameterFilter { + $args[0] -ceq 'api' -and $args -ccontains 'POST' -and $args -ccontains 'ref=refs/tags/v3.0.0' + } + } + + It 'does not publish or move aliases if GitHub rejects the version tag' { + Mock gh { $global:LASTEXITCODE = 1 } -ParameterFilter { + $args[0] -ceq 'api' -and $args -ccontains 'POST' -and $args -ccontains 'ref=refs/tags/v3.0.0' + } + + { & $runRelease } | Should -Throw '*release tag*v3.0.0*' + + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { + $args[0] -eq 'release' -and $args[1] -eq 'create' + } + Should -Invoke git -Times 0 -Exactly -ParameterFilter { $args[0] -ceq 'push' } + } + + It 'rejects a pushed SHA before writing labels or tags' -ForEach @( + @{ SourceCase = 'missing'; CommitSha = $null } + @{ SourceCase = 'branch name instead of a'; CommitSha = 'main' } + ) { + $githubEvent.after = $CommitSha + $githubEvent | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH + + { & $runRelease } | Should -Throw '*branch push*full commit SHA*' + + Should -Invoke gh -Times 0 -Exactly + Should -Invoke git -Times 0 -Exactly + } + + It 'does not write a tag if it cannot fetch the target for the enabled aliases' { + Mock git { $global:LASTEXITCODE = 1 } -ParameterFilter { $args[0] -eq 'fetch' } + + { & $runRelease } | Should -Throw '*Failed to fetch release target*' + + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { + $args[0] -cin @('label', 'release', 'pr') -or $args -ccontains 'POST' + } + Should -Invoke git -Times 0 -Exactly -ParameterFilter { $args[0] -eq 'push' } + } + } + + It 'does not write labels or tags when the event has no pull request' { + $env:GITHUB_EVENT_NAME = 'workflow_dispatch' + '{}' | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH + $env:PSMODULE_AUTO_RELEASE_INPUT_WhatIf = 'false' + $simulateLabelWrites = $true + Mock Write-GitHubWarning {} + + $null = & $runRelease + + Should -Invoke gh -Times 0 -Exactly + Should -Invoke git -Times 0 -Exactly + Should -Invoke Write-GitHubWarning -Times 1 -Exactly + } + + It 'rejects conflicting release labels instead of falling back to the default' { + $githubEvent.pull_request.labels = @(@{ name = 'release:patch' }, @{ name = 'release:major' }) + $githubEvent | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH + + { & $runRelease } | Should -Throw '*Conflicting release bump labels*' + Should -Invoke gh -Times 1 -Exactly + } + + It 'rejects invalid effective file settings before calling GitHub' -ForEach @( + @{ Yaml = 'DefaultBump: null'; Message = '*DefaultBump*' } + @{ Yaml = 'DefaultBump: date'; Message = '*Invalid DefaultBump*' } + @{ Yaml = 'WhatIf: invalid'; Message = '*WhatIf*true or false*' } + @{ Yaml = "DatePrereleaseFormat: '%'"; Message = '*DatePrereleaseFormat*format*' } + @{ Yaml = 'AutoPatching: false'; Message = '*AutoPatching*removed*' } + @{ Yaml = 'DefaultBunp: minor'; Message = '*Unsupported release setting*' } + @{ Yaml = '- patch'; Message = '*configuration must be a mapping*' } + @{ Yaml = ''; Message = '*settings file*must be a mapping*' } + ) { + $Yaml | Set-Content -LiteralPath $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath + + { & $runRelease } | Should -Throw $Message + Should -Invoke gh -Times 0 -Exactly + Should -Invoke git -Times 0 -Exactly + } +} diff --git a/tests/ReleaseDecisionSettings.Tests.ps1 b/tests/ReleaseDecisionSettings.Tests.ps1 new file mode 100644 index 0000000..2d8f345 --- /dev/null +++ b/tests/ReleaseDecisionSettings.Tests.ps1 @@ -0,0 +1,96 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute( + 'PSUseDeclaredVarsMoreThanAssignments', '', + Justification = 'The Pester cases share the bootstrap and workflow fixtures.' +)] +[CmdletBinding()] +param() + +BeforeAll { + Import-Module -Name powershell-yaml -RequiredVersion 0.4.12 + $bootstrap = Join-Path -Path $PSScriptRoot -ChildPath '..\src\Initialize-ReleaseConfiguration.ps1' +} + +Describe 'Resolving release settings from the candidate' { + BeforeEach { + $workspace = Join-Path -Path $TestDrive -ChildPath ([guid]::NewGuid().ToString('N')) + $workflowDirectory = Join-Path -Path $workspace -ChildPath '.github\workflows' + $null = New-Item -Path $workflowDirectory -ItemType Directory -Force + $workflowPath = Join-Path -Path $workflowDirectory -ChildPath 'Release.yml' + $settingsPath = Join-Path -Path $workspace -ChildPath '.github\alternate.yml' + $workflow = @' +name: Release +on: + push: + branches: [main] +jobs: + PublishStable: + if: ${{ github.event_name == 'push' && github.ref_name == github.event.repository.default_branch }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@example + - uses: ./ + with: + SettingsFilePath: .github/alternate.yml +'@ + $workflow | Set-Content -LiteralPath $workflowPath + $parameters = @{ + WorkspacePath = $workspace + OutputPath = '' + PublisherBranch = 'main' + } + } + + It 'uses the candidate settings file specified by the publisher' { + 'DefaultBump: major' | Set-Content -LiteralPath $settingsPath + + $settings = & $bootstrap @parameters + + $settings.DefaultBump | Should -BeExactly 'major' + $settings.DefaultBumpSource | Should -BeExactly 'RepositorySetting' + $settings.Mode | Should -BeExactly 'calculate' + } + + It 'uses the actual publisher override when it differs from the selected file' { + "$workflow`n DefaultBump: minor" | Set-Content -LiteralPath $workflowPath + 'DefaultBump: major' | Set-Content -LiteralPath $settingsPath + + $settings = & $bootstrap @parameters + + $settings.DefaultBump | Should -BeExactly 'minor' + $settings.DefaultBumpSource | Should -BeExactly 'ActionInput' + } + + It 'rejects a missing explicitly selected policy file instead of substituting a default' { + "$workflow`n DefaultBump: minor" | Set-Content -LiteralPath $workflowPath + + { & $bootstrap @parameters } | Should -Throw '*publisher*settings file*not found*' + } + + It 'rejects invalid candidate settings even when a publisher override is valid' { + "$workflow`n DefaultBump: minor" | Set-Content -LiteralPath $workflowPath + 'DefaultBump: invalid' | Set-Content -LiteralPath $settingsPath + + { & $bootstrap @parameters } | Should -Throw '*Invalid DefaultBump*' + } + + It 'rejects a repository setting that would put the publisher in Calculate mode' { + 'Mode: calculate' | Set-Content -LiteralPath $settingsPath + + { & $bootstrap @parameters } | Should -Throw '*publisher*publish*' + } + + It 'rejects a publisher invocation that would only Calculate' { + "$workflow`n Mode: calculate" | Set-Content -LiteralPath $workflowPath + 'DefaultBump: major' | Set-Content -LiteralPath $settingsPath + + { & $bootstrap @parameters } | Should -Throw '*publisher*publish*' + } + + It 'rejects a policy path outside the candidate checkout' { + $outside = Join-Path -Path $TestDrive -ChildPath 'runner-settings.yml' + 'DefaultBump: major' | Set-Content -LiteralPath $outside + $workflow.Replace('.github/alternate.yml', '../runner-settings.yml') | Set-Content -LiteralPath $workflowPath + + { & $bootstrap @parameters } | Should -Throw '*SettingsFilePath*inside the candidate checkout*' + } +} diff --git a/tests/Test-ReleaseDecisionContext.Tests.ps1 b/tests/Test-ReleaseDecisionContext.Tests.ps1 new file mode 100644 index 0000000..e040db2 --- /dev/null +++ b/tests/Test-ReleaseDecisionContext.Tests.ps1 @@ -0,0 +1,213 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute( + 'PSUseDeclaredVarsMoreThanAssignments', '', + Justification = 'The Pester cases and mocks share the Git and pull request fixtures.' +)] +[CmdletBinding()] +param() + +BeforeAll { + Import-Module -Name GitHub, powershell-yaml, PSSemVer + $actionDirectory = Split-Path -Path $PSScriptRoot -Parent + $scriptPath = Join-Path -Path $PSScriptRoot -ChildPath '..\src\Test-ReleaseDecisionContext.ps1' + $source = Join-Path -Path $TestDrive -ChildPath 'source' + $workspace = Join-Path -Path $TestDrive -ChildPath 'candidate' + git init --quiet -b main $source + $gitAuthor = @('-c', 'user.name=Release Test', '-c', 'user.email=release@example.test', '-c', 'commit.gpgsign=false') + $workflowDirectory = Join-Path -Path $source -ChildPath '.github\workflows' + $null = New-Item -Path $workflowDirectory -ItemType Directory -Force + $publisher = Join-Path -Path $actionDirectory -ChildPath '.github\workflows\Release.yml' + Copy-Item -LiteralPath $publisher -Destination $workflowDirectory + git -C $source add -- .github + git -C $source @gitAuthor commit --quiet -m 'Base publisher' + $baseSha = git -C $source rev-parse HEAD + '# Documentation' | Set-Content -LiteralPath (Join-Path -Path $source -ChildPath 'README.md') + git -C $source add -- README.md + git -C $source @gitAuthor commit --quiet -m 'Docs-only contribution' + $headSha = git -C $source rev-parse HEAD + $tree = git -C $source rev-parse 'HEAD^{tree}' + $mergeSha = git -C $source @gitAuthor commit-tree $tree -p $baseSha -p $headSha -m 'Candidate' + git -C $source update-ref HEAD $mergeSha + git clone --quiet --no-local --depth 1 $source $workspace +} + +AfterAll { + # Git marks loose objects read-only on Windows, but TestDrive needs to delete them. + foreach ($repositoryPath in @($source, $workspace)) { + Get-ChildItem -LiteralPath (Join-Path -Path $repositoryPath -ChildPath '.git') -Recurse -Force -File | + Where-Object IsReadOnly | ForEach-Object { $_.IsReadOnly = $false } + } +} + +Describe 'Checking the release decision snapshot' { + BeforeEach { + $repository = 'PSModule/Release-GHRepository' + $fork = 'contributor/Release-GHRepository' + $pullRequest = @{ + number = 42 + state = 'open' + head = @{ sha = $headSha; ref = 'docs'; repo = @{ full_name = $fork } } + base = @{ sha = $baseSha; ref = 'main'; repo = @{ full_name = $repository } } + labels = @(@{ name = 'documentation' }, @{ name = 'release:skip' }) + } + $eventPath = Join-Path -Path $TestDrive -ChildPath 'pull-request.json' + ConvertTo-Json -Depth 8 -InputObject @{ + repository = @{ full_name = $repository } + pull_request = $pullRequest + } | Set-Content -LiteralPath $eventPath + $current = $pullRequest + Mock gh { ConvertTo-Json -Depth 8 -InputObject $current } + $parameters = @{ + EventPath = $eventPath + Workspace = $workspace + Repository = $repository + CandidateSha = $mergeSha + } + } + + It 'verifies a fork candidate even when GitHub returns its labels in a different order' { + $current.labels = @(@{ name = 'release:skip' }, @{ name = 'documentation' }) + + $checked = & $scriptPath @parameters + + $checked.Number | Should -Be 42 + $checked.BaseSha | Should -BeExactly $baseSha + $checked.HeadSha | Should -BeExactly $headSha + $checked.MergeSha | Should -BeExactly $mergeSha + Should -Invoke gh -Times 1 -Exactly -ParameterFilter { + $args -join ' ' -ceq "api --method GET repos/$repository/pulls/42" + } + } + + It 'rejects a label-only change after calculation even when the candidate SHA is unchanged' { + $null = & $scriptPath @parameters + $current.labels = @(@{ name = 'release:patch' }) + + { & $scriptPath @parameters } | Should -Throw '*labels changed*' + } + + It 'rejects labels read by Calculate that do not match the event snapshot' { + $usedByCalculator = $current.Clone() + $usedByCalculator.labels = @(@{ name = 'release:major' }) + $parameters.CurrentPullRequest = $usedByCalculator | ConvertTo-Json -Depth 8 | ConvertFrom-Json + + { & $scriptPath @parameters } | Should -Throw '*labels changed*' + Should -Invoke gh -Times 0 -Exactly + } + + It 'rejects a pull request that was retargeted while the job was running' { + $current.base.ref = 'maintenance' + + { & $scriptPath @parameters } | Should -Throw '*target changed*' + } + + It 'rejects a live head advance against the same target branch' { + $current.head.sha = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' + + { & $scriptPath @parameters } | Should -Throw '*source changed*' + } + + It 'fails before reading labels if the checkout is not the event candidate' { + $parameters.CandidateSha = $headSha + + { & $scriptPath @parameters } | Should -Throw '*candidate merge checkout*' + Should -Invoke gh -Times 0 -Exactly + } + + It 'rejects a candidate with parents that do not match the reported head and base' { + $eventPayload = Get-Content -LiteralPath $eventPath -Raw | ConvertFrom-Json -AsHashtable + $eventPayload.pull_request.base.sha = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + $eventPayload | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $eventPath + + { & $scriptPath @parameters } | Should -Throw '*merge parents*' + Should -Invoke gh -Times 0 -Exactly + } + + It 'does not treat a missing live pull request response as empty labels' { + Mock gh { '{}' } + + { & $scriptPath @parameters } | Should -Throw '*incomplete*' + } + + It 'fails if the pull request read fails' { + Mock gh { $global:LASTEXITCODE = 1 } + + { & $scriptPath @parameters } | Should -Throw '*Could not read pull request*' + } + + It 'reports a valid skip for a docs-only fork without a write or a version' { + $actionPath = Join-Path -Path $actionDirectory -ChildPath 'action.yml' + $workflowPath = Join-Path -Path $actionDirectory -ChildPath '.github\workflows\Release-Decision.yml' + $action = ConvertFrom-Yaml -Yaml ([IO.File]::ReadAllText($actionPath)) + $workflow = ConvertFrom-Yaml -Yaml ([IO.File]::ReadAllText($workflowPath)) + $steps = $workflow.jobs.ReleaseDecision.steps + $calculate = $steps | Where-Object id -EQ 'calculate' + $settingsOutput = Join-Path -Path $TestDrive -ChildPath 'settings-output.txt' + $outputPath = Join-Path -Path $TestDrive -ChildPath 'decision-output.txt' + [IO.File]::WriteAllText($outputPath, '') + $checkEnvironment = @{ + GITHUB_ACTION = 'release' + GITHUB_BASE_REF = 'main' + GITHUB_EVENT_NAME = 'pull_request' + GITHUB_EVENT_PATH = $eventPath + GITHUB_OUTPUT = $settingsOutput + GITHUB_REPOSITORY = $repository + GITHUB_SERVER_URL = 'https://github.com' + GITHUB_SHA = $mergeSha + GITHUB_WORKSPACE = $workspace + PSMODULE_AUTO_RELEASE_ACTION_PATH = $actionDirectory + PSMODULE_AUTO_RELEASE_CHECK_PUBLISHER = $calculate.env.PSMODULE_AUTO_RELEASE_CHECK_PUBLISHER + PSMODULE_AUTO_RELEASE_INPUT_Mode = $calculate.with.Mode + PSMODULE_AUTO_RELEASE_RESOLVED_SETTINGS = '' + PSMODULE_GITHUB_SCRIPT = 'true' + RELEASE_BUMP_SOURCE = '' + RELEASE_DECISION = '' + RELEASE_PLAN = '' + RELEASE_VERSION = '' + } + $savedEnvironment = @{} + foreach ($name in $checkEnvironment.Keys) { + $savedEnvironment[$name] = [Environment]::GetEnvironmentVariable($name) + [Environment]::SetEnvironmentVariable($name, $checkEnvironment[$name]) + } + Mock Install-PSResource {} + Mock gh { + $global:LASTEXITCODE = 0 + if ($args[0] -cne 'api' -or $args -cnotcontains 'GET' -or $args -cnotcontains "repos/$repository/pulls/42") { + throw "Unexpected command: gh $($args -join ' ')" + } + ConvertTo-Json -Depth 8 -InputObject $current + } + + Push-Location -LiteralPath $actionDirectory + try { + $verify = [scriptblock]::Create(($steps | Where-Object name -EQ 'Verify the pull request snapshot').run) + $report = [scriptblock]::Create(($steps | Where-Object name -EQ 'Recheck and report the decision').run) + $bootstrap = [scriptblock]::Create(($action.runs.steps | Where-Object id -EQ 'settings').run) + $runCalculation = [scriptblock]::Create(($action.runs.steps | Where-Object id -EQ 'release').with.Script) + $null = & $verify + $null = & $bootstrap + $settingsRecord = Select-String -LiteralPath $settingsOutput -Pattern '^ReleaseSettings<<' -Context 0, 1 + $env:PSMODULE_AUTO_RELEASE_RESOLVED_SETTINGS = $settingsRecord.Context.PostContext[0] + $env:GITHUB_OUTPUT = $outputPath + $null = & $runCalculation + $result = (Get-GitHubOutput -AsHashtable).result + $env:RELEASE_DECISION = $result.Decision + $env:RELEASE_BUMP_SOURCE = $result.BumpSource + $env:RELEASE_PLAN = $result.ReleasePlan + $env:RELEASE_VERSION = $result.ReleaseVersion + $checked = & $report | ConvertFrom-Json + + $checked.Decision | Should -BeExactly 'skip' + $checked.BumpSource | Should -BeExactly 'release:skip' + $checked.SourceSha | Should -BeExactly $mergeSha + $result.Keys | Should -Not -Contain 'ReleaseVersion' + $result.Keys | Should -Not -Contain 'ReleasePlan' + Should -Invoke gh -Times 3 -Exactly + } finally { + Pop-Location + foreach ($name in $savedEnvironment.Keys) { + [Environment]::SetEnvironmentVariable($name, $savedEnvironment[$name]) + } + } + } +}