diff --git a/.github/scripts/Invoke-ReleaseFixture.ps1 b/.github/scripts/Invoke-ReleaseFixture.ps1 new file mode 100644 index 0000000..885b301 --- /dev/null +++ b/.github/scripts/Invoke-ReleaseFixture.ps1 @@ -0,0 +1,88 @@ +#Requires -Version 7.4 + +<# + .SYNOPSIS + Resolve a candidate or drive one case in the release fixture repository. + + .DESCRIPTION + Run only in the producer's main-branch dispatch workflow. Read GH_TOKEN from the current step. + + .EXAMPLE + ./Invoke-ReleaseFixture.ps1 -Mode Resolve -PullRequest '109' +#> +[CmdletBinding(SupportsShouldProcess)] +param( + # Resolve a producer SHA, start a fixture case, or verify a merged fixture case. + [Parameter(Mandatory)] + [ValidateSet('Resolve', 'Start', 'Verify')] + [string] $Mode, + + # Producer pull request number in Resolve mode or fixture pull request number in Verify mode. + [Parameter()] + [AllowEmptyString()] + [string] $PullRequest, + + # Scenario name in Start mode. + [Parameter()] + [string] $Scenario, + + # Resolved producer SHA in Start mode. + [Parameter()] + [string] $Candidate +) + +$ErrorActionPreference = 'Stop' + +if ($env:GITHUB_EVENT_NAME -cne 'workflow_dispatch' -or $env:GITHUB_REPOSITORY -cne 'PSModule/Release-GHRepository' -or + $env:GITHUB_REF -cne 'refs/heads/main') { + throw 'Run this driver only from a manual dispatch on PSModule/Release-GHRepository main.' +} +Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath 'ReleaseFixture.psm1') + +switch ($Mode) { + 'Resolve' { + $sha = Resolve-ReleaseFixtureCandidate -PullRequest $PullRequest + Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value "sha=$sha" -Encoding utf8 + Write-Information -MessageData "Candidate commit: $sha" -InformationAction Continue + return + } + 'Start' { + $caseId = "$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" + if (-not $PSCmdlet.ShouldProcess("Fixture case $caseId", 'Start')) { + return + } + $case = Start-ReleaseFixtureCase -Scenario $Scenario -Candidate $Candidate -CaseId $caseId -Confirm:$false + Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Value @( + "Fixture pull request: [#$($case.number)]($($case.url))" + '' + "Case: $($case.caseId) | Scenario: $($case.scenario) | Candidate: $($case.candidate) | Head: $($case.head)" + '' + ) + Write-Information -MessageData "Opened $($case.url)" -InformationAction Continue + if ($case.scenario -ceq 'missing-decision') { + Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Value 'Close this pull request without merging.' -Encoding utf8 + } + Add-ReleaseFixtureLabel -Case $case -Confirm:$false + $runType = 'Open pull request' + } + 'Verify' { + $case = Get-MergedReleaseFixtureCase -PullRequest $PullRequest + Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Value @( + "Fixture pull request: [#$($case.number)]($($case.url))" + '' + "Case: $($case.caseId) | Scenario: $($case.scenario) | Candidate: $($case.candidate) | Squash SHA: $($case.source)" + '' + ) + $runType = 'Final push' + } +} + +$report = Wait-ReleaseFixtureReport -Case $case +Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Value @( + "${runType} run: [$($report.run)]($($report.run))" + '' +) +if ($null -ne $report.tag) { + Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Value "Tag: $($report.tag)" -Encoding utf8 +} +Write-Information -MessageData "Verified $($case.event) evidence: $($report.run)" -InformationAction Continue diff --git a/.github/scripts/ReleaseFixture.psm1 b/.github/scripts/ReleaseFixture.psm1 new file mode 100644 index 0000000..3403529 --- /dev/null +++ b/.github/scripts/ReleaseFixture.psm1 @@ -0,0 +1,606 @@ +#Requires -Version 7.4 + +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest + +$producerRepo = 'PSModule/Release-GHRepository' +$fixtureRepo = 'PSModule/Release-GHRepository-Test' +$producerApi = "/repos/$producerRepo" +$fixtureApi = "/repos/$fixtureRepo" +$fixtureId = 1477027955 +$fixtureUrl = "https://github.com/$fixtureRepo" +$shaPattern = '\A[0-9a-f]{40}\z' +$versionCore = 'v(?0|[1-9][0-9]*)\.(?0|[1-9][0-9]*)\.(?0|[1-9][0-9]*)' +$scenarioLabels = @{ + preview = 'release:patch' + staged = 'release:patch' + 'one-step' = 'release:patch' + 'configured-default' = '' + 'missing-decision' = '' + skip = 'release:skip' + 'ci-failure' = 'release:patch' +} + +function Invoke-ReleaseFixtureRequest { + <# + .SYNOPSIS + Send a REST request to GitHub.com using only the supplied step token. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [string] $Path, + + [Parameter()] + [ValidateSet('GET', 'POST', 'PUT')] + [string] $Method = 'GET', + + [Parameter()] + [hashtable] $Body, + + [Parameter()] + [switch] $Paged + ) + + $value = [Environment]::GetEnvironmentVariable('GH_TOKEN') + if ([string]::IsNullOrWhiteSpace($value)) { + throw 'GH_TOKEN must be set for this step.' + } + + $request = @{ + Method = $Method + Headers = @{ + Accept = 'application/vnd.github+json' + Authorization = "Bearer $value" + 'X-GitHub-Api-Version' = '2026-03-10' + } + MaximumRedirection = 0 + ConnectionTimeoutSeconds = 20 + OperationTimeoutSeconds = 20 + SkipHttpErrorCheck = $true + } + if ($null -ne $Body) { + $request.ContentType = 'application/json' + $request.Body = ConvertTo-Json -InputObject $Body -Depth 10 -Compress + } + + $page = 1 + $uri = "https://api.github.com$Path" + $separator = '?' + if ($Path.Contains('?')) { + $separator = '&' + } + do { + $request.Uri = $uri + if ($Paged) { + $request.Uri += "${separator}per_page=100&page=$page" + } + $response = Invoke-WebRequest @request + if ([int] $response.StatusCode -notin 200, 201) { + throw "GitHub API $Method $Path returned HTTP $($response.StatusCode)." + } + + $data = ConvertFrom-Json -InputObject $response.Content -AsHashtable -NoEnumerate + if ($Paged -and $data -isnot [array]) { + throw "GitHub API $Method $Path did not return a list." + } + $data + $page++ + } while ($Paged -and $data.Count -eq 100) +} + +function Get-ReleaseFixtureMain { + <# + .SYNOPSIS + Read the exact commit at a repository's main ref. + #> + [OutputType([string])] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [string] $RepositoryApi + ) + + $ref = Invoke-ReleaseFixtureRequest -Path "$RepositoryApi/git/ref/heads/main" + if ($ref['object']['type'] -cne 'commit' -or $ref['object']['sha'] -cnotmatch $shaPattern) { + throw "No valid main commit was returned for $RepositoryApi." + } + $ref['object']['sha'] +} + +function Resolve-ReleaseFixtureCandidate { + <# + .SYNOPSIS + Resolve a producer commit that declares the fixture action contract. + #> + [OutputType([string])] + [CmdletBinding()] + param( + [Parameter()] + [AllowEmptyString()] + [ValidatePattern('\A(?:[1-9][0-9]*)?\z')] + [string] $PullRequest = '' + ) + + if ($PullRequest -ceq '') { + $candidate = Get-ReleaseFixtureMain -RepositoryApi $producerApi + } else { + $pull = Invoke-ReleaseFixtureRequest -Path "$producerApi/pulls/$PullRequest" + if ($pull.number -ne $PullRequest -or $pull.state -cne 'open' -or $pull.base.ref -cne 'main' -or + $null -eq $pull.base.repo -or $null -eq $pull.head.repo -or + $pull.base.repo.full_name -cne $producerRepo -or $pull.head.repo.full_name -cne $producerRepo -or + $null -eq $pull.base.repo.id -or $pull.base.repo.id -ne $pull.head.repo.id) { + throw "Producer pull request #$PullRequest must be an open same-repository pull request to main." + } + if ($pull.head.sha -cnotmatch $shaPattern) { + throw "Producer pull request #$PullRequest did not return a valid head SHA." + } + $candidate = $pull.head.sha + } + + Assert-ReleaseFixtureCandidateContract -Candidate $candidate + $candidate +} + +function Assert-ReleaseFixtureCandidateContract { + <# + .SYNOPSIS + Check the declared inputs and outputs without running candidate code. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [string] $Candidate + ) + + $hint = 'Supply candidate_pr for an open producer pull request that supports the fixture contract.' + $file = Invoke-ReleaseFixtureRequest -Path "$producerApi/contents/action.yml?ref=$Candidate" + if ($file.type -cne 'file' -or $file.encoding -cne 'base64') { + throw "Expected a base64-encoded action.yml at $Candidate. $hint" + } + + $yaml = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($file.content)) + $PSNativeCommandUseErrorActionPreference = $false + $json = $yaml | yq eval-all --input-format yaml --output-format json --no-colors '[.]' - 2>$null + $invalidYaml = "Expected one YAML mapping in action.yml at $Candidate. $hint" + if ($LASTEXITCODE -ne 0) { + throw $invalidYaml + } + $documents = ConvertFrom-Json -InputObject ($json -join "`n") -AsHashtable -NoEnumerate + if ($documents -isnot [array] -or $documents.Count -ne 1 -or $documents[0] -isnot [System.Collections.IDictionary]) { + throw $invalidYaml + } + + $required = [ordered] @{ + inputs = 'Mode', 'DefaultBump', 'ReleasePlan', 'WhatIf' + outputs = 'Decision', 'BumpSource', 'ReleaseVersion', 'ReleasePlan' + } + $missing = foreach ($section in $required.Keys) { + $entries = $documents[0][$section] + foreach ($name in $required[$section]) { + if ($entries -isnot [System.Collections.IDictionary] -or $name -cnotin $entries.Keys -or + $entries[$name] -isnot [System.Collections.IDictionary]) { + "$section.$name" + } + } + } + if ($missing) { + throw "The action.yml at $Candidate does not declare the required fixture inputs and outputs: $($missing -join ', '). $hint" + } +} + +function Get-ReleaseFixtureJson { + <# + .SYNOPSIS + Read a JSON object from an immutable fixture commit. + #> + [OutputType([System.Collections.IDictionary])] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [string] $Path, + + [Parameter(Mandatory)] + [string] $Commit + ) + + $file = Invoke-ReleaseFixtureRequest -Path "$fixtureApi/contents/${Path}?ref=$Commit" + if ($file.type -cne 'file' -or $file.encoding -cne 'base64') { + throw "$Path at $Commit must be a base64-encoded file." + } + $json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($file.content)) + $document = ConvertFrom-Json -InputObject $json -AsHashtable -NoEnumerate + if ($document -isnot [System.Collections.IDictionary]) { + throw "$Path at $Commit must contain a JSON object." + } + $document +} + +function Get-ReleaseFixtureBaseline { + <# + .SYNOPSIS + Find the source commit of the greatest published stable fixture version. + #> + [OutputType([string])] + [CmdletBinding()] + param() + + $stablePattern = "\A$versionCore\z" + $versions = foreach ($release in (Invoke-ReleaseFixtureRequest -Path "$fixtureApi/releases" -Paged)) { + if ($release.draft -ceq $false -and $release.prerelease -ceq $false -and $release.tag_name -cmatch $stablePattern) { + [pscustomobject] @{ + Tag = $release.tag_name + Major = [bigint] $Matches.major + Minor = [bigint] $Matches.minor + Patch = [bigint] $Matches.patch + } + } + } + $latest = $versions | Sort-Object -Property Major, Minor, Patch -Descending -Top 1 + if ($null -eq $latest) { + 'initial' + return + } + + $ref = Invoke-ReleaseFixtureRequest -Path "$fixtureApi/git/ref/tags/$($latest.Tag)" + $target = $ref.object + for ($depth = 0; $depth -lt 16 -and $target.type -ceq 'tag' -and $target.sha -cmatch $shaPattern; $depth++) { + $tag = Invoke-ReleaseFixtureRequest -Path "$fixtureApi/git/tags/$($target.sha)" + $target = $tag.object + } + if ($target.type -cne 'commit' -or $target.sha -cnotmatch $shaPattern) { + throw "Stable fixture tag $($latest.Tag) did not resolve to a commit." + } + $commit = Invoke-ReleaseFixtureRequest -Path "$fixtureApi/git/commits/$($target.sha)" + if ($commit.sha -cne $target.sha) { + throw "GitHub did not return the commit at stable fixture tag $($latest.Tag)." + } + $commit.sha +} + +function Test-ReleaseFixturePullRequest { + <# + .SYNOPSIS + Check that Shelly opened a same-repository fixture pull request to main. + #> + [OutputType([bool])] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [System.Collections.IDictionary] $PullRequest + ) + + $base = $PullRequest.base + $head = $PullRequest.head + $author = $PullRequest.user + $null -ne $base.repo -and $null -ne $head.repo -and $null -ne $author -and $base.ref -ceq 'main' -and + $base.repo.id -eq $fixtureId -and $base.repo.full_name -ceq $fixtureRepo -and + $head.repo.id -eq $fixtureId -and $head.repo.full_name -ceq $fixtureRepo -and + $author.id -eq 314722336 -and $author.login -ceq 'psmodule-s-shelly[bot]' -and $author.type -ceq 'Bot' +} + +function Start-ReleaseFixtureCase { + <# + .SYNOPSIS + Open a fixture pull request with one synthetic case commit. + + .EXAMPLE + Start-ReleaseFixtureCase -Scenario staged -Candidate ('a' * 40) -CaseId '123-2' + #> + [OutputType([hashtable])] + [CmdletBinding(SupportsShouldProcess)] + param( + [Parameter(Mandatory)] + [string] $Scenario, + + [Parameter(Mandatory)] + [string] $Candidate, + + [Parameter(Mandatory)] + [ValidatePattern('\A[1-9][0-9]*-[1-9][0-9]*\z')] + [string] $CaseId + ) + + if ($Scenario -cnotin $scenarioLabels.Keys -or $Candidate -cnotmatch $shaPattern) { + throw 'Supply a defined fixture scenario and a lowercase candidate SHA.' + } + $repository = Invoke-ReleaseFixtureRequest -Path $fixtureApi + if ($repository.id -ne $fixtureId -or $repository.full_name -cne $fixtureRepo -or $repository.default_branch -cne 'main') { + throw 'The fixture repository identity or default branch does not match the driver.' + } + foreach ($open in (Invoke-ReleaseFixtureRequest -Path "$fixtureApi/pulls?state=open" -Paged)) { + if ($open.head.ref -clike 'release-fixture/*') { + if (-not (Test-ReleaseFixturePullRequest -PullRequest $open)) { + continue + } + throw "Fixture pull request #$($open.number) is already open. Finish or close it before starting another case." + } + } + + $main = Get-ReleaseFixtureMain -RepositoryApi $fixtureApi + $contract = Get-ReleaseFixtureJson -Path 'tests/FixtureContract.json' -Commit $main + if ($contract.schema -isnot [long] -or $contract.schema -ne 2 -or + $contract.scenarios -isnot [System.Collections.IDictionary] -or $contract.scenarios.Count -ne $scenarioLabels.Count) { + throw "The fixture contract at $main must use schema 2 with the supported scenario map." + } + foreach ($name in $scenarioLabels.Keys) { + if ($name -cnotin $contract.scenarios.Keys -or $contract.scenarios[$name] -isnot [string] -or + $contract.scenarios[$name] -cne $scenarioLabels[$name]) { + throw "The label for scenario '$name' in the fixture contract at $main does not match the driver." + } + } + $label = $contract.scenarios[$Scenario] + + $baseline = Get-ReleaseFixtureBaseline + if ($Scenario -cin 'configured-default', 'missing-decision' -and $baseline -cne $main) { + throw "Fixture main must match the published stable source before '$Scenario'. Publish an explicit patch case first." + } + if ($baseline -cne 'initial' -and $baseline -cne $main) { + $comparison = Invoke-ReleaseFixtureRequest -Path "$fixtureApi/compare/$baseline...$main" + if ($comparison.status -cne 'ahead') { + throw "Fixture main at $main does not descend from the published stable source at $baseline." + } + } + $activity = 'opened' + if ($label -cne '') { + $encodedLabel = [uri]::EscapeDataString($label) + $fixtureLabel = Invoke-ReleaseFixtureRequest -Path "$fixtureApi/labels/$encodedLabel" + if ($fixtureLabel.name -cne $label) { + throw "Fixture label '$label' is not available." + } + $activity = 'labeled' + } + if ((Get-ReleaseFixtureMain -RepositoryApi $fixtureApi) -cne $main) { + throw 'Fixture main changed during setup. Start the case again.' + } + + $branch = "release-fixture/$CaseId" + if (-not $PSCmdlet.ShouldProcess("$fixtureRepo/$branch", 'Create a case branch, a commit, and a pull request')) { + return + } + $null = Invoke-ReleaseFixtureRequest -Method POST -Path "$fixtureApi/git/refs" -Body @{ + ref = "refs/heads/$branch" + sha = $main + } + $caseJson = ConvertTo-Json -InputObject @{ scenario = $Scenario; candidate = $Candidate } -Compress + $created = Invoke-ReleaseFixtureRequest -Method PUT -Path "$fixtureApi/contents/tests/cases/$CaseId.json" -Body @{ + branch = $branch + message = "Add release fixture case $CaseId" + content = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("$caseJson`n")) + } + $head = $created.commit.sha + if ($head -cnotmatch $shaPattern -or $created.commit.parents.Count -ne 1 -or $created.commit.parents[0].sha -cne $main) { + throw "The commit on $branch must have fixture main at $main as its only parent." + } + if ((Get-ReleaseFixtureMain -RepositoryApi $fixtureApi) -cne $main) { + throw "Fixture main changed before opening the pull request. The unmerged case branch is $branch." + } + $notes = @( + "Synthetic fixture case $CaseId tests the '$Scenario' scenario with producer commit $Candidate." + 'This release also covers any fixture maintenance changes since the last stable release.' + '' + "" + ) -join "`n" + $pull = Invoke-ReleaseFixtureRequest -Method POST -Path "$fixtureApi/pulls" -Body @{ + base = 'main' + head = $branch + title = "Test release fixture: $Scenario ($CaseId)" + body = $notes + } + if ($pull.number -notmatch '\A[1-9][0-9]*\z') { + throw "GitHub did not return a pull request number for $branch." + } + $url = "$fixtureUrl/pull/$($pull.number)" + if (-not (Test-ReleaseFixturePullRequest -PullRequest $pull) -or $pull.state -cne 'open' -or + $pull.head.ref -cne $branch -or $pull.head.sha -cne $head -or $pull.base.sha -cne $main) { + throw "The new fixture pull request does not match the selected base and case head: $url" + } + @{ + number = $pull.number + url = $url + caseId = $CaseId + candidate = $Candidate + scenario = $Scenario + event = 'pull_request' + activity = $activity + head = $head + label = $label + } +} + +function Add-ReleaseFixtureLabel { + <# + .SYNOPSIS + Add the case label after the fixture pull request opens. + #> + [CmdletBinding(SupportsShouldProcess)] + param( + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Case + ) + + if ($Case.label -ceq '' -or -not $PSCmdlet.ShouldProcess($Case.url, "Add label '$($Case.label)'")) { + return + } + $body = @{ labels = @($Case.label) } + $labels = @(Invoke-ReleaseFixtureRequest -Method POST -Path "$fixtureApi/issues/$($Case.number)/labels" -Body $body) + if ($labels.Count -eq 0 -or $Case.label -cnotin $labels.name) { + throw "GitHub did not attach label '$($Case.label)' to $($Case.url)." + } +} + +function Get-MergedReleaseFixtureCase { + <# + .SYNOPSIS + Recover the case identity and exact squash source from a merged fixture pull request. + #> + [OutputType([hashtable])] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [ValidatePattern('\A[1-9][0-9]*\z')] + [string] $PullRequest + ) + + $pull = Invoke-ReleaseFixtureRequest -Path "$fixtureApi/pulls/$PullRequest" + $url = "$fixtureUrl/pull/$PullRequest" + if ($pull.number -ne $PullRequest -or -not (Test-ReleaseFixturePullRequest -PullRequest $pull)) { + throw "Not a same-repository fixture pull request opened by Shelly: $url" + } + if ($pull.state -cne 'closed' -or $pull.merged -isnot [bool] -or -not $pull.merged) { + throw "The fixture pull request has not been merged: $url" + } + $caseRef = [regex]::Match($pull.head.ref, '\Arelease-fixture/([1-9][0-9]*-[1-9][0-9]*)\z') + if (-not $caseRef.Success -or $pull.commits -ne 1 -or + $pull.head.sha -cnotmatch $shaPattern -or $pull.merge_commit_sha -cnotmatch $shaPattern) { + throw "The fixture pull request does not have the expected branch and single commit: $url" + } + $caseId = $caseRef.Groups[1].Value + $head = $pull.head.sha + $source = $pull.merge_commit_sha + $path = "tests/cases/$caseId.json" + $commit = Invoke-ReleaseFixtureRequest -Path "$fixtureApi/commits/$source" + if ($commit.sha -cne $source -or $commit.parents.Count -ne 1 -or $commit.files.Count -ne 1 -or + $commit.files[0].filename -cne $path -or $commit.files[0].status -cne 'added') { + throw "Expected a squash commit at $source that only adds $path." + } + + $original = Get-ReleaseFixtureJson -Path $path -Commit $head + $merged = Get-ReleaseFixtureJson -Path $path -Commit $source + if ($original.Count -ne 2 -or $merged.Count -ne 2 -or + $original.candidate -isnot [string] -or $original.candidate -cnotmatch $shaPattern -or + $original.scenario -isnot [string] -or $original.scenario -cnotin $scenarioLabels.Keys -or + $merged.candidate -isnot [string] -or $merged.candidate -cne $original.candidate -or + $merged.scenario -isnot [string] -or $merged.scenario -cne $original.scenario) { + throw "The case payload at the merged source does not match the fixture pull request head: $url" + } + if ($original.scenario -ceq 'missing-decision') { + throw "The missing-decision case must be closed without merging: $url" + } + @{ + number = $pull.number + url = $url + caseId = $caseId + candidate = $original.candidate + scenario = $original.scenario + event = 'push' + head = $head + source = $source + } +} + +function Find-ReleaseFixtureReport { + <# + .SYNOPSIS + Select and validate the latest bot report bound to the exact fixture case. + #> + [OutputType([System.Collections.IDictionary])] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [AllowEmptyCollection()] + [object[]] $Comments, + + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Case + ) + + $reportPattern = '\A[ \t]*\r?\n\s*```json[ \t]*\r?\n(?[\s\S]+?)\r?\n```[ \t\r\n]*\z' + $runPattern = "\A$([regex]::Escape($fixtureUrl))/actions/runs/[1-9][0-9]*\z" + # The comments endpoint returns comments in ascending ID order. + for ($index = $Comments.Count - 1; $index -ge 0; $index--) { + $author = $Comments[$index]['user'] + $body = $Comments[$index]['body'] + if ($null -eq $author -or $author['id'] -ne 41898282 -or $author['login'] -cne 'github-actions[bot]' -or + $author['type'] -cne 'Bot' -or $body -isnot [string] -or $body -cnotmatch $reportPattern) { + continue + } + try { + $report = ConvertFrom-Json -InputObject $Matches.json -AsHashtable -NoEnumerate -ErrorAction Stop + } catch [System.ArgumentException] { + continue + } + if ($report -isnot [System.Collections.IDictionary] -or $report['schema'] -isnot [long] -or $report['schema'] -ne 2) { + continue + } + $sameCase = $true + foreach ($field in 'caseId', 'candidate', 'scenario', 'event', 'head') { + if ($report[$field] -isnot [string] -or $report[$field] -cne $Case[$field]) { + $sameCase = $false + break + } + } + $activity = $report['activity'] + $source = $report['source'] + if (-not $sameCase -or + ($Case.event -ceq 'pull_request' -and ($activity -isnot [string] -or $activity -cne $Case.activity)) -or + ($Case.event -ceq 'push' -and ($source -isnot [string] -or $source -cne $Case.source))) { + continue + } + + $run = $report['run'] + if ($run -isnot [string] -or $run -cnotmatch $runPattern) { + throw "Fixture case $($Case.caseId) returned an invalid run URL." + } + if ($source -isnot [string] -or $source -cnotmatch $shaPattern -or + $report['testedSource'] -isnot [string] -or $report['testedSource'] -cne $source) { + throw "Fixture report testedSource must match source. See $run." + } + if ($report['verified'] -isnot [bool] -or -not $report['verified'] -or $report['oracle'] -isnot [string] -or + $report['oracle'] -cne 'success') { + throw "Fixture report must be verified and have a successful oracle. See $run." + } + $tag = $report['tag'] + $stableWrite = $Case.event -ceq 'push' -and $Case.scenario -cin 'staged', 'one-step', 'configured-default' + if ($stableWrite) { + if ($tag -isnot [string] -or $tag -cnotmatch "\A$versionCore\z") { + throw "Fixture push report must include the published stable tag. See $run." + } + } elseif (-not $report.Contains('tag') -or $null -ne $tag) { + throw "A non-publishing fixture report must have a null tag. See $run." + } + $report + return + } +} + +function Wait-ReleaseFixtureReport { + <# + .SYNOPSIS + Wait up to ten minutes for a case report without querying the Actions run status. + #> + [OutputType([System.Collections.IDictionary])] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Case + ) + + $elapsed = [Diagnostics.Stopwatch]::StartNew() + $limit = [TimeSpan]::FromMinutes(10) + while ($elapsed.Elapsed -lt $limit) { + $comments = @(Invoke-ReleaseFixtureRequest -Path "$fixtureApi/issues/$($Case.number)/comments" -Paged) + if ($elapsed.Elapsed -ge $limit) { + break + } + $report = Find-ReleaseFixtureReport -Comments $comments -Case $Case + if ($null -ne $report) { + $report + return + } + $delay = [Math]::Min(10000, ($limit - $elapsed.Elapsed).TotalMilliseconds) + if ($delay -gt 0) { + Start-Sleep -Milliseconds $delay + } + } + throw "No matching $($Case.event) report for fixture case $($Case.caseId) within ten minutes. See $($Case.url)." +} + +Export-ModuleMember -Function @( + 'Resolve-ReleaseFixtureCandidate' + 'Start-ReleaseFixtureCase' + 'Add-ReleaseFixtureLabel' + 'Get-MergedReleaseFixtureCase' + 'Find-ReleaseFixtureReport' + 'Wait-ReleaseFixtureReport' +) diff --git a/.github/workflows/Fixture-Driver-Test.yml b/.github/workflows/Fixture-Driver-Test.yml new file mode 100644 index 0000000..d638f0f --- /dev/null +++ b/.github/workflows/Fixture-Driver-Test.yml @@ -0,0 +1,22 @@ +name: Fixture Driver Test + +on: + pull_request: + +permissions: {} + +jobs: + FixtureDriver: + name: Fixture driver unit tests + runs-on: ubuntu-24.04 + permissions: + contents: read + steps: + - name: Check out the repository + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + persist-credentials: false + + - name: Test the fixture driver without credentials + shell: pwsh + run: Invoke-Pester -CI -Path ./tests/ReleaseFixture.Tests.ps1 diff --git a/.github/workflows/Fixture-Test.yml b/.github/workflows/Fixture-Test.yml new file mode 100644 index 0000000..e444536 --- /dev/null +++ b/.github/workflows/Fixture-Test.yml @@ -0,0 +1,132 @@ +name: Fixture Test + +on: + workflow_dispatch: + # checkov:skip=CKV_GHA_7:Validated inputs select a fixture case. This workflow does not build or publish a producer artifact. + inputs: + scenario: + description: Scenario for a new fixture pull request (ignored for verification) + type: choice + default: preview + options: + - preview + - staged + - one-step + - configured-default + - missing-decision + - skip + - ci-failure + candidate_pr: + description: Open producer pull request number. Omit only if producer main supports the fixture contract. + type: string + fixture_pr: + description: Merged fixture pull request number (verifies the push instead of starting a case) + type: string + +permissions: {} + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false + +defaults: + run: + shell: pwsh + +jobs: + Start: + name: Open and verify a fixture pull request + if: >- + github.event_name == 'workflow_dispatch' && + github.repository == 'PSModule/Release-GHRepository' && + github.ref == 'refs/heads/main' && + inputs.fixture_pr == '' + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: read + pull-requests: read + steps: + - name: Confirm the exact repository and ref + run: | + if ($env:GITHUB_REPOSITORY -cne 'PSModule/Release-GHRepository' -or $env:GITHUB_REF -cne 'refs/heads/main') { + throw 'This workflow can run only on PSModule/Release-GHRepository main.' + } + + - name: Check out the trusted workflow commit + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ github.workflow_sha }} + persist-credentials: false + + - name: Resolve the candidate SHA and check the fixture contract + id: candidate + env: + GH_TOKEN: ${{ github.token }} + CANDIDATE_PR: ${{ inputs.candidate_pr }} + run: ./.github/scripts/Invoke-ReleaseFixture.ps1 -Mode Resolve -PullRequest $env:CANDIDATE_PR + + - name: Mint a fixture write token + id: fixture-token + uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 + with: + client-id: ${{ secrets.SHELLY_CLIENT_ID }} + private-key: ${{ secrets.SHELLY_PRIVATE_KEY }} + owner: PSModule + repositories: Release-GHRepository-Test + permission-contents: write + permission-pull-requests: write + + - name: Start the case and verify the pull request report + env: + GH_TOKEN: ${{ steps.fixture-token.outputs.token }} + CANDIDATE_SHA: ${{ steps.candidate.outputs.sha }} + SCENARIO: ${{ inputs.scenario }} + run: ./.github/scripts/Invoke-ReleaseFixture.ps1 -Mode Start -Scenario $env:SCENARIO -Candidate $env:CANDIDATE_SHA + + Verify: + name: Verify the fixture push report + if: >- + github.event_name == 'workflow_dispatch' && + github.repository == 'PSModule/Release-GHRepository' && + github.ref == 'refs/heads/main' && + inputs.fixture_pr != '' + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: read + steps: + - name: Confirm the exact repository, ref, and continuation input + env: + CANDIDATE_PR: ${{ inputs.candidate_pr }} + FIXTURE_PR: ${{ inputs.fixture_pr }} + run: | + if ($env:GITHUB_REPOSITORY -cne 'PSModule/Release-GHRepository' -or $env:GITHUB_REF -cne 'refs/heads/main') { + throw 'This workflow can run only on PSModule/Release-GHRepository main.' + } + if ($env:FIXTURE_PR -cnotmatch '\A[1-9][0-9]*\z' -or $env:CANDIDATE_PR) { + throw 'Supply only the fixture pull request number to verify a push.' + } + + - name: Check out the trusted workflow commit + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ github.workflow_sha }} + persist-credentials: false + + - name: Mint a fixture read token + id: fixture-token + uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 + with: + client-id: ${{ secrets.SHELLY_CLIENT_ID }} + private-key: ${{ secrets.SHELLY_PRIVATE_KEY }} + owner: PSModule + repositories: Release-GHRepository-Test + permission-contents: read + permission-pull-requests: read + + - name: Verify the push report for the squash commit + env: + GH_TOKEN: ${{ steps.fixture-token.outputs.token }} + FIXTURE_PR: ${{ inputs.fixture_pr }} + run: ./.github/scripts/Invoke-ReleaseFixture.ps1 -Mode Verify -PullRequest $env:FIXTURE_PR diff --git a/docs/Fixture-Test.md b/docs/Fixture-Test.md new file mode 100644 index 0000000..e3ad956 --- /dev/null +++ b/docs/Fixture-Test.md @@ -0,0 +1,41 @@ +# Test a release candidate in the fixture repository + +Maintainers can run [Fixture Test](../.github/workflows/Fixture-Test.yml) from `main` in this repository after the +[fixture repository](https://github.com/PSModule/Release-GHRepository-Test) has the schema-2 contract and workflows. + +| Input | Start a case | Verify a push | +| --- | --- | --- | +| `scenario` | `preview` (default), `staged`, `one-step`, `configured-default`, `missing-decision`, `skip`, or `ci-failure` | Ignored | +| `candidate_pr` | Number of an open pull request from this repository to `main`. Omit only if producer `main` supports the fixture contract. | Omit | +| `fixture_pr` | Omit | Number of the merged fixture pull request | + +The driver reads `action.yml` at the selected commit before it requests a fixture write token. The action must declare the +`Mode`, `DefaultBump`, `ReleasePlan`, and `WhatIf` inputs and the `Decision`, `BumpSource`, `ReleaseVersion`, and `ReleasePlan` +outputs. If producer `main` does not declare them, select a compatible pull request with `candidate_pr`. + +1. Start one case. The driver opens a fixture pull request and links it in the job summary. It waits up to ten minutes for the + fixture report for the `labeled` event, or the `opened` event if the case has no label. +2. Read the open-run link in the job summary. Close `missing-decision` without merging. For a case that needs push evidence, use + the fixture repository's normal independent approval and squash merge. The driver does not approve, merge, or close pull requests. +3. After the squash merge, dispatch again with `fixture_pr`. The driver uses a read-only token and links the final run for the exact + squash commit. It checks the bot's verification and oracle results, not the overall workflow status. + +The `staged`, `one-step`, and `configured-default` push reports must include a stable tag. All other reports must use `tag: null`. + +Finish or close the open fixture pull request before you start another case. If you merge it, verify its push report before you start +another case. If fixture `main` is not at the greatest published stable release source, complete an explicit patch case such as `staged` +before you start `configured-default` or `missing-decision`. The driver includes the exact stable-to-main range in the pull request notes. + +The producer checks out only its workflow commit. Shelly credentials are used only to issue a token scoped to the fixture repository. +The driver sends only the scenario and exact candidate SHA as case data; it does not supply Shelly credentials to fixture jobs. + +## Run unit tests without credentials + +[Fixture Driver Test](../.github/workflows/Fixture-Driver-Test.yml) runs the unit tests on pull requests. To run them locally +from the repository root, use PowerShell 7.4 or later, Pester 5.7.1 or later, and [yq v4](https://github.com/mikefarah/yq) on `PATH`: + +```powershell +Invoke-Pester -Path ./tests/ReleaseFixture.Tests.ps1 +``` + +These tests substitute the driver's REST boundary. They do not use credentials or exercise the live fixture workflows. diff --git a/tests/ReleaseFixture.Tests.ps1 b/tests/ReleaseFixture.Tests.ps1 new file mode 100644 index 0000000..ad73127 --- /dev/null +++ b/tests/ReleaseFixture.Tests.ps1 @@ -0,0 +1,493 @@ +#Requires -Version 7.4 + +BeforeAll { + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..' -AdditionalChildPath '.github', 'scripts', 'ReleaseFixture.psm1') + + $script:candidate = 'a' * 40 + $script:headSha = 'b' * 40 + $script:mainSha = 'c' * 40 + $script:squashSha = 'd' * 40 + $script:producer = '/repos/PSModule/Release-GHRepository' + $script:fixture = '/repos/PSModule/Release-GHRepository-Test' + $script:runUrl = 'https://github.com/PSModule/Release-GHRepository-Test/actions/runs/50' + $script:fixtureRepo = @{ id = 1477027955; full_name = 'PSModule/Release-GHRepository-Test' } + $script:shelly = @{ id = 314722336; login = 'psmodule-s-shelly[bot]'; type = 'Bot' } + $script:contract = @{ + schema = 2 + scenarios = @{ + preview = 'release:patch' + staged = 'release:patch' + 'one-step' = 'release:patch' + 'configured-default' = '' + 'missing-decision' = '' + skip = 'release:skip' + 'ci-failure' = 'release:patch' + } + } + + function ConvertTo-TestReportComment { + <# + .SYNOPSIS + Create an anonymous report comment with selected field overrides. + #> + [OutputType([hashtable])] + [CmdletBinding()] + param( + [Parameter()] + [hashtable] $Fields = @{}, + + [Parameter()] + [long] $AuthorId = 41898282 + ) + + $report = @{ + schema = 2 + caseId = '123-2' + candidate = $script:candidate + scenario = 'staged' + event = 'pull_request' + activity = 'labeled' + head = $script:headSha + source = $script:mainSha + testedSource = $script:mainSha + verified = $true + oracle = 'success' + run = $script:runUrl + tag = $null + } + foreach ($key in $Fields.Keys) { + $report[$key] = $Fields[$key] + } + @{ + user = @{ login = 'github-actions[bot]'; id = $AuthorId; type = 'Bot' } + body = ( + '', + '```json', + ($report | ConvertTo-Json -Compress), + '```' + ) -join "`n" + } + } +} + +Describe 'Resolve-ReleaseFixtureCandidate' { + BeforeEach { + $script:producerRepo = @{ id = 100; full_name = 'PSModule/Release-GHRepository' } + $script:pull = @{ + number = 109 + state = 'open' + base = @{ ref = 'main'; repo = $script:producerRepo } + head = @{ ref = 'topic'; repo = $script:producerRepo; sha = $script:candidate } + } + $action = @' +name: Test release action +inputs: {Mode: {}, DefaultBump: {}, ReleasePlan: {}, WhatIf: {}} +outputs: + Decision: {value: release} + BumpSource: {value: 'release:patch'} + ReleaseVersion: {value: '1.0.0'} + ReleasePlan: {value: '{}'} +'@ + $script:candidateMetadataPath = "$script:producer/contents/action.yml?ref=$script:candidate" + $script:mainMetadataPath = "$script:producer/contents/action.yml?ref=$script:mainSha" + $script:metadata = @{ + $script:candidateMetadataPath = $action + $script:mainMetadataPath = $action + } + + Mock Invoke-ReleaseFixtureRequest -ModuleName ReleaseFixture { + if ($Method -and $Method -ne 'GET') { + throw 'Expected a read-only request.' + } + switch ($Path) { + "$script:producer/pulls/109" { $script:pull } + "$script:producer/git/ref/heads/main" { @{ object = @{ type = 'commit'; sha = $script:mainSha } } } + default { + if (-not $script:metadata.ContainsKey($Path)) { + throw "Unexpected request: $Path" + } + @{ + type = 'file' + encoding = 'base64' + content = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($script:metadata[$Path])) + } + } + } + } + } + + It 'uses the exact producer pull request head' { + Resolve-ReleaseFixtureCandidate -PullRequest '109' | Should -BeExactly $script:candidate + Should -Invoke -CommandName Invoke-ReleaseFixtureRequest -ModuleName ReleaseFixture -Times 1 -Exactly -ParameterFilter { + $Path -ceq $script:candidateMetadataPath + } + } + + It 'reads the current main SHA when no pull request is supplied' { + Resolve-ReleaseFixtureCandidate | Should -BeExactly $script:mainSha + Should -Invoke -CommandName Invoke-ReleaseFixtureRequest -ModuleName ReleaseFixture -Times 1 -Exactly -ParameterFilter { + $Path -ceq $script:mainMetadataPath + } + } + + It 'requires a compatible candidate_pr if main does not support the fixture contract' { + $script:metadata[$script:mainMetadataPath] = 'inputs: {WhatIf: {description: Preview}}' + { Resolve-ReleaseFixtureCandidate } | Should -Throw '*candidate_pr*' + } + + It 'rejects a producer pull request that does not declare the required version output' { + $action = $script:metadata[$script:candidateMetadataPath] + $script:metadata[$script:candidateMetadataPath] = $action.Replace(' ReleaseVersion:', ' LegacyVersion:') + { Resolve-ReleaseFixtureCandidate -PullRequest '109' } | Should -Throw '*outputs.ReleaseVersion*' + } + + It 'rejects malformed candidate action metadata' { + $script:metadata[$script:candidateMetadataPath] = 'inputs: {' + { Resolve-ReleaseFixtureCandidate -PullRequest '109' } | Should -Throw '*action.yml*' + } + + It 'rejects a fork even when the head SHA is available' { + $script:pull.head.repo = @{ id = 101; full_name = 'example/Release-GHRepository' } + { Resolve-ReleaseFixtureCandidate -PullRequest '109' } | Should -Throw '*open same-repository*' + } + + It 'rejects a pull request not targeting main' { + $script:pull.base.ref = 'maintenance' + { Resolve-ReleaseFixtureCandidate -PullRequest '109' } | Should -Throw '*open same-repository*' + } + + It 'rejects a closed pull request' { + $script:pull.state = 'closed' + { Resolve-ReleaseFixtureCandidate -PullRequest '109' } | Should -Throw '*open same-repository*' + } + + It 'rejects an arbitrary ref in place of a number before making a request' { + { Resolve-ReleaseFixtureCandidate -PullRequest 'refs/heads/topic' } | Should -Throw + Should -Invoke -CommandName Invoke-ReleaseFixtureRequest -ModuleName ReleaseFixture -Times 0 -Exactly + } +} + +Describe 'Find-ReleaseFixtureReport' { + BeforeEach { + $script:case = @{ + caseId = '123-2' + candidate = $script:candidate + scenario = 'staged' + event = 'pull_request' + activity = 'labeled' + head = $script:headSha + } + } + + It 'selects the exact labeled report instead of older or unrelated reports' { + $comments = @( + (ConvertTo-TestReportComment -Fields @{ head = 'f' * 40 }), + (ConvertTo-TestReportComment -Fields @{ activity = 'opened' }), + (ConvertTo-TestReportComment), + (ConvertTo-TestReportComment -Fields @{ caseId = '123-1' }), + (ConvertTo-TestReportComment -Fields @{ candidate = 'f' * 40 }), + (ConvertTo-TestReportComment -Fields @{ scenario = 'one-step' }), + (ConvertTo-TestReportComment -AuthorId 100) + ) + $result = Find-ReleaseFixtureReport -Comments $comments -Case $script:case + $result.run | Should -BeExactly $script:runUrl + ($null -eq $result.tag) | Should -BeTrue + } + + It 'does not accept a report that copies the bot login with a different author ID' { + $comments = @(ConvertTo-TestReportComment -AuthorId 100) + Find-ReleaseFixtureReport -Comments $comments -Case $script:case | Should -BeNullOrEmpty + } + + It 'accepts an opened missing-decision report with no tag and a failed workflow' { + $script:case.scenario = 'missing-decision' + $script:case.activity = 'opened' + $fields = @{ + scenario = 'missing-decision' + activity = 'opened' + conclusion = 'failure' + tag = $null + } + $comments = @( + (ConvertTo-TestReportComment -Fields $fields), + @{ user = $null; body = 'Unrelated comment from a deleted user.' } + ) + $result = Find-ReleaseFixtureReport -Comments $comments -Case $script:case + $result.run | Should -BeExactly $script:runUrl + $result.tag | Should -BeNullOrEmpty + } + + It 'does not accept a report for another push SHA' { + $script:case.event = 'push' + $script:case.source = $script:squashSha + $comments = @(ConvertTo-TestReportComment -Fields @{ event = 'push' }) + Find-ReleaseFixtureReport -Comments $comments -Case $script:case | Should -BeNullOrEmpty + } + + It 'accepts successful push evidence at the exact squash SHA despite workflow failure' { + $script:case.event = 'push' + $script:case.scenario = 'ci-failure' + $script:case.source = $script:squashSha + $comments = @(ConvertTo-TestReportComment -Fields @{ + event = 'push' + activity = $null + scenario = 'ci-failure' + source = $script:squashSha + testedSource = $script:squashSha + conclusion = 'failure' + tag = $null + }) + $result = Find-ReleaseFixtureReport -Comments $comments -Case $script:case + $result.run | Should -BeExactly $script:runUrl + $result.tag | Should -BeNullOrEmpty + } + + It 'rejects on the latest matching report' -ForEach @( + @{ Name = 'a different tested SHA'; Fields = @{ testedSource = ('f' * 40) }; ExpectedError = '*testedSource*' } + @{ Name = 'a string in place of a boolean'; Fields = @{ verified = 'true' }; ExpectedError = '*verified*' } + @{ Name = 'a failed verification'; Fields = @{ verified = $false }; ExpectedError = '*verified*' } + @{ Name = 'an unsuccessful oracle'; Fields = @{ oracle = 'failure' }; ExpectedError = '*oracle*' } + @{ Name = 'a run URL outside the fixture'; Fields = @{ run = 'https://example.invalid/actions/runs/50' }; ExpectedError = '*run URL*' } + ) { + $comments = @((ConvertTo-TestReportComment), (ConvertTo-TestReportComment -Fields $Fields)) + { Find-ReleaseFixtureReport -Comments $comments -Case $script:case } | Should -Throw $ExpectedError + } + + It 'rejects a non-null tag in a report' -ForEach @( + @{ Name = 'pull request'; Scenario = 'staged'; Event = 'pull_request' } + @{ Name = 'preview push'; Scenario = 'preview'; Event = 'push' } + @{ Name = 'skip push'; Scenario = 'skip'; Event = 'push' } + ) { + $script:case.scenario = $Scenario + $script:case.event = $Event + $script:case.source = $script:squashSha + $comments = @(ConvertTo-TestReportComment -Fields @{ + scenario = $Scenario + event = $Event + source = $script:squashSha + testedSource = $script:squashSha + tag = 'v1.2.3' + }) + { Find-ReleaseFixtureReport -Comments $comments -Case $script:case } | Should -Throw '*tag*' + } + + It 'rejects a staged push report without its published stable tag' { + $script:case.event = 'push' + $script:case.source = $script:squashSha + $comments = @(ConvertTo-TestReportComment -Fields @{ + event = 'push' + source = $script:squashSha + testedSource = $script:squashSha + tag = $null + }) + { Find-ReleaseFixtureReport -Comments $comments -Case $script:case } | Should -Throw '*stable tag*' + } + + It 'reports the stable tag from a verified staged push' { + $script:case.event = 'push' + $script:case.source = $script:squashSha + $comments = @(ConvertTo-TestReportComment -Fields @{ + event = 'push' + source = $script:squashSha + testedSource = $script:squashSha + tag = 'v1.2.3' + }) + (Find-ReleaseFixtureReport -Comments $comments -Case $script:case).tag | Should -BeExactly 'v1.2.3' + } +} + +Describe 'Start-ReleaseFixtureCase' { + BeforeEach { + $script:active = @() + $script:releases = @() + $script:prBody = $null + $script:caseWrite = $null + $script:contractAtMain = $false + + Mock Invoke-ReleaseFixtureRequest -ModuleName ReleaseFixture { + $effectiveMethod = $Method ?? 'GET' + switch ("$effectiveMethod $Path") { + "GET $script:fixture" { $script:fixtureRepo + @{ default_branch = 'main' } } + "GET $script:fixture/pulls?state=open" { $script:active } + "GET $script:fixture/git/ref/heads/main" { @{ object = @{ type = 'commit'; sha = $script:mainSha } } } + "GET $script:fixture/contents/tests/FixtureContract.json?ref=$script:mainSha" { + $script:contractAtMain = $true + $json = ConvertTo-Json -InputObject $script:contract -Depth 4 -Compress + @{ + type = 'file' + encoding = 'base64' + content = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($json)) + } + } + "GET $script:fixture/releases" { $script:releases } + "GET $script:fixture/git/ref/tags/v1.10.0" { @{ object = @{ type = 'tag'; sha = ('f' * 40) } } } + "GET $script:fixture/git/tags/$('f' * 40)" { @{ object = @{ type = 'commit'; sha = $script:squashSha } } } + "GET $script:fixture/git/commits/$script:squashSha" { @{ sha = $script:squashSha } } + "GET $script:fixture/compare/$script:squashSha...$script:mainSha" { @{ status = 'ahead' } } + "GET $script:fixture/labels/release%3Apatch" { @{ name = 'release:patch' } } + "POST $script:fixture/git/refs" { + if (-not $script:contractAtMain -or $Body.ref -cne 'refs/heads/release-fixture/123-2' -or + $Body.sha -cne $script:mainSha) { + throw 'Expected a new branch at the main SHA used to read the contract.' + } + @{ ref = $Body.ref; object = @{ sha = $Body.sha } } + } + "PUT $script:fixture/contents/tests/cases/123-2.json" { + $script:caseWrite = $Body + @{ + commit = @{ sha = $script:headSha; parents = @(@{ sha = $script:mainSha }) } + } + } + "POST $script:fixture/pulls" { + $script:prBody = $Body.body + @{ + number = 40 + state = 'open' + user = $script:shelly + base = @{ ref = 'main'; repo = $script:fixtureRepo; sha = $script:mainSha } + head = @{ ref = $Body.head; repo = $script:fixtureRepo; sha = $script:headSha } + } + } + default { throw "Unexpected request: $Method $Path" } + } + } + } + + It 'uses initial with no published stable release and adds only the candidate case' { + $result = Start-ReleaseFixtureCase -Scenario 'staged' -Candidate $script:candidate -CaseId '123-2' + $script:prBody -split "`n" | Should -Contain "" + $script:caseWrite.branch | Should -BeExactly 'release-fixture/123-2' + $script:caseWrite.ContainsKey('sha') | Should -BeFalse + $caseData = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($script:caseWrite.content)) | + ConvertFrom-Json -AsHashtable + $caseData.Count | Should -Be 2 + $caseData.scenario | Should -BeExactly 'staged' + $caseData.candidate | Should -BeExactly $script:candidate + $result.head | Should -BeExactly $script:headSha + $result.activity | Should -BeExactly 'labeled' + } + + It 'uses the peeled commit of the greatest published stable tag' { + $script:releases = @( + @{ tag_name = 'v1.10.0'; draft = $false; prerelease = $false }, + @{ tag_name = 'v1.9.9'; draft = $false; prerelease = $false }, + @{ tag_name = 'v3.0.0'; draft = $true; prerelease = $false }, + @{ tag_name = 'v2.0.0'; draft = $false; prerelease = $true }, + @{ tag_name = 'v4'; draft = $false; prerelease = $false } + ) + $null = Start-ReleaseFixtureCase -Scenario 'staged' -Candidate $script:candidate -CaseId '123-2' + $script:prBody -split "`n" | Should -Contain "" + } + + It 'refuses until main itself is the published stable source' -ForEach @( + @{ Name = 'configured-default' } + @{ Name = 'missing-decision' } + ) { + $script:releases = @(@{ tag_name = 'v1.10.0'; draft = $false; prerelease = $false }) + { Start-ReleaseFixtureCase -Scenario $Name -Candidate $script:candidate -CaseId '123-2' } | + Should -Throw '*published stable source*' + Should -Invoke -CommandName Invoke-ReleaseFixtureRequest -ModuleName ReleaseFixture -Times 0 -Exactly -ParameterFilter { + $Method -in 'POST', 'PUT' + } + } + + It 'refuses to write when a fixture pull request is already open' { + $script:active = @(@{ + number = 39 + user = $script:shelly + base = @{ ref = 'main'; repo = $script:fixtureRepo } + head = @{ ref = 'release-fixture/122-1'; repo = $script:fixtureRepo } + }) + { Start-ReleaseFixtureCase -Scenario 'staged' -Candidate $script:candidate -CaseId '123-2' } | + Should -Throw '*already open*' + Should -Invoke -CommandName Invoke-ReleaseFixtureRequest -ModuleName ReleaseFixture -Times 0 -Exactly -ParameterFilter { + $Method -in 'POST', 'PUT' + } + } + + It 'ignores with the fixture branch prefix' -ForEach @( + @{ Name = 'a fork pull request'; Base = 'main'; Fork = $true } + @{ Name = 'a pull request to another branch'; Base = 'maintenance'; Fork = $false } + ) { + $headRepo = $script:fixtureRepo + if ($Fork) { + $headRepo = @{ id = 100; full_name = 'example/Release-GHRepository-Test' } + } + $script:active = @(@{ + number = 39 + user = $script:shelly + base = @{ ref = $Base; repo = $script:fixtureRepo } + head = @{ ref = 'release-fixture/122-1'; repo = $headRepo } + }) + + $result = Start-ReleaseFixtureCase -Scenario 'staged' -Candidate $script:candidate -CaseId '123-2' + + $result.number | Should -Be 40 + } +} + +Describe 'Get-MergedReleaseFixtureCase' { + BeforeEach { + $script:pull = @{ + state = 'closed' + merged = $true + number = 40 + commits = 1 + merge_commit_sha = $script:squashSha + user = $script:shelly + base = @{ ref = 'main'; repo = $script:fixtureRepo } + head = @{ ref = 'release-fixture/123-2'; repo = $script:fixtureRepo; sha = $script:headSha } + } + $script:squash = @{ + sha = $script:squashSha + parents = @(@{ sha = $script:mainSha }) + files = @(@{ filename = 'tests/cases/123-2.json'; status = 'added' }) + } + $script:caseByRef = @{ + $script:headSha = @{ scenario = 'staged'; candidate = $script:candidate } + $script:squashSha = @{ scenario = 'staged'; candidate = $script:candidate } + } + + Mock Invoke-ReleaseFixtureRequest -ModuleName ReleaseFixture { + if ($Method -and $Method -ne 'GET') { + throw 'Expected a read-only request.' + } + switch -Wildcard ($Path) { + "$script:fixture/pulls/40" { $script:pull } + "$script:fixture/commits/$script:squashSha" { $script:squash } + "$script:fixture/contents/tests/cases/123-2.json?ref=*" { + $ref = ($Path -split 'ref=')[1] + $json = ConvertTo-Json -InputObject $script:caseByRef[$ref] -Compress + @{ + type = 'file' + encoding = 'base64' + content = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($json)) + } + } + default { throw "Unexpected request: $Path" } + } + } + } + + It 'binds the case and head to the exact merged source' { + $result = Get-MergedReleaseFixtureCase -PullRequest '40' + $result.source | Should -BeExactly $script:squashSha + $result.head | Should -BeExactly $script:headSha + $result.candidate | Should -BeExactly $script:candidate + } + + It 'refuses a pull request that was only closed' { + $script:pull.merged = $false + { Get-MergedReleaseFixtureCase -PullRequest '40' } | Should -Throw '*merged*' + } + + It 'refuses a two-parent merge commit' { + $script:squash.parents += @{ sha = $script:headSha } + { Get-MergedReleaseFixtureCase -PullRequest '40' } | Should -Throw '*squash*' + } + + It 'refuses a different case payload at the merge SHA' { + $script:caseByRef[$script:squashSha].candidate = 'f' * 40 + { Get-MergedReleaseFixtureCase -PullRequest '40' } | Should -Throw '*case payload*' + } +}