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 23ac7b5..5c65755 100644 --- a/README.md +++ b/README.md @@ -137,9 +137,19 @@ The action reads the current labels and latest stable release from the target re 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. -Use a separate read-only job for the [required release decision check][release-decision-check]. -Include `labeled` and `unlabeled` to check label changes. Do not use a path filter to skip the check. -Apply `release:skip` when a change does not need a release. +### 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 @@ -281,6 +291,7 @@ These outputs are available only in Calculate mode. For example, read `steps.cal | 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. | diff --git a/action.yml b/action.yml index d8dd15c..2ad30c4 100644 --- a/action.yml +++ b/action.yml @@ -116,6 +116,9 @@ 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 }} @@ -171,7 +174,15 @@ 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 id: release 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/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 b37f526..77f4000 100644 --- a/src/main.ps1 +++ b/src/main.ps1 @@ -89,7 +89,12 @@ LogGroup 'Loading libraries' { 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) { 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 index 0869d31..fcd20d2 100644 --- a/tests/Release-GHRepository.Calculation.Tests.ps1 +++ b/tests/Release-GHRepository.Calculation.Tests.ps1 @@ -187,8 +187,8 @@ Describe 'Release-GHRepository event release plans' { $result = & $runCalculation - $result.Keys.Count | Should -Be 2 $result.Decision | Should -BeExactly 'release' + $result.BumpSource | Should -BeExactly 'release:minor' $result.ReleaseVersion | Should -BeExactly '2.1.0-featurecalc.1' } @@ -231,13 +231,14 @@ Describe 'Release-GHRepository event release plans' { $plan.CalculatedAt | Should -BeExactly $timestamp } - It 'returns only a successful skip and does not read release history' { + It 'returns a successful skip without a version or a release history read' { $currentPullRequest.labels = @(@{ name = 'release:skip' }) $result = & $runCalculation - $result.Keys.Count | Should -Be 1 $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' } } 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]) + } + } + } +}