diff --git a/.github/workflows/Action-Test.yml b/.github/workflows/Action-Test.yml index d3a3000..d55cc24 100644 --- a/.github/workflows/Action-Test.yml +++ b/.github/workflows/Action-Test.yml @@ -56,6 +56,7 @@ jobs: - name: Action-Test uses: ./ with: + DefaultBump: patch WhatIf: true - name: Prepare caller settings diff --git a/.github/workflows/Release-Decision.yml b/.github/workflows/Release-Decision.yml new file mode 100644 index 0000000..6c3f856 --- /dev/null +++ b/.github/workflows/Release-Decision.yml @@ -0,0 +1,75 @@ +name: Release decision + +on: + pull_request: + branches: + - main + types: + - opened + - reopened + - synchronize + - labeled + - unlabeled + - edited + +concurrency: + group: ${{ github.workflow }}-${{ github.event.number }} + cancel-in-progress: true + +permissions: + contents: read + pull-requests: read + +jobs: + ReleaseDecision: + name: Release decision + runs-on: ubuntu-latest + steps: + - name: Check out the candidate merge + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Verify the pull request snapshot + 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_BUMP_SOURCE: ${{ steps.calculate.outputs.BumpSource }} + run: | + $ErrorActionPreference = 'Stop' + $checked = & '.\src\Test-ReleaseDecisionContext.ps1' + $decision = $env:RELEASE_DECISION + $version = $env:RELEASE_VERSION + $source = $env:RELEASE_BUMP_SOURCE + $hasVersion = -not [string]::IsNullOrWhiteSpace($version) + if ($decision -cnotin @('release', 'skip') -or -not $source -or + ($decision -ceq 'release') -ne $hasVersion) { + throw 'Calculate did not return a complete release decision.' + } + [ordered]@{ + PullRequest = $checked.Number + BaseBranch = $checked.BaseRef + BaseSha = $checked.BaseSha + HeadSha = $checked.HeadSha + MergeSha = $checked.MergeSha + Decision = $decision + BumpSource = $source + Candidate = $version + } | ConvertTo-Json diff --git a/README.md b/README.md index a247ea6..5c65755 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Release-GHRepository -Create GitHub releases from pull request labels and repository settings. +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. @@ -15,17 +15,20 @@ The namespace is `release`. The qualifier selects the release instruction. | `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. | Alone or with 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`. -The default is `patch`. A `release:patch`, `release:minor`, or `release:major` label overrides `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 selects prerelease mode. The `release:skip` label prevents publication. +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 `patch`, `minor`, or `major`; +- 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. @@ -33,21 +36,22 @@ The action ignores labels that are not in the table. ## How it works -During a pull request run with `WhatIf: false`, the action creates missing labels from the table. +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. -If the event has no pull request, the action does not change labels or publish a release. +Push events do not change labels. -The action publishes a prerelease for an open pull request with `release:prerelease`. -The prerelease name uses the head branch name. When the tag does not exist, the action creates it at the exact pull request head commit. +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. -A publishing run creates a stable release on a merge into the default branch unless the pull request has `release:skip`. -The version tag points to the merge commit. For a squash merge, this is the squash commit. -The action does not move an existing version tag. After publication, it sets each enabled major or minor tag to the same commit. +Only a push to the default branch can publish a stable release. The version tag points to the exact pushed commit. +If a pull request merged into the default branch at that commit, the action uses its current labels. +For a direct push without a matching pull request, set `DefaultBump` to `patch`, `minor`, or `major`. +The action does not move an existing stable version tag. After publication, it sets each enabled major or minor tag to the same commit. 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. -If `AutoCleanup` is `true`, the action deletes matching prereleases and their tags when the pull request closes. +When the pull request closes, Publish does not create a release. If `AutoCleanup` is `true`, it deletes matching prereleases and their tags. The `release:skip` label does not prevent cleanup. For cleanup, the action finds the version number after `VersionPrefix`. It then matches the exact, case-sensitive identifier for the head branch. @@ -57,7 +61,7 @@ The action uses [GitHub-Script](https://github.com/PSModule/GitHub-Script), whic ## Usage -This example shows the publishing job. +This example shows the prerelease and cleanup job. It does not publish stable releases. ```yaml name: Release-GHRepository @@ -87,17 +91,10 @@ jobs: if: ${{ github.event.pull_request.head.repo.full_name == github.repository }} runs-on: ubuntu-24.04 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 code 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 }} + ref: ${{ github.event.pull_request.base.sha }} persist-credentials: false - name: Release repository @@ -108,31 +105,114 @@ Pin the action to the full commit SHA of a published release that supports these Do not use a pull request head in a production workflow. Use a moving major tag only if the producer's release automation controls it and moves it only to compatible stable releases in that major version. -The example uses `pull_request`. The publishing job skips pull requests from forks, including on merge. -For a merge, it checks out the exact merge commit. For other events, it checks out the base commit, not the pull request head. +The publishing job skips pull requests from forks. It checks out the base commit, not the pull request head. + +### Calculate a version + +Use `Mode: calculate` to validate a release decision and get a version without publishing. +The action does not change releases, tags, labels, or comments in this mode, even when `WhatIf` is `false`. +Use a workflow token that can read contents and pull requests in the target repository. + +```yaml +- name: Calculate the release version + id: calculate + uses: PSModule/Release-GHRepository@ + with: + Mode: calculate +``` + +On `pull_request`, the action calculates a prerelease for the current open pull request. +On a branch push other than a push to the target repository's default branch, it also calculates a prerelease. +The open pull request must match the source repository, branch name, and exact pushed commit. +The `release:prerelease` label is not necessary in either case. +If more than one pull request matches, set `PullRequest` to the target `OWNER/REPO#NUMBER`. +For a push in a fork, always set `PullRequest`. +The action checks the selected pull request before it uses its labels. + +The action calculates a stable version only on a push to the target repository's default branch. +It uses the labels of a pull request with that base repository, base branch, and merge commit. +If there is no such pull request, the push needs a configured `DefaultBump` of `patch`, `minor`, or `major`. + +The action reads the current labels and latest stable release from the target repository. +If GitHub reports no latest stable release, the action uses `0.0.0` as the baseline. +A failed read, a stale pull request, or an invalid decision fails the run without outputs. + +### Check a pull request + +This repository's `Release decision` job runs on pull requests to `main`, including forks and changes that affect only documentation. +It checks the candidate merge commit and uses the release settings and literal inputs from the local publisher in `.github/workflows/Release.yml`. +The publisher must check out this repository at the workspace root before it invokes the local action. +If the workflow route or its inputs cannot be resolved, the check fails. Do not use expressions for publisher inputs that this check must evaluate. +The default settings file is optional. If the publisher names a file, include it in the candidate checkout. + +The job uses read-only permissions. It checks the current labels and revisions again before it reports its decision. +Apply `release:skip` when a change does not need a release. The job still runs and passes for a valid skip. +The job is separate from `Action-Test` and is advisory. It does not prevent merges, and a label rerun alone does not invalidate a previous pass. +See the [required check design][release-decision-check] for future enforcement. + +If a fork contribution needs publication, follow [Prerelease a fork contribution][fork-prerelease]. + +### Publish a version from Calculate -Run the [required release decision check][release-decision-check] in a separate job with read-only permissions and `WhatIf: true`. -Include `labeled` and `unlabeled` so the check runs when a label changes. -Do not use a path filter to skip the check. Apply `release:skip` when a change does not need a release. +Use the Calculate outputs from the same GitHub event and commit. Use the same version settings in both steps. +Pass `ReleaseVersion` without the tag prefix. If Calculate returns `CalculatedAt`, pass it unchanged. +Publish checks the current labels, stable release history, version settings, and target commit before it writes to GitHub. +It rejects a stale or invalid version, a conflicting tag, and a supplied version when the event cannot publish. +It does not replace a rejected value with a new version. -Use the read-only check for fork pull requests. -If a fork contribution needs a prerelease, follow [Prerelease a fork contribution][fork-prerelease]. +On an open pull request with `release:prerelease`, use these steps to preview the handoff without changing GitHub: + +```yaml +- name: Calculate the prerelease version + id: calculate + uses: PSModule/Release-GHRepository@ + with: + Mode: calculate + +- name: Preview the exact prerelease + if: ${{ steps.calculate.outputs.Decision == 'release' }} + uses: PSModule/Release-GHRepository@ + with: + Mode: publish + ReleaseVersion: ${{ steps.calculate.outputs.ReleaseVersion }} + CalculatedAt: ${{ steps.calculate.outputs.CalculatedAt }} + WhatIf: true +``` + +In another job of the same workflow run, expose both step outputs as job outputs and pass them through `needs`. +If you do not need a separate Calculate step, omit both inputs. Publish calculates a version only when the event can publish: + +```yaml +- name: Preview a prerelease with automatic version selection + uses: PSModule/Release-GHRepository@ + with: + Mode: publish + WhatIf: true +``` + +For a stable release, calculate and publish from the same default-branch push. Do not pass a prerelease version to that run. +Before you adopt this version, update any workflow that publishes stable releases on a pull request close. +This action change does not install a push trigger. Track the production transition in [#108][push-rollout]. ## Inputs -`SettingsFilePath` selects the settings file. For the other inputs, a file value overrides the default. +`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 | +| `ReleaseVersion` | Use the exact unprefixed version from Calculate. Omit it to calculate the version during Publish. | `''` | false | +| `CalculatedAt` | Pass the unchanged ISO 8601 UTC Calculate output with `ReleaseVersion` for a date-dependent prerelease. | `''` | 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 explicit bump or skip label exists. Accepts exactly `patch`, `minor`, or `major` with case-sensitive matching. | `patch` | 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 that has the same calculated prerelease tag. | `true` | false | +| `IncrementalPrerelease` | Enable prerelease numbering. When false, replace a release at the same prerelease tag. A supplied `ReleaseVersion` 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 | @@ -160,7 +240,8 @@ File selection and execution follow this order: 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`. The file must contain a YAML mapping. +Use the input names in the table as YAML keys, except `SettingsFilePath`, `ReleaseVersion`, and `CalculatedAt`. +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. @@ -168,8 +249,9 @@ 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 the source of the bump: a label, an input, a file value, or the default. -For example, if the file sets `DefaultBump: major`, omit the input to use `major`. Set the `DefaultBump` input to `patch` to use `patch`. +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. @@ -202,12 +284,27 @@ with: 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. | +| `BumpSource` | The release label or settings layer that supplied the decision. | +| `ReleaseVersion` | The calculated SemVer string without `VersionPrefix`. 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/). @@ -226,5 +323,6 @@ The caller job runs the composite action with `WhatIf: true`. These checks do no [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 +[push-rollout]: https://github.com/PSModule/Release-GHRepository/issues/108 [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 bdacac8..2ad30c4 100644 --- a/action.yml +++ b/action.yml @@ -1,11 +1,31 @@ name: Release GHRepository (by PSModule) -description: Creates GitHub releases from namespaced pull request labels and release settings. +description: Calculates versions and creates GitHub releases from pull request labels and release settings. author: PSModule branding: icon: upload-cloud color: white inputs: + 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 + ReleaseVersion: + description: >- + An exact, unprefixed SemVer from Calculate. Publish validates it against the current release plan. + Omit it to calculate the version during Publish. + required: false + CalculatedAt: + description: >- + Pass the unchanged Calculate output with ReleaseVersion for a date-dependent prerelease. + Use the ISO 8601 UTC format returned by Calculate. + required: false AutoCleanup: description: >- Delete pull-request prereleases and their tags after the pull request closes. @@ -20,17 +40,17 @@ inputs: DefaultBump: description: >- The bump when the pull request has neither a supported bump label nor release:skip. - Accepts exactly patch, minor, or major. - Effective standard default: patch. Omit or leave empty to follow repository policy. + 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. + Control whether to create or update a major tag after a stable release. Effective standard default: true. required: false CreateMinorTag: description: >- - Control whether to create a minor tag when a pull request is merged into the main branch. + Control whether to create or update a minor tag after a stable release. Effective standard default: true. required: false DatePrereleaseFormat: @@ -92,6 +112,20 @@ inputs: Effective standard default: github.workspace. A file-defined directory does not select another settings file. required: false +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 }} + 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: @@ -102,8 +136,10 @@ runs: 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: patch, 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 } @@ -118,6 +154,8 @@ runs: 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_SettingsFilePath: ${{ inputs.SettingsFilePath }} PSMODULE_AUTO_RELEASE_INPUT_DefaultBump: ${{ inputs.DefaultBump }} @@ -136,13 +174,24 @@ runs: PSMODULE_AUTO_RELEASE_INPUT_Version: ${{ inputs.Version }} PSMODULE_AUTO_RELEASE_INPUT_Prerelease: ${{ inputs.Prerelease }} run: | - $null = & (Join-Path -Path $env:PSMODULE_AUTO_RELEASE_ACTION_PATH -ChildPath 'src\Initialize-ReleaseConfiguration.ps1') + $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 = $env:GITHUB_BASE_REF + } + $bootstrap = Join-Path -Path $env:PSMODULE_AUTO_RELEASE_ACTION_PATH -ChildPath 'src\Initialize-ReleaseConfiguration.ps1' + $null = & $bootstrap @configuration - name: Release-GHRepository - uses: PSModule/GitHub-Script@8083ec1f733f00357ee4d0db0c6056686e483bc0 # v1.9.0 + 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_ReleaseVersion: ${{ inputs.ReleaseVersion }} + PSMODULE_AUTO_RELEASE_INPUT_CalculatedAt: ${{ inputs.CalculatedAt }} with: Debug: ${{ steps.settings.outputs.Debug }} Prerelease: ${{ steps.settings.outputs.Prerelease }} @@ -151,5 +200,9 @@ runs: Name: Release-GHRepository WorkingDirectory: ${{ steps.settings.outputs.WorkingDirectory }} Script: | - $releaseSettings = ConvertFrom-Json -InputObject $env:PSMODULE_AUTO_RELEASE_RESOLVED_SETTINGS - & (Join-Path -Path $env:PSMODULE_AUTO_RELEASE_ACTION_PATH -ChildPath 'src\main.ps1') -Settings $releaseSettings + $parameters = @{ + Settings = ConvertFrom-Json -InputObject $env:PSMODULE_AUTO_RELEASE_RESOLVED_SETTINGS + ReleaseVersion = $env:PSMODULE_AUTO_RELEASE_INPUT_ReleaseVersion + CalculatedAt = $env:PSMODULE_AUTO_RELEASE_INPUT_CalculatedAt + } + & (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..e31fb2e --- /dev/null +++ b/src/Get-EventReleasePlan.ps1 @@ -0,0 +1,467 @@ +#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 + version, 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 unprefixed version to validate for publication, if the caller supplied one. + [Parameter()] + [string] $ReleaseVersion, + + # 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 $ReleaseVersion) { + throw 'ReleaseVersion 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 ($ReleaseVersion) { + throw 'ReleaseVersion 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 ($ReleaseVersion) { + throw 'ReleaseVersion 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 + } +} + +$decisionParameters = @{ + Labels = $labels + DefaultBump = $Settings.DefaultBump + DefaultBumpSource = $Settings.DefaultBumpSource +} +$decision = 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 ($ReleaseVersion -and -not $eligible) { + if ($decision.Skip) { + throw 'Do not supply ReleaseVersion with release:skip.' + } + throw 'ReleaseVersion 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 ($ReleaseVersion -and $usesDate -and -not $hasCalculationTime) { + throw 'CalculatedAt is required with ReleaseVersion for a date-dependent prerelease. Pass the original Calculate output.' +} + +$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 } +if ($ReleaseVersion -and $versionPlan.ReleaseVersion -cne $ReleaseVersion) { + throw "ReleaseVersion [$ReleaseVersion] does not match the current release plan [$($versionPlan.ReleaseVersion)]. Run Calculate again." +} + +$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 ($ReleaseVersion -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 + 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..b767f79 --- /dev/null +++ b/src/Get-ReleaseWorkflowInputs.ps1 @@ -0,0 +1,129 @@ +#Requires -Version 7.2 +#Requires -Modules powershell-yaml + +<# + .SYNOPSIS + Read the supported inputs from the local release workflow. + + .DESCRIPTION + Select the publisher for the target branch. Return only literal input values. + Do not execute workflow expressions or guess unresolved values. + + .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.pull_request +if ($trigger -isnot [System.Collections.IDictionary]) { + throw 'The release workflow must have a supported pull_request trigger.' +} +foreach ($filter in $trigger.GetEnumerator()) { + if ($filter.Key -cnotin @('branches', 'types')) { + throw "The release workflow has an unsupported pull_request 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 pull_request branch filter." +} +if ($trigger.types -isnot [System.Collections.IList] -or $trigger.types -cnotcontains 'closed') { + throw 'The release workflow must handle closed pull requests.' +} + +$job = $workflow.jobs.Release +$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 Release job.' +} +$sameRepository = 'github.event.pull_request.head.repo.full_name == github.repository' +if ($job.Contains('if') -and + ($job.if -isnot [string] -or ($job.if.Trim() -replace '\s+', ' ') -cnotin @($sameRepository, ('${{ ' + $sameRepository + ' }}')))) { + throw 'The release check cannot resolve a conditional publisher job other than the same-repository guard.' +} +if ($publisher[0].Contains('if') -or $job.Contains('strategy') -or $job.Contains('needs')) { + throw 'The release check cannot resolve a conditional publisher step, publisher dependencies, 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.' + } + $currentReleaseRef = @( + '${{ github.event.action == ''closed'' && github.event.pull_request.merged' + '&& github.event.pull_request.merge_commit_sha || github.event.pull_request.base.sha }}' + ) -join ' ' + $supportedRefs = @('${{ github.sha }}', '${{ github.event.pull_request.merge_commit_sha }}', $currentReleaseRef) + if ($checkoutInputs.Contains('ref') -and + ($checkoutInputs.ref -isnot [string] -or ($checkoutInputs.ref.Trim() -replace '\s+', ' ') -cnotin $supportedRefs)) { + throw 'The publisher checkout ref must come from the pull request merge rather than another revision.' + } +} + +$inputs = @{} +if (-not $publisher[0].Contains('with')) { + return $inputs +} + +$overrides = $publisher[0].with +if ($overrides -isnot [System.Collections.IDictionary]) { + throw 'The publisher with block must contain a mapping of literal inputs.' +} +foreach ($override in $overrides.GetEnumerator()) { + $key = $override.Key + $value = $override.Value + $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 index 28488d9..a312f63 100644 --- a/src/Initialize-ReleaseConfiguration.ps1 +++ b/src/Initialize-ReleaseConfiguration.ps1 @@ -33,10 +33,15 @@ param( # The runner's output file; local callers can omit it to return settings only. [Parameter()] - [string] $OutputPath = [Environment]::GetEnvironmentVariable('GITHUB_OUTPUT') + [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 @@ -67,9 +72,25 @@ 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 - $inputs = @{} - foreach ($name in $metadata.Keys) { - $inputs[$name] = [Environment]::GetEnvironmentVariable("PSMODULE_AUTO_RELEASE_INPUT_$name") + 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 @@ -82,7 +103,6 @@ try { } $initialDirectory = ConvertTo-ReleaseSettingValue @initialParameters } - $settingsFilePath = [Environment]::GetEnvironmentVariable('PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath') if ($null -eq $settingsFilePath) { $actionDefinition = ConvertFrom-Yaml -Yaml ([IO.File]::ReadAllText($actionDefinitionPath)) $settingsFilePath = $actionDefinition.inputs.SettingsFilePath.default @@ -93,6 +113,12 @@ try { 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.' } @@ -104,6 +130,8 @@ try { 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 } @@ -115,6 +143,12 @@ try { 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) { diff --git a/src/Release-GHRepository.Helpers.psm1 b/src/Release-GHRepository.Helpers.psm1 index d19383c..950b663 100644 --- a/src/Release-GHRepository.Helpers.psm1 +++ b/src/Release-GHRepository.Helpers.psm1 @@ -46,7 +46,9 @@ function Get-ReleaseSettingSchema { if ($metadata -isnot [System.Collections.IDictionary]) { throw 'The action release standards must be a mapping of setting definitions.' } - $settingNames = @($actionDefinition.inputs.Keys | Where-Object { $_ -ne 'SettingsFilePath' }) + $validTypes = @('Boolean', 'Text', 'Bump', 'DateTimeFormat', 'VersionConstraint', 'DirectoryPath', 'ReleaseMode', 'PullRequestSelector') + $runtimeInputs = @('SettingsFilePath', 'ReleaseVersion', 'CalculatedAt') + $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]." @@ -62,7 +64,7 @@ function Get-ReleaseSettingSchema { $definition.Keys -notcontains 'Phase' -or $definition.Count -ne 3) { throw "Invalid metadata for release setting [$name]. Supply Type, Default, and Phase." } - if (@('Boolean', 'Text', 'Bump', 'DateTimeFormat', 'VersionConstraint', 'DirectoryPath') -cnotcontains $definition.Type) { + if ($validTypes -cnotcontains $definition.Type) { throw "Invalid metadata type for release setting [$name]." } if (@('Startup', 'Release') -cnotcontains $definition.Phase) { @@ -179,7 +181,7 @@ function ConvertTo-ReleaseSettingValue { # The type supplied by the action's private schema. [Parameter(Mandatory)] - [ValidateSet('Boolean', 'Text', 'Bump', 'DateTimeFormat', 'VersionConstraint', 'DirectoryPath')] + [ValidateSet('Boolean', 'Text', 'Bump', 'DateTimeFormat', 'VersionConstraint', 'DirectoryPath', 'ReleaseMode', 'PullRequestSelector')] [string] $Type, # The supplied value, including null so invalid values can be diagnosed. @@ -210,6 +212,16 @@ function ConvertTo-ReleaseSettingValue { 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) @@ -470,7 +482,7 @@ function ConvertTo-ReleaseBump { .DESCRIPTION Validate DefaultBump with case-sensitive matching and return the - corresponding internal Patch, Minor, or Major value. Require the + corresponding internal None, Patch, Minor, or Major value. Require the configured value rather than choosing a policy default. .EXAMPLE @@ -498,12 +510,13 @@ function ConvertTo-ReleaseBump { [string] $DefaultBump ) - $validDefaultBumps = @('patch', 'minor', 'major') + $validDefaultBumps = @('none', 'patch', 'minor', 'major') if ($validDefaultBumps -cnotcontains $DefaultBump) { - throw "Invalid DefaultBump [$DefaultBump]. Use exactly one of: patch, minor, major." + throw "Invalid DefaultBump [$DefaultBump]. Use exactly one of: none, patch, minor, major." } switch -CaseSensitive ($DefaultBump) { + 'none' { 'None' } 'patch' { 'Patch' } 'minor' { 'Minor' } 'major' { 'Major' } @@ -519,8 +532,8 @@ function Resolve-ReleaseDecision { 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. Require the validated effective - DefaultBump instead of loading standards or choosing a policy. + Reject conflicting release labels. If DefaultBump is none, require + a bump label or release:skip. .EXAMPLE Resolve-ReleaseDecision -Labels @('release:minor') -DefaultBump 'major' @@ -609,6 +622,10 @@ function Resolve-ReleaseDecision { } $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 { @@ -738,12 +755,127 @@ function Test-PrereleaseCreation { $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' 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 c3e15b6..77f4000 100644 --- a/src/main.ps1 +++ b/src/main.ps1 @@ -1,443 +1,305 @@ -[Diagnostics.CodeAnalysis.SuppressMessageAttribute( - 'PSAvoidLongLines', '', Justification = 'Long ternary operators are used for readability.' -)] -[Diagnostics.CodeAnalysis.SuppressMessageAttribute( - 'PSUseDeclaredVarsMoreThanAssignments', '', - Justification = 'Parameter is used in dynamic parameter validation.' -)] +#Requires -Version 7.2 + +<# + .SYNOPSIS + Run Release-GHRepository for the current GitHub Actions event. + + .DESCRIPTION + Return Calculate outputs or execute the validated Publish plan. + + .EXAMPLE + .\main.ps1 -Settings $releaseSettings + + Run the action in the mode selected by the resolved settings. + + .INPUTS + None + + You can't pipe objects to main.ps1. + + .OUTPUTS + System.String + + Operational logs for the current GitHub Actions run. +#> [CmdletBinding()] param( - # The release policy resolved by the bootstrap before GitHub-Script starts. + # The release policy resolved before GitHub-Script starts. [Parameter(Mandatory)] [ValidateNotNull()] - [PSCustomObject] $Settings + [PSCustomObject] $Settings, + + # The exact unprefixed semantic version from Calculate, if supplied. + [Parameter()] + [string] $ReleaseVersion, + + # The unchanged UTC timestamp from Calculate for a date-dependent prerelease. + [Parameter()] + [string] $CalculatedAt ) $ErrorActionPreference = 'Stop' -$releaseSettings = $Settings +$PSNativeCommandUseErrorActionPreference = $false + +$planParameters = @{ Settings = $Settings } +if ($ReleaseVersion) { + if ($Settings.Mode -cne 'publish') { + throw 'ReleaseVersion requires Mode: publish.' + } + $parsedVersion = $null + if (-not [semver]::TryParse($ReleaseVersion, [ref] $parsedVersion) -or $parsedVersion.ToString() -cne $ReleaseVersion) { + throw 'Invalid ReleaseVersion. Use an exact, unprefixed SemVer from Calculate.' + } + $planParameters.ReleaseVersion = $ReleaseVersion +} +if ($CalculatedAt) { + if (-not $ReleaseVersion) { + throw 'CalculatedAt requires ReleaseVersion.' + } + $calculationTime = [datetime]::MinValue + $parsedTime = [datetime]::TryParseExact( + $CalculatedAt, 'o', [cultureinfo]::InvariantCulture, [Globalization.DateTimeStyles]::RoundtripKind, [ref] $calculationTime + ) + if (-not $parsedTime -or $calculationTime.Kind -ne [DateTimeKind]::Utc) { + throw 'Invalid CalculatedAt. Pass the original ISO 8601 UTC value from Calculate.' + } + $planParameters.CalculationTime = $calculationTime +} $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 'Loading libraries' { - '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 + 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 $name } + Import-Module -Name PSSemVer } -LogGroup 'Set configuration' { - $autoCleanup = $releaseSettings.AutoCleanup - $defaultBump = $releaseSettings.DefaultBump - $defaultBumpSource = $releaseSettings.DefaultBumpSource - $createMajorTag = $releaseSettings.CreateMajorTag - $createMinorTag = $releaseSettings.CreateMinorTag - $datePrereleaseFormat = $releaseSettings.DatePrereleaseFormat - $incrementalPrerelease = $releaseSettings.IncrementalPrerelease - $usePRBodyAsReleaseNotes = $releaseSettings.UsePRBodyAsReleaseNotes - $usePRTitleAsReleaseName = $releaseSettings.UsePRTitleAsReleaseName - $usePRTitleAsNotesHeading = $releaseSettings.UsePRTitleAsNotesHeading - $versionPrefix = $releaseSettings.VersionPrefix - $whatIf = $releaseSettings.WhatIf - - Write-Output '-------------------------------------------------' - Write-Output "Auto cleanup enabled: [$autoCleanup]" - Write-Output "Default bump: [$defaultBump]" - Write-Output "Default bump source: [$defaultBumpSource]" - 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 '-------------------------------------------------' -} - -LogGroup 'Event information - JSON' { - $githubEventJson = Get-Content -LiteralPath $env:GITHUB_EVENT_PATH -Raw - $githubEventJson | Format-List | Out-String -} - -LogGroup 'Event information - Object' { - $githubEvent = ConvertFrom-Json -InputObject $githubEventJson - $githubEvent | Format-List | Out-String -} - -$pull_request = $githubEvent.pull_request -if (-not $pull_request) { - Write-GitHubWarning 'This is not run for a pull request. Exiting.' +if ($Settings.Mode -ceq 'calculate') { + $plan = & $planPath @planParameters + if ($env:PSMODULE_AUTO_RELEASE_CHECK_PUBLISHER -ceq 'true') { + $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 + if ($plan.CalculatedAt) { + Set-GitHubOutput -Name CalculatedAt -Value $plan.CalculatedAt + } + } return } -$defaultBranchName = (gh repo view --json defaultBranchRef | ConvertFrom-Json | Select-Object -ExpandProperty defaultBranchRef).name -if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($defaultBranchName)) { - throw 'Could not determine the repository default branch.' -} -$actionType = $githubEvent.action -$isMerged = $pull_request.merged -is [bool] -and $pull_request.merged -$prIsClosed = $pull_request.state -eq 'closed' -$prBaseRef = $pull_request.base.ref -$labels = @($pull_request.labels.name | Where-Object { $null -ne $_ }) -$decisionParameters = @{ - Labels = $labels - DefaultBump = $defaultBump - DefaultBumpSource = $defaultBumpSource -} -$releaseDecision = Resolve-ReleaseDecision @decisionParameters -$contextParameters = @{ - PullRequest = $pull_request - AllowEmptyPrereleaseName = (-not $releaseDecision.Prerelease) -} -$pullRequestReleaseContext = Resolve-PullRequestReleaseContext @contextParameters -$prHeadRef = $pullRequestReleaseContext.HeadRef -$prereleaseTarget = $pullRequestReleaseContext.PrereleaseTarget -$targetIsDefaultBranch = $prBaseRef -ceq $defaultBranchName - -Write-Output '-------------------------------------------------' -Write-Output "Default branch: [$defaultBranchName]" -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 "PR Head SHA: [$prereleaseTarget]" -Write-Output "Target is default branch: [$targetIsDefaultBranch]" -Write-Output '-------------------------------------------------' -LogGroup 'Pull request - details' { - $pull_request | Format-List | Out-String +$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 ($ReleaseVersion) { + throw 'ReleaseVersion was supplied, but this event is not eligible for publication.' + } + Write-GitHubWarning 'This event is not eligible for publication or pull request cleanup.' + return } -LogGroup 'Pull request - Labels' { - $labels | Format-List | Out-String +$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 } -$createRelease = $actionType -eq 'closed' -and $isMerged -and $prIsClosed -and $targetIsDefaultBranch -and -not $releaseDecision.Skip -$stableTarget = $null -if ($createRelease) { - $stableTarget = [string] $pull_request.merge_commit_sha - if ($stableTarget -notmatch '\A[0-9a-fA-F]{40}\z') { - throw 'A merged pull request must supply a full merge commit SHA before a stable release can publish.' - } - Write-Output "Stable target SHA: [$stableTarget]" +$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]" - if ($whatIf) { - Write-Output "WhatIf: git fetch --no-tags origin $stableTarget" - } else { - git fetch --no-tags origin $stableTarget +$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 fetch the merge commit [$stableTarget]. git exited with code [$LASTEXITCODE]." + 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.' } } -LogGroup 'Provision release labels' { - if ([string]::IsNullOrWhiteSpace($env:GITHUB_REPOSITORY)) { - throw 'GITHUB_REPOSITORY is required to provision release labels.' +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)" + } + 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]." + } + } } - foreach ($definition in Get-ReleaseLabelDefinition) { - $arguments = @( - 'label' - 'create' - $definition.Name - '--repo' - $env:GITHUB_REPOSITORY - '--color' - $definition.Color - '--description' - $definition.Description - '--force' - ) + if ($plan.ReplacePrerelease) { + $releaseDelete = @('release', 'delete', $tag, '--repo', $repositoryArgument, '--yes') + if (-not $plan.TagExists) { + $releaseDelete += '--cleanup-tag' + } if ($whatIf) { - Write-Output "WhatIf: gh $($arguments -join ' ')" + Write-Output "WhatIf: gh $($releaseDelete -join ' ')" } else { - gh @arguments + gh @releaseDelete if ($LASTEXITCODE -ne 0) { - throw "Failed to provision the canonical label [$($definition.Name)]. gh exited with code [$LASTEXITCODE]." + throw "Failed to replace prerelease [$tag]. gh exited with code [$LASTEXITCODE]." } } } -} - -$closedPullRequest = $prIsClosed -and -not $isMerged -$createPrerelease = Test-PrereleaseCreation -ReleaseDecision $releaseDecision -PullRequestClosed:$prIsClosed -$prereleaseName = $pullRequestReleaseContext.PrereleaseName -$majorRelease = $releaseDecision.Bump -eq 'Major' -$minorRelease = $releaseDecision.Bump -eq 'Minor' -$patchRelease = $releaseDecision.Bump -eq 'Patch' - -Write-Output '-------------------------------------------------' -Write-Output "Default bump applied: [$($releaseDecision.DefaultBumpApplied)]" -Write-Output "Bump source: [$($releaseDecision.BumpSource)]" -Write-Output "Skip release: [$($releaseDecision.Skip)]" -Write-Output "Create a release: [$createRelease]" -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 '-------------------------------------------------' + 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]." + } + } + } -LogGroup 'Get releases' { - $releases = gh release list --json 'createdAt,isDraft,isLatest,isPrerelease,name,publishedAt,tagName' | ConvertFrom-Json - if ($LASTEXITCODE -ne 0) { - throw "Failed to list all releases for the repo. gh exited with code [$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' } - $releases | Select-Object -Property name, isPrerelease, isLatest, publishedAt | Format-Table | Out-String -} -$latestVersion = $null -if (-not $releaseDecision.Skip) { - 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 ($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]." } } -} else { - Write-Output 'Skip selected; no release version is resolved.' -} - -Write-Output '-------------------------------------------------' -Write-Output "Latest version: [$latestVersion]" -Write-Output '-------------------------------------------------' -if (-not $releaseDecision.Skip -and ($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() + if ($createPrerelease) { + if ($whatIf) { + Write-Output "WhatIf: gh pr comment $($pullRequest.number) --repo $repositoryArgument" } else { - Write-Output 'Skipping release creation, exiting.' - return - } - - 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() + 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]." } } } - 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) { - throw "Failed to delete the release [$newVersion]. gh exited with code [$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', $prereleaseTarget, '--prerelease') - - Write-Output "gh $($releaseCreateCommand -join ' ')" - if (-not $whatIf) { - # Execute the command and capture the output - $releaseURL = gh @releaseCreateCommand - if ($LASTEXITCODE -ne 0) { - throw "Failed to create the release [$newVersion]. gh exited with code [$LASTEXITCODE]." - } - } - - if ($whatIf) { - $commentPreview = 'WhatIf: gh pr comment {0} -b "The release [{1}] has been created."' -f $pull_request.number, $newVersion - Write-Output $commentPreview - } else { - gh pr comment $pull_request.number -b "The release [$newVersion]($releaseURL) has been created." - if ($LASTEXITCODE -ne 0) { - throw "Failed to comment on the pull request. gh exited with code [$LASTEXITCODE]." - } - } + if ($aliasPush.Count -gt 0) { + if ($whatIf) { + Write-Output "WhatIf: git $($aliasPush -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") - } - - # 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 ($createRelease) { - $versionTagPush = @('push', '--no-follow-tags', 'origin', "${stableTarget}:refs/tags/$newVersion") - if ($whatIf) { - Write-Output "WhatIf: git $($versionTagPush -join ' ')" - } else { - # Do not force the version tag. A conflicting tag must stop publication. - git @versionTagPush - if ($LASTEXITCODE -ne 0) { - throw "Failed to set version tag [$newVersion] to [$stableTarget]. git exited with code [$LASTEXITCODE]." - } - } - $releaseCreateCommand += @('--verify-tag', '--target', $stableTarget) - } - - Write-Output "gh $($releaseCreateCommand -join ' ')" - if (-not $whatIf) { - gh @releaseCreateCommand - if ($LASTEXITCODE -ne 0) { - throw "Failed to create the release [$newVersion]. gh exited with code [$LASTEXITCODE]." - } - } - - if ($createRelease -and ($createMajorTag -or $createMinorTag)) { - $aliasPush = @('push', '--no-follow-tags', 'origin') - if ($createMajorTag) { - $majorTag = ('{0}{1}' -f $newVersion.Prefix, $newVersion.Major) - $aliasPush += "+${stableTarget}:refs/tags/$majorTag" - } - if ($createMinorTag) { - $minorTag = ('{0}{1}.{2}' -f $newVersion.Prefix, $newVersion.Major, $newVersion.Minor) - $aliasPush += "+${stableTarget}:refs/tags/$minorTag" - } - - if ($whatIf) { - Write-Output "WhatIf: git $($aliasPush -join ' ')" - } else { - git @aliasPush - if ($LASTEXITCODE -ne 0) { - throw "Failed to update the enabled aliases for [$newVersion]. git exited with code [$LASTEXITCODE]." - } - } + 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 = @() - if ([string]::IsNullOrEmpty($prereleaseName)) { - Write-Output 'This branch has no prerelease identifier; cleanup has no candidates.' - } else { - $prereleasesToCleanup = @( - Get-PrereleaseCleanupCandidate -Releases $releases -PrereleaseName $prereleaseName -VersionPrefix $versionPrefix +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]." + } + } } - $prereleasesToCleanup | Select-Object -Property name, publishedAt, isPrerelease, isLatest | Format-Table | Out-String } -if (($prIsClosed -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) { - throw "Failed to delete release [$relTagName]. gh exited with code [$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..6c0af49 --- /dev/null +++ b/tests/Get-ReleaseWorkflowInputs.Tests.ps1 @@ -0,0 +1,125 @@ +[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: + pull_request: + branches: [main] + types: [closed] +jobs: + Release: + if: ${{ github.event.pull_request.head.repo.full_name == github.repository }} + 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 '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 that only runs on PR events before merge' { + $workflow = $workflowFixture.Replace('types: [closed]', 'types: [opened]') + + { & $read '' -Workflow $workflow } | Should -Throw '*closed*' + } + + It 'rejects a publisher that runs on a path filter' { + $workflow = $workflowFixture.Replace('types: [closed]', "types: [closed]`n paths: ['src/**']") + + { & $read '' -Workflow $workflow } | Should -Throw '*unsupported*filter*' + } + + It 'rejects a different conditional publisher route' { + $workflow = $workflowFixture.Replace('github.event.pull_request.head.repo.full_name == github.repository', '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..fcd20d2 --- /dev/null +++ b/tests/Release-GHRepository.Calculation.Tests.ps1 @@ -0,0 +1,730 @@ +[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 + } + $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_SERVER_URL' + 'GITHUB_WORKSPACE' + 'PSMODULE_AUTO_RELEASE_ACTION_PATH' + 'PSMODULE_AUTO_RELEASE_INPUT_Mode' + 'PSMODULE_AUTO_RELEASE_INPUT_PullRequest' + 'PSMODULE_AUTO_RELEASE_INPUT_ReleaseVersion' + 'PSMODULE_AUTO_RELEASE_INPUT_CalculatedAt' + '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_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 } + $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' + } + + 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' + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[1] -ceq 'graphql' } + } + + It 'requires a valid release decision: ' -ForEach @( + @{ Case = 'no bump'; 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 'uses the configured bump on 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 'release' + $result.ReleaseVersion | Should -BeExactly '2.0.4' + $result.Keys | Should -Not -Contain 'CalculatedAt' + } + + It 'requires a configured bump when a default push has no exact merged PR' { + $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) + + & $expectFailure -Message '*No release bump*' + } + + 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 '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 output with the configured prefix at the exact PR head' { + $env:PSMODULE_AUTO_RELEASE_INPUT_Mode = 'calculate' + $env:PSMODULE_AUTO_RELEASE_INPUT_VersionPrefix = 'product-' + $result = & $runCalculation + $result.ReleaseVersion | Should -BeExactly '2.1.0-featurecalc.1' + $env:PSMODULE_AUTO_RELEASE_INPUT_Mode = 'publish' + $env:PSMODULE_AUTO_RELEASE_INPUT_ReleaseVersion = $result.ReleaseVersion + + $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 ReleaseVersion 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 'replays the UTC Calculate output 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' + $env:PSMODULE_AUTO_RELEASE_INPUT_Mode = 'calculate' + $result = & $runCalculation + $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_Mode = 'publish' + $env:PSMODULE_AUTO_RELEASE_INPUT_ReleaseVersion = $result.ReleaseVersion + $env:PSMODULE_AUTO_RELEASE_INPUT_CalculatedAt = $timestamp + $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 prefixed version'; Version = 'v2.1.0-featurecalc.1'; Message = '*ReleaseVersion*unprefixed SemVer*' } + @{ Case = 'an invalid version'; Version = '2.1'; Message = '*ReleaseVersion*unprefixed SemVer*' } + @{ Case = 'a stable version on a PR'; Version = '2.1.0'; Message = '*ReleaseVersion*does not match*' } + @{ Case = 'a different bump'; Version = '2.0.4-featurecalc.1'; Message = '*ReleaseVersion*does not match*' } + @{ Case = 'changed labels'; Message = '*ReleaseVersion*does not match*' } + @{ Case = 'changed stable history'; Message = '*ReleaseVersion*does not match*' } + @{ Case = 'changed settings'; Message = '*ReleaseVersion*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 = '*ReleaseVersion*release:skip*' } + @{ Case = 'a release request on a PR close'; Message = '*ReleaseVersion*not eligible*' } + @{ Case = 'a release request on manual dispatch'; Message = '*ReleaseVersion*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*' } + @{ Case = 'a missing date timestamp'; Message = '*CalculatedAt*required*' } + @{ Case = 'a non-UTC timestamp'; Message = '*CalculatedAt*UTC*' } + ) { + $env:PSMODULE_AUTO_RELEASE_INPUT_ReleaseVersion = $Version ?? '2.1.0-featurecalc.1' + switch ($Case) { + 'changed labels' { $currentPullRequest.labels = @(@{ name = 'release:major' }, @{ name = 'release:prerelease' }) } + 'changed stable history' { $latest.tagName = 'v2.1.0' } + 'changed settings' { $env:PSMODULE_AUTO_RELEASE_INPUT_IncrementalPrerelease = 'false' } + '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' } }) } + 'a missing date timestamp' { $env:PSMODULE_AUTO_RELEASE_INPUT_DatePrereleaseFormat = 'yyyy-MM-dd' } + 'a non-UTC timestamp' { + $env:PSMODULE_AUTO_RELEASE_INPUT_DatePrereleaseFormat = 'yyyy-MM-dd' + $env:PSMODULE_AUTO_RELEASE_INPUT_CalculatedAt = '2026-01-03T02:05:06.0000000+01:00' + } + } + + { & $runActionStep } | Should -Throw $Message + & $expectNoRepositoryWrites + } + + It 'does not confuse a longer ref with the exact version tag' { + $env:PSMODULE_AUTO_RELEASE_INPUT_ReleaseVersion = '2.1.0-featurecalc.1' + $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) { + $env:PSMODULE_AUTO_RELEASE_INPUT_ReleaseVersion = '2.1.0-featurecalc' + } + $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 'uses the exact default-branch push and its matching merged PR, not the configured bump' { + $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 + $unrelated = $currentPullRequest.Clone() + $unrelated.number = 43 + $unrelated.merge_commit_sha = $headSha + $associatedPages = , @($unrelated, $currentPullRequest) + $env:PSMODULE_AUTO_RELEASE_INPUT_Mode = 'calculate' + $result = & $runCalculation + $result.ReleaseVersion | Should -BeExactly '2.1.0' + $env:PSMODULE_AUTO_RELEASE_INPUT_Mode = 'publish' + $env:PSMODULE_AUTO_RELEASE_INPUT_ReleaseVersion = $result.ReleaseVersion + + $null = & $runActionStep + + Should -Invoke gh -Times 1 -Exactly -ParameterFilter { + $args[0] -ceq 'release' -and $args[1] -ceq 'create' -and $args -ccontains 'v2.1.0' -and + $args -ccontains $mergeSha -and $args -cnotcontains '--prerelease' + } + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[0] -cin @('label', 'pr') } + } + + It 'uses a configured bump for a direct push and honors WhatIf' { + $env:GITHUB_EVENT_NAME = 'push' + $githubEvent = $defaultPush + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'patch' + $env:PSMODULE_AUTO_RELEASE_INPUT_WhatIf = 'true' + + $output = (& $runActionStep) -join "`n" + + $output | Should -Match "release create v2\.0\.4 .+--target $mergeSha" + & $expectNoRepositoryWrites + } + + It 'rejects for a push before any repository writes' -ForEach @( + @{ Case = 'a prerelease on a default-branch push'; Message = '*ReleaseVersion*does not match*' } + @{ Case = 'a changed default branch'; Message = '*no longer matches the repository default branch*' } + @{ Case = 'a direct push without a default bump'; Message = '*No release bump*' } + @{ Case = 'a version on a push with no open PR'; Message = '*ReleaseVersion*not eligible*' } + ) { + $env:GITHUB_EVENT_NAME = 'push' + $githubEvent = $defaultPush + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'patch' + $env:PSMODULE_AUTO_RELEASE_INPUT_ReleaseVersion = '2.0.4' + switch ($Case) { + 'a prerelease on a default-branch push' { $env:PSMODULE_AUTO_RELEASE_INPUT_ReleaseVersion = '2.0.4-featurecalc.1' } + 'a changed default branch' { $liveDefaultBranch = 'renamed' } + 'a direct push without a default bump' { + $env:PSMODULE_AUTO_RELEASE_INPUT_DefaultBump = 'none' + $env:PSMODULE_AUTO_RELEASE_INPUT_ReleaseVersion = $null + } + 'a version on a push with no open PR' { + $githubEvent = $push + $openPages = , @() + } + } + + { & $runActionStep } | Should -Throw $Message + & $expectNoRepositoryWrites + } + + It 'does not publish a stable release on a merged PR close but still cleans its prerelease' { + $githubEvent.action = 'closed' + $eventPullRequest.state = 'closed' + $eventPullRequest.merged = $true + $eventPullRequest.merge_commit_sha = $mergeSha + $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 index 4464dab..4869873 100644 --- a/tests/Release-GHRepository.Helpers.Tests.ps1 +++ b/tests/Release-GHRepository.Helpers.Tests.ps1 @@ -94,8 +94,10 @@ Describe 'Resolve-ReleaseConfiguration' { It 'applies every documented controller default when settings are omitted' { $result = Resolve-ReleaseConfiguration @resolveConfiguration $expected = [ordered]@{ + Mode = 'publish' + PullRequest = '' AutoCleanup = $true - DefaultBump = 'patch' + DefaultBump = 'none' CreateMajorTag = $true CreateMinorTag = $true DatePrereleaseFormat = '' @@ -209,12 +211,12 @@ Describe 'Resolve-ReleaseConfiguration' { Should -Throw '*WhatIf*true or false*' } - It 'rejects an explicit invalid DefaultBump [] instead of selecting patch' -ForEach @( + It 'rejects an explicit invalid DefaultBump []' -ForEach @( @{ Value = '' } @{ Value = $null } @{ Value = 'Patch' } @{ Value = 'date' } - @{ Value = 'none' } + @{ Value = 'NONE' } @{ Value = 1 } @{ Value = @('patch', 'minor') } ) { @@ -276,12 +278,26 @@ Describe 'Resolve-ReleaseConfiguration' { } It 'records the action input as the default source even when it equals the shared default' { - $result = Resolve-ReleaseConfiguration @resolveConfiguration -Inputs @{ DefaultBump = 'patch' } + $result = Resolve-ReleaseConfiguration @resolveConfiguration -Inputs @{ DefaultBump = 'none' } - $result.DefaultBump | Should -BeExactly 'patch' + $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' } @@ -598,6 +614,7 @@ Describe 'Get-PrereleaseCleanupCandidate' { Describe 'ConvertTo-ReleaseBump' { It 'converts to ' -ForEach @( + @{ DefaultBump = 'none'; Expected = 'None' } @{ DefaultBump = 'patch'; Expected = 'Patch' } @{ DefaultBump = 'minor'; Expected = 'Minor' } @{ DefaultBump = 'major'; Expected = 'Major' } @@ -613,7 +630,7 @@ Describe 'ConvertTo-ReleaseBump' { @{ DefaultBump = '' } @{ DefaultBump = 'Patch' } @{ DefaultBump = 'prerelease' } - @{ DefaultBump = 'none' } + @{ DefaultBump = 'None' } @{ DefaultBump = $null } ) { { ConvertTo-ReleaseBump -DefaultBump $DefaultBump } | diff --git a/tests/Release-GHRepository.Tests.ps1 b/tests/Release-GHRepository.Tests.ps1 index 3b076b9..4fe0a48 100644 --- a/tests/Release-GHRepository.Tests.ps1 +++ b/tests/Release-GHRepository.Tests.ps1 @@ -10,6 +10,7 @@ $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' @@ -140,7 +141,7 @@ Describe 'Release-GHRepository configuration bootstrap' { $settings.Prerelease | Should -BeFalse $settings.Version | Should -BeExactly '' $settings.WorkingDirectory | Should -BeExactly $workspace - $settings.DefaultBump | Should -BeExactly 'patch' + $settings.DefaultBump | Should -BeExactly 'none' $settings.DefaultBumpSource | Should -BeExactly 'SharedDefault' $outputs = & $readBootstrapOutputs -Path $env:GITHUB_OUTPUT $outputs.Count | Should -Be 6 @@ -150,7 +151,7 @@ Describe 'Release-GHRepository configuration bootstrap' { $outputs.Version | Should -BeExactly '' $outputs.WorkingDirectory | Should -BeExactly $workspace $releaseSettings = ConvertFrom-Json -InputObject $outputs.ReleaseSettings - $releaseSettings.DefaultBump | Should -BeExactly 'patch' + $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 @@ -340,28 +341,13 @@ 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' - 'PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath' - 'PSMODULE_AUTO_RELEASE_INPUT_AutoCleanup' - 'PSMODULE_AUTO_RELEASE_INPUT_DefaultBump' - 'PSMODULE_AUTO_RELEASE_INPUT_CreateMajorTag' - 'PSMODULE_AUTO_RELEASE_INPUT_CreateMinorTag' - 'PSMODULE_AUTO_RELEASE_INPUT_DatePrereleaseFormat' - 'PSMODULE_AUTO_RELEASE_INPUT_IncrementalPrerelease' - 'PSMODULE_AUTO_RELEASE_INPUT_UsePRTitleAsReleaseName' - 'PSMODULE_AUTO_RELEASE_INPUT_UsePRBodyAsReleaseNotes' - 'PSMODULE_AUTO_RELEASE_INPUT_UsePRTitleAsNotesHeading' - 'PSMODULE_AUTO_RELEASE_INPUT_VersionPrefix' - 'PSMODULE_AUTO_RELEASE_INPUT_WhatIf' - 'PSMODULE_AUTO_RELEASE_INPUT_Debug' - 'PSMODULE_AUTO_RELEASE_INPUT_Verbose' - 'PSMODULE_AUTO_RELEASE_INPUT_WorkingDirectory' - 'PSMODULE_AUTO_RELEASE_INPUT_Version' - 'PSMODULE_AUTO_RELEASE_INPUT_Prerelease' - ) + ) + @($actionDefinition.inputs.Keys | ForEach-Object { "PSMODULE_AUTO_RELEASE_INPUT_$_" }) $savedEnvironment = @{} foreach ($name in $environmentNames) { $savedEnvironment[$name] = [Environment]::GetEnvironmentVariable($name) @@ -371,6 +357,8 @@ Describe 'Release-GHRepository caller compatibility' { } $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')) @@ -379,14 +367,15 @@ Describe 'Release-GHRepository caller compatibility' { $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' } - head = @{ ref = 'feature/caller'; sha = $headSha } + base = @{ ref = 'main'; repo = @{ full_name = $env:GITHUB_REPOSITORY } } + head = @{ ref = 'feature/caller'; sha = $headSha; repo = @{ full_name = $env:GITHUB_REPOSITORY } } labels = @() } } @@ -396,11 +385,23 @@ Describe 'Release-GHRepository caller compatibility' { $simulateLabelWrites = $false Mock Install-PSResource {} Mock Write-GitHubNotice {} - Mock git { throw 'A caller compatibility test must never invoke git.' } + 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] -eq 'repo' -and $args[1] -eq 'view') { - '{"defaultBranchRef":{"name":"main"}}' + 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') { @@ -423,15 +424,29 @@ Describe 'Release-GHRepository caller compatibility' { } } - It 'uses action standards without repository settings or injected input defaults' { + 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+\[patch\]' + $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 ' + $output | Should -Match 'gh release create v2\.0\.4-featurecaller\.1 ' $output.Contains($authoredBody) | Should -BeTrue - Should -Invoke gh -Times 2 -Exactly + } + + 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 } @@ -456,7 +471,7 @@ Describe 'Release-GHRepository caller compatibility' { $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 -Destination $fixtureSource + 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 @@ -508,8 +523,7 @@ Describe 'Release-GHRepository caller compatibility' { $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 -Match 'gh release create v2\.1\.0 ' - Should -Invoke gh -Times 2 -Exactly + $output | Should -Not -Match 'gh release create' } } finally { Pop-Location @@ -519,18 +533,16 @@ Describe 'Release-GHRepository caller compatibility' { It 'uses the declared SettingsFilePath default when the file is ' -ForEach @( @{ - FileState = 'present' - FilePresent = $true - ExpectedBump = 'minor' - ExpectedSource = 'RepositorySetting' - ExpectedVersion = 'v2.1.0' + FileState = 'present' + FilePresent = $true + ExpectedBump = 'minor' + ExpectedSource = 'RepositorySetting' } @{ - FileState = 'absent' - FilePresent = $false - ExpectedBump = 'patch' - ExpectedSource = 'SharedDefault' - ExpectedVersion = 'v2.0.4' + FileState = 'absent' + FilePresent = $false + ExpectedBump = 'none' + ExpectedSource = 'SharedDefault' } ) { $defaultSettingsPath = '.github\auto-release.yml' @@ -538,6 +550,9 @@ Describe 'Release-GHRepository caller compatibility' { $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 @@ -551,8 +566,7 @@ Describe 'Release-GHRepository caller compatibility' { $output | Should -Match "Default bump:\s+\[$ExpectedBump\]" $output | Should -Match "Default bump source:\s+\[$ExpectedSource\]" - $output | Should -Match "gh release create $([regex]::Escape($ExpectedVersion)) " - Should -Invoke gh -Times 2 -Exactly + $output | Should -Not -Match 'gh release create' Should -Invoke git -Times 0 -Exactly } @@ -573,8 +587,7 @@ Describe 'Release-GHRepository caller compatibility' { $output = (& $runRelease) -join "`n" $output | Should -Match 'Default bump:\s+\[minor\]' - $output | Should -Match 'gh release create v2\.1\.0 ' - Should -Invoke gh -Times 2 -Exactly + $output | Should -Not -Match 'gh release create' } It 'keeps repository policy when the runner supplies empty release inputs' { @@ -594,32 +607,28 @@ VersionPrefix: '' $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 -Match 'gh release create 2\.1\.0 ' - Should -Invoke gh -Times 2 -Exactly + $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' - ExpectedVersion = 'v3.0.0' + InputState = 'omitted' + InputValue = $null + ExpectedBump = 'major' + ExpectedSource = 'RepositorySetting' } @{ - InputState = 'empty' - InputValue = '' - ExpectedBump = 'major' - ExpectedSource = 'RepositorySetting' - ExpectedVersion = 'v3.0.0' + InputState = 'empty' + InputValue = '' + ExpectedBump = 'major' + ExpectedSource = 'RepositorySetting' } @{ - InputState = 'equal to the standard' - InputValue = 'patch' - ExpectedBump = 'patch' - ExpectedSource = 'ActionInput' - ExpectedVersion = 'v2.0.4' + InputState = 'an explicit patch' + InputValue = 'patch' + ExpectedBump = 'patch' + ExpectedSource = 'ActionInput' } ) { if ($null -ne $InputValue) { @@ -631,37 +640,47 @@ VersionPrefix: '' $output | Should -Match "Default bump:\s+\[$ExpectedBump\]" $output | Should -Match "Default bump source:\s+\[$ExpectedSource\]" - $output | Should -Match "gh release create $([regex]::Escape($ExpectedVersion)) " - Should -Invoke gh -Times 2 -Exactly + $output | Should -Not -Match 'gh release create' Should -Invoke git -Times 0 -Exactly } - It 'keeps action standards when all release inputs are empty' { + 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:\s+\[patch\]' - $output | Should -Match 'Default bump source:\s+\[SharedDefault\]' - $output | Should -Match 'gh release create v2\.0\.4 ' - Should -Invoke gh -Times 2 -Exactly + $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 = 'dependencies' }) + $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 ' + $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\)' - Should -Invoke gh -Times 2 -Exactly } It 'ignores dependency, retired, and bare labels when using the caller default' { @@ -677,7 +696,7 @@ VersionPrefix: '' $output | Should -Match 'Default bump applied:\s+\[True\]' $output | Should -Match 'Create a prerelease:\s+\[False\]' - $output | Should -Match 'gh release create v2\.1\.0 ' + $output | Should -Not -Match 'gh release create' } It 'lets a named DefaultBump override repository policy' { @@ -689,8 +708,7 @@ VersionPrefix: '' $output | Should -Match 'Default bump:\s+\[minor\]' $output | Should -Match 'Default bump source:\s+\[ActionInput\]' $output | Should -Match 'Bump source:\s+\[ActionInput\]' - $output | Should -Match 'gh release create v2\.1\.0 ' - Should -Invoke gh -Times 2 -Exactly + $output | Should -Not -Match 'gh release create' } It 'applies named patch and false while an empty text input keeps file policy' { @@ -709,8 +727,7 @@ VersionPrefix: v $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 -Match 'gh release create v2\.0\.4 ' - Should -Invoke gh -Times 2 -Exactly + $output | Should -Not -Match 'gh release create' } It 'does not mask an invalid file value with a valid explicit caller override' { @@ -722,13 +739,14 @@ VersionPrefix: v } 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 2 -Exactly + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[0] -ceq 'label' } Should -Invoke git -Times 0 -Exactly } @@ -737,18 +755,17 @@ VersionPrefix: v DatePrereleaseFormat: "'fixed'" '@ | Set-Content -LiteralPath $env:PSMODULE_AUTO_RELEASE_INPUT_SettingsFilePath $env:PSMODULE_AUTO_RELEASE_INPUT_DatePrereleaseFormat = '' - $githubEvent.pull_request.labels = @(@{ name = 'release:prerelease' }) + $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 ' - Should -Invoke gh -Times 2 -Exactly - Should -Invoke git -Times 0 -Exactly } 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 = '' @@ -756,7 +773,7 @@ DatePrereleaseFormat: "'fixed'" $output | Should -Match 'What if mode:\s+\[True\]' $output | Should -Match 'WhatIf: gh label create ' - Should -Invoke gh -Times 2 -Exactly + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[0] -ceq 'label' } Should -Invoke git -Times 0 -Exactly } @@ -770,7 +787,6 @@ DatePrereleaseFormat: "'fixed'" $output | Should -Match 'Version prefix:\s+\[inherit\]' $output | Should -Match 'Skipping release creation\.' - Should -Invoke gh -Times 2 -Exactly Should -Invoke git -Times 0 -Exactly } @@ -816,20 +832,21 @@ DatePrereleaseFormat: "'fixed'" $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 gh -Times 2 -Exactly Should -Invoke Write-GitHubNotice -Times 0 -Exactly } - It 'validates a skipped branch even when it has no ASCII prerelease identifier' { + 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 2 -Exactly + Should -Invoke gh -Times 0 -Exactly Should -Invoke git -Times 0 -Exactly } @@ -848,7 +865,7 @@ DatePrereleaseFormat: "'fixed'" $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 2 -Exactly + Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[1] -ceq 'graphql' } Should -Invoke git -Times 0 -Exactly } @@ -869,13 +886,13 @@ WhatIf: true $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 -Match 'gh release create v3\.0\.0 ' - Should -Invoke gh -Times 2 -Exactly + $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 @@ -886,9 +903,7 @@ Version: '[0.43.0, 1.0.0)' $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 -Match 'gh release create v2\.0\.4 ' - $output | Should -Not -Match '--prerelease' - Should -Invoke gh -Times 2 -Exactly + $output | Should -Not -Match 'gh release create|--prerelease' Should -Invoke git -Times 0 -Exactly } @@ -922,7 +937,6 @@ Version: '[0.43.0, 1.0.0)' $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 gh -Times 2 -Exactly Should -Invoke git -Times 0 -Exactly } @@ -936,35 +950,59 @@ Version: '[0.43.0, 1.0.0)' $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 2 -Exactly - Should -Invoke git -Times 0 -Exactly + 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 merged pull request' { + Context 'Stable publication from a default-branch push' { BeforeEach { - $githubEvent.action = 'closed' - $githubEvent.pull_request.merged = $true - $githubEvent.pull_request.state = 'closed' - $githubEvent.pull_request.merge_commit_sha = $squashCommitSha - $githubEvent.pull_request.labels = @(@{ name = 'release:major' }) + $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' - $simulateLabelWrites = $true + $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] -eq 'release' -and $args[1] -eq 'create' + ($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 3 -Exactly Should -Invoke git -Times 1 -Exactly -ParameterFilter { - ($args -join ' ') -ceq "fetch --no-tags origin $squashCommitSha" + ($args -join ' ') -ceq "fetch --no-tags $stableRemote $squashCommitSha" } - Should -Invoke git -Times 1 -Exactly -ParameterFilter { - ($args -join ' ') -ceq "push --no-follow-tags origin ${squashCommitSha}:refs/tags/v3.0.0" + 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 @@ -972,7 +1010,8 @@ Version: '[0.43.0, 1.0.0)' $args -notcontains '--prerelease' } Should -Invoke git -Times 1 -Exactly -ParameterFilter { - ($args -join ' ') -ceq "push --no-follow-tags origin +${squashCommitSha}:refs/tags/v3 +${squashCommitSha}:refs/tags/v3.0" + $expected = "push --no-follow-tags $stableRemote +${squashCommitSha}:refs/tags/v3 +${squashCommitSha}:refs/tags/v3.0" + ($args -join ' ') -ceq $expected } } @@ -982,65 +1021,52 @@ Version: '[0.43.0, 1.0.0)' $null = & $runRelease - Should -Invoke git -Times 1 -Exactly -ParameterFilter { $args[0] -eq 'push' } - Should -Invoke git -Times 1 -Exactly -ParameterFilter { - ($args -join ' ') -ceq "push --no-follow-tags origin ${squashCommitSha}:refs/tags/v3.0.0" + 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 Git rejects the version tag' { - Mock git { $global:LASTEXITCODE = 1 } -ParameterFilter { - $args[0] -eq 'push' -and $args -contains "${squashCommitSha}: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 '*version tag*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 1 -Exactly -ParameterFilter { $args[0] -eq 'push' } + Should -Invoke git -Times 0 -Exactly -ParameterFilter { $args[0] -ceq 'push' } } - It 'rejects a merge SHA before writing labels or tags' -ForEach @( - @{ SourceCase = 'missing'; MergeSha = $null } - @{ SourceCase = 'branch name instead of a'; MergeSha = 'main' } + It 'rejects a pushed SHA before writing labels or tags' -ForEach @( + @{ SourceCase = 'missing'; CommitSha = $null } + @{ SourceCase = 'branch name instead of a'; CommitSha = 'main' } ) { - $githubEvent.pull_request.merge_commit_sha = $MergeSha + $githubEvent.after = $CommitSha $githubEvent | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH - { & $runRelease } | Should -Throw '*merge commit SHA*' + { & $runRelease } | Should -Throw '*branch push*full commit SHA*' - Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[0] -eq 'label' -or $args[0] -eq 'release' } + Should -Invoke gh -Times 0 -Exactly Should -Invoke git -Times 0 -Exactly } - It 'does not write labels or tags if it cannot fetch the squash commit' { + 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 the merge commit*' - - Should -Invoke gh -Times 0 -Exactly -ParameterFilter { $args[0] -eq 'label' -or $args[0] -eq 'release' } - Should -Invoke git -Times 0 -Exactly -ParameterFilter { $args[0] -eq 'push' } - } - - It 'does not publish a stable release on ' -ForEach @( - @{ Case = 'a label change after merge'; Action = 'labeled'; Base = 'main' } - @{ Case = 'a merge into a different branch'; Action = 'closed'; Base = 'Main' } - ) { - $githubEvent.action = $Action - $githubEvent.pull_request.base.ref = $Base - $githubEvent | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $env:GITHUB_EVENT_PATH - - $null = & $runRelease + { & $runRelease } | Should -Throw '*Failed to fetch release target*' Should -Invoke gh -Times 0 -Exactly -ParameterFilter { - $args[0] -eq 'release' -and $args[1] -eq 'create' + $args[0] -cin @('label', 'release', 'pr') -or $args -ccontains 'POST' } - Should -Invoke git -Times 0 -Exactly + 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 diff --git a/tests/ReleaseDecisionSettings.Tests.ps1 b/tests/ReleaseDecisionSettings.Tests.ps1 new file mode 100644 index 0000000..597a60e --- /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: + pull_request: + branches: [main] + types: [closed] +jobs: + Release: + 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..efe565d --- /dev/null +++ b/tests/Test-ReleaseDecisionContext.Tests.ps1 @@ -0,0 +1,210 @@ +[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_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_VERSION = $result.ReleaseVersion + $checked = & $report | ConvertFrom-Json + + $checked.Decision | Should -BeExactly 'skip' + $checked.BumpSource | Should -BeExactly 'release:skip' + $checked.MergeSha | Should -BeExactly $mergeSha + $result.Keys | Should -Not -Contain 'ReleaseVersion' + Should -Invoke gh -Times 3 -Exactly + } finally { + Pop-Location + foreach ($name in $savedEnvironment.Keys) { + [Environment]::SetEnvironmentVariable($name, $savedEnvironment[$name]) + } + } + } +}