diff --git a/.github/scripts/Invoke-ReleaseFixture.ps1 b/.github/scripts/Invoke-ReleaseFixture.ps1 index 885b301..e7f9fb2 100644 --- a/.github/scripts/Invoke-ReleaseFixture.ps1 +++ b/.github/scripts/Invoke-ReleaseFixture.ps1 @@ -12,16 +12,22 @@ #> [CmdletBinding(SupportsShouldProcess)] param( - # Resolve a producer SHA, start a fixture case, or verify a merged fixture case. + # Resolve a producer SHA, start a fixture case, verify a merged fixture case, or run a baseline-first pair step. [Parameter(Mandatory)] - [ValidateSet('Resolve', 'Start', 'Verify')] + [ValidateSet('Resolve', 'Start', 'Verify', 'StartLegacy', 'StartPairCandidate', 'ComparePair')] [string] $Mode, # Producer pull request number in Resolve mode or fixture pull request number in Verify mode. + # The candidate fixture pull request number in ComparePair mode. [Parameter()] [AllowEmptyString()] [string] $PullRequest, + # Merged legacy fixture pull request number in StartPairCandidate and ComparePair modes. + [Parameter()] + [AllowEmptyString()] + [string] $LegacyPullRequest, + # Scenario name in Start mode. [Parameter()] [string] $Scenario, @@ -65,6 +71,71 @@ switch ($Mode) { Add-ReleaseFixtureLabel -Case $case -Confirm:$false $runType = 'Open pull request' } + 'StartLegacy' { + $caseId = "$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" + if (-not $PSCmdlet.ShouldProcess("Legacy fixture case $caseId", 'Start')) { + return + } + $case = Start-ReleaseFixtureLegacyCase -CaseId $caseId -Confirm:$false + Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Value @( + "Legacy fixture pull request: [#$($case.number)]($($case.url))" + '' + "Case: $($case.caseId) | Action pin: $($case.candidate) | Head: $($case.head)" + '' + ) + Write-Information -MessageData "Opened $($case.url)" -InformationAction Continue + Add-ReleaseFixtureLabel -Case $case -Confirm:$false + Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Value @( + 'Approve and squash merge this pull request through the normal process. Then dispatch the candidate step.' + '' + ) + return + } + 'StartPairCandidate' { + if (-not $PSCmdlet.ShouldProcess("Paired candidate case for legacy pull request #$LegacyPullRequest", 'Start')) { + return + } + $caseId = "$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" + $case = Start-ReleaseFixturePairCandidate -LegacyPullRequest $LegacyPullRequest -Candidate $Candidate -CaseId $caseId -Confirm:$false + Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Value @( + "Candidate fixture pull request: [#$($case.number)]($($case.url))" + '' + "Case: $($case.caseId) (after legacy pull request #$LegacyPullRequest) | Action pin: $($case.candidate) | Head: $($case.head)" + '' + ) + Write-Information -MessageData "Opened $($case.url)" -InformationAction Continue + Add-ReleaseFixtureLabel -Case $case -Confirm:$false + $runType = 'Open pull request' + } + 'ComparePair' { + $pair = Get-ReleaseFixturePairEvidence -LegacyPullRequest $LegacyPullRequest -CandidatePullRequest $PullRequest + $lines = @( + 'Baseline-first pair comparison' + '' + '| Lane | Pull request | Action pin | Squash | Parent | Tag | Run |' + '| --- | --- | --- | --- | --- | --- | --- |' + ) + foreach ($lane in 'legacy', 'candidate') { + $item = $pair[$lane] + $caseLink = "[#$($item.case.number)]($($item.case.url))" + $runLink = "[$($item.report.run)]($($item.report.run))" + $cells = @($lane, $caseLink, $item.case.candidate, $item.case.source, $item.case.parent, $item.release.tag, $runLink) + $lines += "| $($cells -join ' | ') |" + } + $lines += '' + $lines += '| Check | Value | Reference | Result |' + $lines += '| --- | --- | --- | --- |' + foreach ($row in $pair.comparison.rows) { + $result = $row.match ? 'match' : 'MISMATCH' + $lines += "| $($row.check) | $($row.value) | $($row.reference) | $result |" + } + Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Value ($lines + '') + if (-not $pair.comparison.match) { + throw 'The legacy and candidate evidence do not match. See the job summary for every compared value.' + } + Write-Information -MessageData 'The legacy and candidate evidence match.' -InformationAction Continue + return + } 'Verify' { $case = Get-MergedReleaseFixtureCase -PullRequest $PullRequest Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Value @( diff --git a/.github/scripts/ReleaseFixture.psm1 b/.github/scripts/ReleaseFixture.psm1 index 3403529..da8e12e 100644 --- a/.github/scripts/ReleaseFixture.psm1 +++ b/.github/scripts/ReleaseFixture.psm1 @@ -9,6 +9,8 @@ $producerApi = "/repos/$producerRepo" $fixtureApi = "/repos/$fixtureRepo" $fixtureId = 1477027955 $fixtureUrl = "https://github.com/$fixtureRepo" +$legacyBaseline = '750abed0ecab02394554b610dc3aa191e75e3248' +$legacyWorkflowPath = '.github/workflows/Legacy-Release-Test.yml' $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 = @{ @@ -21,6 +23,29 @@ $scenarioLabels = @{ 'ci-failure' = 'release:patch' } +function Get-ReleaseFixtureLane { + <# + .SYNOPSIS + Describe a case lane. Both lanes use the one fixture repository. The legacy lane runs the published action in Legacy-Release-Test.yml. + #> + [OutputType([hashtable])] + [CmdletBinding()] + param( + [Parameter()] + [ValidateSet('Candidate', 'Legacy')] + [string] $Name = 'Candidate' + ) + + @{ + Name = $Name + Repository = $fixtureRepo + Id = $fixtureId + Api = $fixtureApi + Url = $fixtureUrl + TokenVariable = 'GH_TOKEN' + } +} + function Invoke-ReleaseFixtureRequest { <# .SYNOPSIS @@ -31,6 +56,9 @@ function Invoke-ReleaseFixtureRequest { [Parameter(Mandatory)] [string] $Path, + [Parameter()] + [string] $TokenVariable = 'GH_TOKEN', + [Parameter()] [ValidateSet('GET', 'POST', 'PUT')] [string] $Method = 'GET', @@ -42,9 +70,9 @@ function Invoke-ReleaseFixtureRequest { [switch] $Paged ) - $value = [Environment]::GetEnvironmentVariable('GH_TOKEN') + $value = [Environment]::GetEnvironmentVariable($TokenVariable) if ([string]::IsNullOrWhiteSpace($value)) { - throw 'GH_TOKEN must be set for this step.' + throw "$TokenVariable must be set for this step." } $request = @{ @@ -98,10 +126,13 @@ function Get-ReleaseFixtureMain { [CmdletBinding()] param( [Parameter(Mandatory)] - [string] $RepositoryApi + [string] $RepositoryApi, + + [Parameter()] + [string] $TokenVariable = 'GH_TOKEN' ) - $ref = Invoke-ReleaseFixtureRequest -Path "$RepositoryApi/git/ref/heads/main" + $ref = Invoke-ReleaseFixtureRequest -Path "$RepositoryApi/git/ref/heads/main" -TokenVariable $TokenVariable if ($ref['object']['type'] -cne 'commit' -or $ref['object']['sha'] -cnotmatch $shaPattern) { throw "No valid main commit was returned for $RepositoryApi." } @@ -201,10 +232,15 @@ function Get-ReleaseFixtureJson { [string] $Path, [Parameter(Mandatory)] - [string] $Commit + [string] $Commit, + + [Parameter()] + [ValidateSet('Candidate', 'Legacy')] + [string] $Lane = 'Candidate' ) - $file = Invoke-ReleaseFixtureRequest -Path "$fixtureApi/contents/${Path}?ref=$Commit" + $laneInfo = Get-ReleaseFixtureLane -Name $Lane + $file = Invoke-ReleaseFixtureRequest -Path "$($laneInfo.Api)/contents/${Path}?ref=$Commit" -TokenVariable $laneInfo.TokenVariable if ($file.type -cne 'file' -or $file.encoding -cne 'base64') { throw "$Path at $Commit must be a base64-encoded file." } @@ -216,6 +252,41 @@ function Get-ReleaseFixtureJson { $document } +function Resolve-ReleaseFixtureTagCommit { + <# + .SYNOPSIS + Peel a fixture tag to the commit it points to. + #> + [OutputType([string])] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [string] $Tag, + + [Parameter()] + [ValidateSet('Candidate', 'Legacy')] + [string] $Lane = 'Candidate' + ) + + $laneInfo = Get-ReleaseFixtureLane -Name $Lane + $token = $laneInfo.TokenVariable + $api = $laneInfo.Api + $ref = Invoke-ReleaseFixtureRequest -Path "$api/git/ref/tags/$Tag" -TokenVariable $token + $target = $ref.object + for ($depth = 0; $depth -lt 16 -and $target.type -ceq 'tag' -and $target.sha -cmatch $shaPattern; $depth++) { + $annotated = Invoke-ReleaseFixtureRequest -Path "$api/git/tags/$($target.sha)" -TokenVariable $token + $target = $annotated.object + } + if ($target.type -cne 'commit' -or $target.sha -cnotmatch $shaPattern) { + throw "Stable fixture tag $Tag did not resolve to a commit." + } + $commit = Invoke-ReleaseFixtureRequest -Path "$api/git/commits/$($target.sha)" -TokenVariable $token + if ($commit.sha -cne $target.sha) { + throw "GitHub did not return the commit at stable fixture tag $Tag." + } + $commit.sha +} + function Get-ReleaseFixtureBaseline { <# .SYNOPSIS @@ -223,10 +294,15 @@ function Get-ReleaseFixtureBaseline { #> [OutputType([string])] [CmdletBinding()] - param() + param( + [Parameter()] + [ValidateSet('Candidate', 'Legacy')] + [string] $Lane = 'Candidate' + ) + $laneInfo = Get-ReleaseFixtureLane -Name $Lane $stablePattern = "\A$versionCore\z" - $versions = foreach ($release in (Invoke-ReleaseFixtureRequest -Path "$fixtureApi/releases" -Paged)) { + $versions = foreach ($release in (Invoke-ReleaseFixtureRequest -Path "$($laneInfo.Api)/releases" -Paged -TokenVariable $laneInfo.TokenVariable)) { if ($release.draft -ceq $false -and $release.prerelease -ceq $false -and $release.tag_name -cmatch $stablePattern) { [pscustomobject] @{ Tag = $release.tag_name @@ -241,21 +317,7 @@ function Get-ReleaseFixtureBaseline { '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 + Resolve-ReleaseFixtureTagCommit -Tag $latest.Tag -Lane $Lane } function Test-ReleaseFixturePullRequest { @@ -267,18 +329,109 @@ function Test-ReleaseFixturePullRequest { [CmdletBinding()] param( [Parameter(Mandatory)] - [System.Collections.IDictionary] $PullRequest + [System.Collections.IDictionary] $PullRequest, + + [Parameter()] + [ValidateSet('Candidate', 'Legacy')] + [string] $Lane = 'Candidate' ) + $laneInfo = Get-ReleaseFixtureLane -Name $Lane $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 + $base.repo.id -eq $laneInfo.Id -and $base.repo.full_name -ceq $laneInfo.Repository -and + $head.repo.id -eq $laneInfo.Id -and $head.repo.full_name -ceq $laneInfo.Repository -and $author.id -eq 314722336 -and $author.login -ceq 'psmodule-s-shelly[bot]' -and $author.type -ceq 'Bot' } +function Assert-ReleaseFixtureRepository { + <# + .SYNOPSIS + Check the exact name, ID, and default branch of a fixture repository. + #> + [CmdletBinding()] + param( + [Parameter()] + [ValidateSet('Candidate', 'Legacy')] + [string] $Lane = 'Candidate' + ) + + $laneInfo = Get-ReleaseFixtureLane -Name $Lane + $repository = Invoke-ReleaseFixtureRequest -Path $laneInfo.Api -TokenVariable $laneInfo.TokenVariable + if ($repository.id -ne $laneInfo.Id -or $repository.full_name -cne $laneInfo.Repository -or $repository.default_branch -cne 'main') { + throw "The $($laneInfo.Name) fixture repository identity or default branch does not match the driver." + } +} + +function Assert-ReleaseFixtureEmptyInventory { + <# + .SYNOPSIS + Check that a fixture repository has no releases and no tags. + #> + [CmdletBinding()] + param( + [Parameter()] + [ValidateSet('Candidate', 'Legacy')] + [string] $Lane = 'Candidate' + ) + + $laneInfo = Get-ReleaseFixtureLane -Name $Lane + $releases = @(Invoke-ReleaseFixtureRequest -Path "$($laneInfo.Api)/releases" -Paged -TokenVariable $laneInfo.TokenVariable) + $tags = @(Invoke-ReleaseFixtureRequest -Path "$($laneInfo.Api)/git/matching-refs/tags" -Paged -TokenVariable $laneInfo.TokenVariable) + if ($releases.Count -ne 0 -or $tags.Count -ne 0) { + throw "The $($laneInfo.Name) fixture repository must have no releases and no tags." + } +} + +function Assert-ReleaseFixtureStableRelease { + <# + .SYNOPSIS + Check that the inventory is exactly the reported tag plus any other expected tags, and that the reported tag points to the exact squash. + #> + [OutputType([hashtable])] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [string] $Tag, + + [Parameter(Mandatory)] + [string] $Source, + + # Other tags that must exist, such as the earlier release. + [Parameter()] + [string[]] $AlsoTag = @(), + + [Parameter()] + [ValidateSet('Candidate', 'Legacy')] + [string] $Lane = 'Candidate', + + # Return a tag target that differs from the squash so the comparison can show it. + [Parameter()] + [switch] $AllowTargetMismatch + ) + + $laneInfo = Get-ReleaseFixtureLane -Name $Lane + if ($Tag -cnotmatch "\A$versionCore\z" -or $Source -cnotmatch $shaPattern) { + throw "The $($laneInfo.Name) release evidence needs a stable tag and a squash SHA." + } + $releases = @(Invoke-ReleaseFixtureRequest -Path "$($laneInfo.Api)/releases" -Paged -TokenVariable $laneInfo.TokenVariable) + $tags = @(Invoke-ReleaseFixtureRequest -Path "$($laneInfo.Api)/git/matching-refs/tags" -Paged -TokenVariable $laneInfo.TokenVariable) + $expected = @($AlsoTag + $Tag | Sort-Object -Unique) + $drafts = @($releases | Where-Object { $_.draft -cne $false -or $_.prerelease -cne $false }) + if ($drafts.Count -ne 0 -or $releases.Count -ne $expected.Count -or $tags.Count -ne $expected.Count -or + (@($releases.tag_name | Sort-Object) -join ' ') -cne ($expected -join ' ') -or + (@($tags.ref | Sort-Object) -join ' ') -cne (($expected | ForEach-Object { "refs/tags/$_" }) -join ' ')) { + throw "The fixture repository must have only the stable release and tag inventory: $($expected -join ', ')." + } + $target = Resolve-ReleaseFixtureTagCommit -Tag $Tag -Lane $Lane + if ($target -cne $Source -and -not $AllowTargetMismatch) { + throw "The $($laneInfo.Name) tag $Tag points to $target, not the squash commit $Source." + } + @{ tag = $Tag; target = $target } +} + function Start-ReleaseFixtureCase { <# .SYNOPSIS @@ -298,17 +451,39 @@ function Start-ReleaseFixtureCase { [Parameter(Mandatory)] [ValidatePattern('\A[1-9][0-9]*-[1-9][0-9]*\z')] - [string] $CaseId + [string] $CaseId, + + # The lane that receives the case. + [Parameter()] + [ValidateSet('Candidate', 'Legacy')] + [string] $Lane = 'Candidate', + + # Fail unless fixture main is exactly this commit. + [Parameter()] + [string] $ExpectedMain = '', + + # Fail unless the repository has no releases and no tags. + [Parameter()] + [switch] $RequireEmptyInventory, + + # Fail unless these files exist at fixture main. + [Parameter()] + [string[]] $RequiredPath = @() ) 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.' + if ($ExpectedMain -cne '' -and $ExpectedMain -cnotmatch $shaPattern) { + throw 'Supply the expected fixture main as a lowercase SHA.' } - foreach ($open in (Invoke-ReleaseFixtureRequest -Path "$fixtureApi/pulls?state=open" -Paged)) { + $laneInfo = Get-ReleaseFixtureLane -Name $Lane + $token = $laneInfo.TokenVariable + $fixtureApi = $laneInfo.Api + $fixtureRepo = $laneInfo.Repository + $fixtureUrl = $laneInfo.Url + Assert-ReleaseFixtureRepository -Lane $Lane + foreach ($open in (Invoke-ReleaseFixtureRequest -Path "$fixtureApi/pulls?state=open" -Paged -TokenVariable $token)) { if ($open.head.ref -clike 'release-fixture/*') { if (-not (Test-ReleaseFixturePullRequest -PullRequest $open)) { continue @@ -317,8 +492,17 @@ function Start-ReleaseFixtureCase { } } - $main = Get-ReleaseFixtureMain -RepositoryApi $fixtureApi - $contract = Get-ReleaseFixtureJson -Path 'tests/FixtureContract.json' -Commit $main + $main = Get-ReleaseFixtureMain -RepositoryApi $fixtureApi -TokenVariable $token + if ($ExpectedMain -cne '' -and $main -cne $ExpectedMain) { + throw "Fixture main at $main must be the expected commit $ExpectedMain." + } + foreach ($requiredFile in $RequiredPath) { + $null = Invoke-ReleaseFixtureRequest -Path "$fixtureApi/contents/${requiredFile}?ref=$main" -TokenVariable $token + } + if ($RequireEmptyInventory) { + Assert-ReleaseFixtureEmptyInventory -Lane $Lane + } + $contract = Get-ReleaseFixtureJson -Path 'tests/FixtureContract.json' -Commit $main -Lane $Lane 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." @@ -331,12 +515,12 @@ function Start-ReleaseFixtureCase { } $label = $contract.scenarios[$Scenario] - $baseline = Get-ReleaseFixtureBaseline + $baseline = Get-ReleaseFixtureBaseline -Lane $Lane 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" + $comparison = Invoke-ReleaseFixtureRequest -Path "$fixtureApi/compare/$baseline...$main" -TokenVariable $token if ($comparison.status -cne 'ahead') { throw "Fixture main at $main does not descend from the published stable source at $baseline." } @@ -344,13 +528,13 @@ function Start-ReleaseFixtureCase { $activity = 'opened' if ($label -cne '') { $encodedLabel = [uri]::EscapeDataString($label) - $fixtureLabel = Invoke-ReleaseFixtureRequest -Path "$fixtureApi/labels/$encodedLabel" + $fixtureLabel = Invoke-ReleaseFixtureRequest -Path "$fixtureApi/labels/$encodedLabel" -TokenVariable $token if ($fixtureLabel.name -cne $label) { throw "Fixture label '$label' is not available." } $activity = 'labeled' } - if ((Get-ReleaseFixtureMain -RepositoryApi $fixtureApi) -cne $main) { + if ((Get-ReleaseFixtureMain -RepositoryApi $fixtureApi -TokenVariable $token) -cne $main) { throw 'Fixture main changed during setup. Start the case again.' } @@ -358,12 +542,12 @@ function Start-ReleaseFixtureCase { 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 @{ + $null = Invoke-ReleaseFixtureRequest -Method POST -Path "$fixtureApi/git/refs" -TokenVariable $token -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 @{ + $created = Invoke-ReleaseFixtureRequest -Method PUT -Path "$fixtureApi/contents/tests/cases/$CaseId.json" -TokenVariable $token -Body @{ branch = $branch message = "Add release fixture case $CaseId" content = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("$caseJson`n")) @@ -372,7 +556,7 @@ function Start-ReleaseFixtureCase { 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) { + if ((Get-ReleaseFixtureMain -RepositoryApi $fixtureApi -TokenVariable $token) -cne $main) { throw "Fixture main changed before opening the pull request. The unmerged case branch is $branch." } $notes = @( @@ -381,7 +565,7 @@ function Start-ReleaseFixtureCase { '' "" ) -join "`n" - $pull = Invoke-ReleaseFixtureRequest -Method POST -Path "$fixtureApi/pulls" -Body @{ + $pull = Invoke-ReleaseFixtureRequest -Method POST -Path "$fixtureApi/pulls" -TokenVariable $token -Body @{ base = 'main' head = $branch title = "Test release fixture: $Scenario ($CaseId)" @@ -391,11 +575,12 @@ function Start-ReleaseFixtureCase { 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 + if (-not (Test-ReleaseFixturePullRequest -PullRequest $pull -Lane $Lane) -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" } @{ + lane = $Lane number = $pull.number url = $url caseId = $CaseId @@ -422,8 +607,10 @@ function Add-ReleaseFixtureLabel { if ($Case.label -ceq '' -or -not $PSCmdlet.ShouldProcess($Case.url, "Add label '$($Case.label)'")) { return } + $laneInfo = Get-ReleaseFixtureLane -Name ($Case['lane'] ?? 'Candidate') $body = @{ labels = @($Case.label) } - $labels = @(Invoke-ReleaseFixtureRequest -Method POST -Path "$fixtureApi/issues/$($Case.number)/labels" -Body $body) + $labelPath = "$($laneInfo.Api)/issues/$($Case.number)/labels" + $labels = @(Invoke-ReleaseFixtureRequest -Method POST -Path $labelPath -TokenVariable $laneInfo.TokenVariable -Body $body) if ($labels.Count -eq 0 -or $Case.label -cnotin $labels.name) { throw "GitHub did not attach label '$($Case.label)' to $($Case.url)." } @@ -439,12 +626,20 @@ function Get-MergedReleaseFixtureCase { param( [Parameter(Mandatory)] [ValidatePattern('\A[1-9][0-9]*\z')] - [string] $PullRequest + [string] $PullRequest, + + [Parameter()] + [ValidateSet('Candidate', 'Legacy')] + [string] $Lane = 'Candidate' ) - $pull = Invoke-ReleaseFixtureRequest -Path "$fixtureApi/pulls/$PullRequest" + $laneInfo = Get-ReleaseFixtureLane -Name $Lane + $token = $laneInfo.TokenVariable + $fixtureApi = $laneInfo.Api + $fixtureUrl = $laneInfo.Url + $pull = Invoke-ReleaseFixtureRequest -Path "$fixtureApi/pulls/$PullRequest" -TokenVariable $token $url = "$fixtureUrl/pull/$PullRequest" - if ($pull.number -ne $PullRequest -or -not (Test-ReleaseFixturePullRequest -PullRequest $pull)) { + if ($pull.number -ne $PullRequest -or -not (Test-ReleaseFixturePullRequest -PullRequest $pull -Lane $Lane)) { 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) { @@ -459,14 +654,14 @@ function Get-MergedReleaseFixtureCase { $head = $pull.head.sha $source = $pull.merge_commit_sha $path = "tests/cases/$caseId.json" - $commit = Invoke-ReleaseFixtureRequest -Path "$fixtureApi/commits/$source" + $commit = Invoke-ReleaseFixtureRequest -Path "$fixtureApi/commits/$source" -TokenVariable $token 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 + $original = Get-ReleaseFixtureJson -Path $path -Commit $head -Lane $Lane + $merged = Get-ReleaseFixtureJson -Path $path -Commit $source -Lane $Lane 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 @@ -477,7 +672,8 @@ function Get-MergedReleaseFixtureCase { if ($original.scenario -ceq 'missing-decision') { throw "The missing-decision case must be closed without merging: $url" } - @{ + $result = @{ + lane = $Lane number = $pull.number url = $url caseId = $caseId @@ -486,7 +682,14 @@ function Get-MergedReleaseFixtureCase { event = 'push' head = $head source = $source + parent = $commit.parents[0].sha + } + if ($Lane -ceq 'Legacy') { + # The legacy workflow reports the closed pull request instead of a push. + $result.event = 'pull_request' + $result.activity = 'closed' } + $result } function Find-ReleaseFixtureReport { @@ -505,8 +708,12 @@ function Find-ReleaseFixtureReport { [System.Collections.IDictionary] $Case ) + $laneInfo = Get-ReleaseFixtureLane -Name ($Case['lane'] ?? 'Candidate') $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" + $runPattern = "\A$([regex]::Escape($laneInfo.Url))/actions/runs/[1-9][0-9]*\z" + # A push report and the legacy closed-pull-request report bind to the exact squash source and publish the stable tag. + $closedPull = $Case.event -ceq 'pull_request' -and $Case['activity'] -ceq 'closed' + $bindsSource = $Case.event -ceq 'push' -or $closedPull # The comments endpoint returns comments in ascending ID order. for ($index = $Comments.Count - 1; $index -ge 0; $index--) { $author = $Comments[$index]['user'] @@ -534,7 +741,7 @@ function Find-ReleaseFixtureReport { $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))) { + ($bindsSource -and ($source -isnot [string] -or $source -cne $Case.source))) { continue } @@ -551,10 +758,10 @@ function Find-ReleaseFixtureReport { 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' + $stableWrite = $bindsSource -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." + throw "Fixture $($Case.event) 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." @@ -576,10 +783,12 @@ function Wait-ReleaseFixtureReport { [System.Collections.IDictionary] $Case ) + $laneInfo = Get-ReleaseFixtureLane -Name ($Case['lane'] ?? 'Candidate') $elapsed = [Diagnostics.Stopwatch]::StartNew() $limit = [TimeSpan]::FromMinutes(10) while ($elapsed.Elapsed -lt $limit) { - $comments = @(Invoke-ReleaseFixtureRequest -Path "$fixtureApi/issues/$($Case.number)/comments" -Paged) + $commentPath = "$($laneInfo.Api)/issues/$($Case.number)/comments" + $comments = @(Invoke-ReleaseFixtureRequest -Path $commentPath -Paged -TokenVariable $laneInfo.TokenVariable) if ($elapsed.Elapsed -ge $limit) { break } @@ -596,7 +805,232 @@ function Wait-ReleaseFixtureReport { throw "No matching $($Case.event) report for fixture case $($Case.caseId) within ten minutes. See $($Case.url)." } +function Find-SingleReleaseFixtureReport { + <# + .SYNOPSIS + Read the comments once and require the exact validated report for a case. + #> + [OutputType([System.Collections.IDictionary])] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Case + ) + + $laneInfo = Get-ReleaseFixtureLane -Name ($Case['lane'] ?? 'Candidate') + $comments = @(Invoke-ReleaseFixtureRequest -Path "$($laneInfo.Api)/issues/$($Case.number)/comments" -Paged -TokenVariable $laneInfo.TokenVariable) + $report = Find-ReleaseFixtureReport -Comments $comments -Case $Case + if ($null -eq $report) { + throw "No matching $($Case.event) report exists yet for $($laneInfo.Name) fixture case $($Case.caseId). See $($Case.url)." + } + $report +} + +function Start-ReleaseFixtureLegacyCase { + <# + .SYNOPSIS + Open the baseline-first legacy pull request when the fixture has no releases and no tags and has the legacy workflow. + + .EXAMPLE + Start-ReleaseFixtureLegacyCase -CaseId '123-1' + #> + [OutputType([hashtable])] + [CmdletBinding(SupportsShouldProcess)] + param( + [Parameter(Mandatory)] + [ValidatePattern('\A[1-9][0-9]*-[1-9][0-9]*\z')] + [string] $CaseId + ) + + Assert-ReleaseFixtureRepository -Lane 'Legacy' + $main = Get-ReleaseFixtureMain -RepositoryApi $fixtureApi + Start-ReleaseFixtureCase -Scenario 'one-step' -Candidate $legacyBaseline -CaseId $CaseId -Lane 'Legacy' ` + -ExpectedMain $main -RequireEmptyInventory -RequiredPath $legacyWorkflowPath -Confirm:$false +} + +function Get-ReleaseFixtureLegacyEvidence { + <# + .SYNOPSIS + Validate the merged legacy pull request, its bot report, and its only release and tag. + #> + [OutputType([hashtable])] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [ValidatePattern('\A[1-9][0-9]*\z')] + [string] $PullRequest, + + # Later release tags that must also exist, such as the candidate release. + [Parameter()] + [string[]] $AlsoTag = @(), + + [Parameter()] + [switch] $AllowTargetMismatch + ) + + $case = Get-MergedReleaseFixtureCase -PullRequest $PullRequest -Lane 'Legacy' + if ($case.scenario -cne 'one-step' -or $case.candidate -cne $legacyBaseline) { + throw "The legacy case must use the one-step scenario with the pinned baseline $legacyBaseline. See $($case.url)." + } + $report = Find-SingleReleaseFixtureReport -Case $case + if ($report.tag -cne 'v0.0.1') { + throw "The legacy release on an empty fixture must be v0.0.1, not $($report.tag). See $($report.run)." + } + + $headCommit = Invoke-ReleaseFixtureRequest -Path "$fixtureApi/git/commits/$($case.head)" + $parents = $headCommit['parents'] + if ($headCommit['sha'] -cne $case.head -or $parents -isnot [array] -or $parents.Count -ne 1 -or + $parents[0]['sha'] -cnotmatch $shaPattern) { + throw "The original legacy case head $($case.head) must have exactly one valid parent commit. See $($case.url)." + } + $originalBase = $parents[0]['sha'] + if ($case.parent -cne $originalBase) { + throw "The legacy squash parent $($case.parent) does not match the original case base $originalBase. See $($case.url)." + } + + $release = Assert-ReleaseFixtureStableRelease -Tag $report.tag -Source $case.source -Lane 'Legacy' -AlsoTag $AlsoTag ` + -AllowTargetMismatch:$AllowTargetMismatch + @{ case = $case; report = $report; release = $release } +} + +function Start-ReleaseFixturePairCandidate { + <# + .SYNOPSIS + Open the candidate pull request on the verified legacy squash. The candidate case ID must differ from the legacy case ID. + + .EXAMPLE + Start-ReleaseFixturePairCandidate -LegacyPullRequest '7' -Candidate ('a' * 40) -CaseId '124-1' + #> + [OutputType([hashtable])] + [CmdletBinding(SupportsShouldProcess)] + param( + [Parameter(Mandatory)] + [ValidatePattern('\A[1-9][0-9]*\z')] + [string] $LegacyPullRequest, + + [Parameter(Mandatory)] + [string] $Candidate, + + [Parameter(Mandatory)] + [ValidatePattern('\A[1-9][0-9]*-[1-9][0-9]*\z')] + [string] $CaseId + ) + + if ($Candidate -ceq $legacyBaseline) { + throw 'The candidate SHA must differ from the published baseline, which routes to the legacy workflow.' + } + $legacy = Get-ReleaseFixtureLegacyEvidence -PullRequest $LegacyPullRequest + if ($CaseId -ceq $legacy.case.caseId) { + throw "The candidate case needs a different case ID than the legacy case $($legacy.case.caseId)." + } + Assert-ReleaseFixtureRepository -Lane 'Candidate' + $main = Get-ReleaseFixtureMain -RepositoryApi $fixtureApi + if ($main -cne $legacy.case.source) { + throw "Fixture main at $main must still equal the legacy squash $($legacy.case.source)." + } + Start-ReleaseFixtureCase -Scenario 'one-step' -Candidate $Candidate -CaseId $CaseId -Lane 'Candidate' ` + -ExpectedMain $legacy.case.source -Confirm:$false +} + +function Compare-ReleaseFixturePair { + <# + .SYNOPSIS + Compare validated legacy and candidate evidence. Every comparison is returned, including mismatches. + #> + [OutputType([hashtable])] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Legacy, + + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Candidate + ) + + $legacyTag = [string] $Legacy.release.tag + $expectedCandidateTag = '' + if ($legacyTag -cmatch "\A$versionCore\z") { + $expectedCandidateTag = "v$($Matches.major).$($Matches.minor).$(([bigint] $Matches.patch) + 1)" + } + $rows = @( + @{ + check = 'Case IDs differ' + value = $Candidate.case.caseId + reference = $Legacy.case.caseId + match = $Legacy.case.caseId -cne $Candidate.case.caseId + } + @{ + check = 'Candidate squash parent is the legacy squash' + value = $Candidate.case.parent + reference = $Legacy.case.source + match = $Legacy.case.source -ceq $Candidate.case.parent + } + @{ + check = 'Legacy tag is the first patch on an empty fixture' + value = $Legacy.release.tag + reference = 'v0.0.1' + match = $Legacy.release.tag -ceq 'v0.0.1' + } + @{ + check = 'Candidate tag is the legacy tag plus one patch' + value = $Candidate.release.tag + reference = $expectedCandidateTag + match = $expectedCandidateTag -cne '' -and $Candidate.release.tag -ceq $expectedCandidateTag + } + @{ + check = 'Legacy release target is its squash' + value = $Legacy.release.target + reference = $Legacy.case.source + match = $Legacy.release.target -ceq $Legacy.case.source + } + @{ + check = 'Candidate release target is its squash' + value = $Candidate.release.target + reference = $Candidate.case.source + match = $Candidate.release.target -ceq $Candidate.case.source + } + ) + @{ rows = $rows; match = @($rows | Where-Object { -not $_.match }).Count -eq 0 } +} + +function Get-ReleaseFixturePairEvidence { + <# + .SYNOPSIS + Validate both lanes and compare their releases. + #> + [OutputType([hashtable])] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [ValidatePattern('\A[1-9][0-9]*\z')] + [string] $LegacyPullRequest, + + [Parameter(Mandatory)] + [ValidatePattern('\A[1-9][0-9]*\z')] + [string] $CandidatePullRequest + ) + + $case = Get-MergedReleaseFixtureCase -PullRequest $CandidatePullRequest -Lane 'Candidate' + if ($case.scenario -cne 'one-step') { + throw "The candidate case must use the one-step scenario. See $($case.url)." + } + $report = Wait-ReleaseFixtureReport -Case $case + $legacy = Get-ReleaseFixtureLegacyEvidence -PullRequest $LegacyPullRequest -AlsoTag $report.tag -AllowTargetMismatch + $release = Assert-ReleaseFixtureStableRelease -Tag $report.tag -Source $case.source -Lane 'Candidate' ` + -AlsoTag $legacy.report.tag -AllowTargetMismatch + $candidate = @{ case = $case; report = $report; release = $release } + @{ + legacy = $legacy + candidate = $candidate + comparison = Compare-ReleaseFixturePair -Legacy $legacy -Candidate $candidate + } +} + Export-ModuleMember -Function @( + 'Start-ReleaseFixtureLegacyCase' + 'Start-ReleaseFixturePairCandidate' + 'Get-ReleaseFixturePairEvidence' + 'Compare-ReleaseFixturePair' 'Resolve-ReleaseFixtureCandidate' 'Start-ReleaseFixtureCase' 'Add-ReleaseFixtureLabel' diff --git a/.github/workflows/Fixture-Driver-Test.yml b/.github/workflows/Fixture-Driver-Test.yml index d638f0f..e41ebaa 100644 --- a/.github/workflows/Fixture-Driver-Test.yml +++ b/.github/workflows/Fixture-Driver-Test.yml @@ -19,4 +19,4 @@ jobs: - name: Test the fixture driver without credentials shell: pwsh - run: Invoke-Pester -CI -Path ./tests/ReleaseFixture.Tests.ps1 + run: Invoke-Pester -CI -Path ./tests/ReleaseFixture.Tests.ps1, ./tests/ReleaseFixturePair.Tests.ps1 diff --git a/.github/workflows/Fixture-Pair-Test.yml b/.github/workflows/Fixture-Pair-Test.yml new file mode 100644 index 0000000..593d419 --- /dev/null +++ b/.github/workflows/Fixture-Pair-Test.yml @@ -0,0 +1,190 @@ +name: Fixture Pair Test + +on: + workflow_dispatch: + # checkov:skip=CKV_GHA_7:Validated inputs select pull requests. This workflow does not build or publish a producer artifact. + inputs: + step: + description: Pair step (start the legacy case, then the candidate case, then compare) + type: choice + default: start-legacy + options: + - start-legacy + - start-candidate + - compare + candidate_pr: + description: Open producer pull request number to test (start-candidate only) + type: string + legacy_pr: + description: Merged legacy fixture pull request number (start-candidate and compare) + type: string + candidate_fixture_pr: + description: Merged candidate fixture pull request number (compare only) + type: string + +permissions: {} + +# Share the group of Fixture Test so only one fixture workflow writes at a time. +concurrency: + group: Fixture Test-${{ github.ref }} + cancel-in-progress: false + +defaults: + run: + shell: pwsh + +jobs: + StartLegacy: + name: Open the legacy baseline pull request + if: >- + github.event_name == 'workflow_dispatch' && + github.repository == 'PSModule/Release-GHRepository' && + github.ref == 'refs/heads/main' && + inputs.step == 'start-legacy' + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: read + steps: + - name: Confirm the exact repository, ref, and inputs + env: + CANDIDATE_PR: ${{ inputs.candidate_pr }} + LEGACY_PR: ${{ inputs.legacy_pr }} + CANDIDATE_FIXTURE_PR: ${{ inputs.candidate_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:CANDIDATE_PR -or $env:LEGACY_PR -or $env:CANDIDATE_FIXTURE_PR) { + throw 'The start-legacy step takes no pull request inputs.' + } + + - 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 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: Open the legacy pull request + env: + GH_TOKEN: ${{ steps.fixture-token.outputs.token }} + run: ./.github/scripts/Invoke-ReleaseFixture.ps1 -Mode StartLegacy + + StartCandidate: + name: Open the candidate pull request after the legacy release + if: >- + github.event_name == 'workflow_dispatch' && + github.repository == 'PSModule/Release-GHRepository' && + github.ref == 'refs/heads/main' && + inputs.step == 'start-candidate' + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: read + pull-requests: read + steps: + - name: Confirm the exact repository, ref, and inputs + env: + CANDIDATE_PR: ${{ inputs.candidate_pr }} + LEGACY_PR: ${{ inputs.legacy_pr }} + CANDIDATE_FIXTURE_PR: ${{ inputs.candidate_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:CANDIDATE_PR -cnotmatch '\A[1-9][0-9]*\z' -or $env:LEGACY_PR -cnotmatch '\A[1-9][0-9]*\z' -or + $env:CANDIDATE_FIXTURE_PR) { + throw 'Supply the producer pull request number and the merged legacy pull request number only.' + } + + - 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 without running candidate code + 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: Open the candidate pull request and verify its report + env: + GH_TOKEN: ${{ steps.fixture-token.outputs.token }} + CANDIDATE_SHA: ${{ steps.candidate.outputs.sha }} + LEGACY_PR: ${{ inputs.legacy_pr }} + run: ./.github/scripts/Invoke-ReleaseFixture.ps1 -Mode StartPairCandidate -LegacyPullRequest $env:LEGACY_PR -Candidate $env:CANDIDATE_SHA + + Compare: + name: Compare the legacy and candidate releases + if: >- + github.event_name == 'workflow_dispatch' && + github.repository == 'PSModule/Release-GHRepository' && + github.ref == 'refs/heads/main' && + inputs.step == 'compare' + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: read + steps: + - name: Confirm the exact repository, ref, and inputs + env: + CANDIDATE_PR: ${{ inputs.candidate_pr }} + LEGACY_PR: ${{ inputs.legacy_pr }} + CANDIDATE_FIXTURE_PR: ${{ inputs.candidate_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:LEGACY_PR -cnotmatch '\A[1-9][0-9]*\z' -or $env:CANDIDATE_FIXTURE_PR -cnotmatch '\A[1-9][0-9]*\z' -or + $env:CANDIDATE_PR) { + throw 'Supply only the merged legacy and candidate fixture pull request numbers.' + } + + - 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: Compare both cases + env: + GH_TOKEN: ${{ steps.fixture-token.outputs.token }} + LEGACY_PR: ${{ inputs.legacy_pr }} + CANDIDATE_FIXTURE_PR: ${{ inputs.candidate_fixture_pr }} + run: ./.github/scripts/Invoke-ReleaseFixture.ps1 -Mode ComparePair -LegacyPullRequest $env:LEGACY_PR -PullRequest $env:CANDIDATE_FIXTURE_PR diff --git a/docs/Fixture-Test.md b/docs/Fixture-Test.md index e3ad956..bbb6ade 100644 --- a/docs/Fixture-Test.md +++ b/docs/Fixture-Test.md @@ -29,13 +29,74 @@ before you start `configured-default` or `missing-decision`. The driver includes 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. +## Compare against the published baseline + +After the workflow lands on `main`, open [Fixture Pair Test](https://github.com/PSModule/Release-GHRepository/actions/workflows/Fixture-Pair-Test.yml) +in the producer repository, `PSModule/Release-GHRepository`. Select **Run workflow** and branch `main` for each step. You need write +access to the producer repository to start a run. Do not dispatch from the fixture repository or from a pull request branch. + +The workflow runs two cases in [`Release-GHRepository-Test`](https://github.com/PSModule/Release-GHRepository-Test). +The first case uses the published `v2.0.3` action (`750abed0ecab02394554b610dc3aa191e75e3248`) for a `one-step` release with `release:patch`. +The second case uses the same scenario and label with an exact producer pull request SHA. The fixture routes a case file by its action SHA. +The `v2.0.3` SHA runs only in `Legacy-Release-Test.yml`. Other SHAs run only in the candidate workflow. + +The cases are sequential, and their case IDs differ. The legacy case file stays on fixture `main`, so the candidate case starts from the +legacy squash commit. Each release is checked relative to its own starting version, not against the other tag: the legacy release on an +empty fixture must be `v0.0.1`, and the candidate release must be that tag plus one patch (`v0.0.2`). + +This setup supports one comparison that starts with an empty inventory. The workflow and driver accept only this fixture repository. +A different fixture repository needs code and configuration changes. + +Minimum setup: + +- Fixture `main` includes `.github/workflows/Legacy-Release-Test.yml` and the schema-2 `tests/FixtureContract.json`. +- The fixture has no releases, no tags, and no open fixture pull request. +- The Shelly app is installed on the fixture repository. The producer workflow has access to `SHELLY_CLIENT_ID` and `SHELLY_PRIVATE_KEY`. +- The `release:patch` label exists in the fixture. +- Fixture pull requests use the normal independent review and squash merge. +- Do not update the fixture case branches. +- Do not run ordinary fixture cases or merge unrelated pull requests in the fixture until the pair finishes. + +| Step | Inputs | Result | +| --- | --- | --- | +| `start-legacy` | None | Opens the legacy pull request and adds `release:patch`. | +| `start-candidate` | `candidate_pr` (open producer pull request), `legacy_pr` | Checks the legacy evidence, then opens the candidate pull request on the legacy squash. | +| `compare` | `legacy_pr`, `candidate_fixture_pr` | Verifies both cases and compares them. | + +1. Run `start-legacy` without any pull request numbers. Find the legacy fixture pull request in the job summary. + Use normal independent review and squash merge for that pull request. The driver does not approve or merge it. +2. Wait for a successful legacy bot report on the merged fixture pull request. Run `start-candidate` with `candidate_pr` and `legacy_pr`. + Keep the producer pull request open. The driver checks the report, including the exact action pin, head, squash, run URL, and tag `v0.0.1`. + The legacy squash parent must match the original case base. Fixture `main` must still be the legacy squash. + The only release and tag must be `v0.0.1` at that squash. The driver opens the candidate case only after these checks pass. + It reads the exact producer pull request SHA through the API. It does not check out or run that code. +3. Wait for a successful `start-candidate` run. Find the candidate fixture pull request in the job summary. + Use normal independent review and squash merge for that pull request. +4. Run `compare` with `legacy_pr` and `candidate_fixture_pr`. Check the job summary for the result. + +If a start run fails after it opens a fixture pull request, use the job summary to find it. Close that pull request +without a merge before you retry the start step. + +The job summary lists the action SHAs, pull requests, run URLs, squash commits, parents, and tags. It shows every comparison, +including a mismatch in the case IDs, the candidate squash parent, a tag, or a release target. A mismatch fails the job after the +summary is written. Other validation failures stop the job before the summary: a missing, stale, or invalid report, an unrelated +release or tag in the inventory, a one-file squash that has other changes, or a tag that does not match the report. + +Each step mints one token that is scoped to the fixture repository. The start steps request write access. The `compare` step requests +read access only. The workflow shares the concurrency group of Fixture Test, so only one fixture workflow runs at a time. + +Limits of this first case: it covers only the `one-step` scenario with `release:patch`. The legacy workflow reports after the squash +merge and does not report at pull request open. The driver finds each report only by the exact schema 2 fields. It does not prove that +the legacy workflow is correct. After the pair finishes, keep both fixture releases as evidence. This workflow cannot start another pair +with that inventory. + ## 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 +Invoke-Pester -Path ./tests/ReleaseFixture.Tests.ps1, ./tests/ReleaseFixturePair.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/ReleaseFixturePair.Tests.ps1 b/tests/ReleaseFixturePair.Tests.ps1 new file mode 100644 index 0000000..fbcfd82 --- /dev/null +++ b/tests/ReleaseFixturePair.Tests.ps1 @@ -0,0 +1,451 @@ +#Requires -Version 7.4 + +BeforeAll { + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..' -AdditionalChildPath '.github', 'scripts', 'ReleaseFixture.psm1') + + $script:baseline = '750abed0ecab02394554b610dc3aa191e75e3248' + $script:candidate = 'a' * 40 + $script:mainSha = 'c' * 40 + $script:legacyHead = 'b' * 40 + $script:legacySquash = 'd' * 40 + $script:candidateHead = 'e' * 40 + $script:candidateSquash = '9' * 40 + $script:fixtureApi = '/repos/PSModule/Release-GHRepository-Test' + $script:fixtureUrl = 'https://github.com/PSModule/Release-GHRepository-Test' + $script:shelly = @{ id = 314722336; login = 'psmodule-s-shelly[bot]'; type = 'Bot' } + + function New-TestReport { + <# + .SYNOPSIS + Create an anonymous bot report comment with selected field overrides. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'In-memory.')] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [hashtable] $Fields + ) + + $report = @{ + schema = 2 + caseId = '123-1' + candidate = $script:baseline + scenario = 'one-step' + event = 'pull_request' + activity = 'closed' + head = $script:legacyHead + source = $script:legacySquash + testedSource = $script:legacySquash + verified = $true + oracle = 'success' + run = "$script:fixtureUrl/actions/runs/60" + tag = 'v0.0.1' + } + foreach ($key in $Fields.Keys) { + $report[$key] = $Fields[$key] + } + @{ + user = @{ login = 'github-actions[bot]'; id = 41898282; type = 'Bot' } + body = ('', '```json', ($report | ConvertTo-Json -Compress), '```') -join "`n" + } + } + + function New-TestPull { + <# + .SYNOPSIS + Create an anonymous merged fixture pull request. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'In-memory.')] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [int] $Number, + + [Parameter(Mandatory)] + [string] $CaseId, + + [Parameter(Mandatory)] + [string] $Head, + + [Parameter(Mandatory)] + [string] $Squash + ) + + $repo = @{ id = 1477027955; full_name = 'PSModule/Release-GHRepository-Test' } + @{ + state = 'closed' + merged = $true + number = $Number + commits = 1 + merge_commit_sha = $Squash + user = $script:shelly + base = @{ ref = 'main'; repo = $repo } + head = @{ ref = "release-fixture/$CaseId"; repo = $repo; sha = $Head } + } + } +} + +Describe 'Baseline-first pair in one fixture repository' { + BeforeEach { + $script:calls = @() + $script:repo = @{ + main = $script:legacySquash + releases = @(@{ tag_name = 'v0.0.1'; draft = $false; prerelease = $false }) + tags = @(@{ ref = 'refs/tags/v0.0.1' }) + tagSha = @{ 'v0.0.1' = $script:legacySquash } + open = @() + workflow = $true + repoId = 1477027955 + pulls = @{ 7 = New-TestPull -Number 7 -CaseId '123-1' -Head $script:legacyHead -Squash $script:legacySquash } + squashes = @{ + $script:legacySquash = @{ + sha = $script:legacySquash + parents = @(@{ sha = $script:mainSha }) + files = @(@{ filename = 'tests/cases/123-1.json'; status = 'added' }) + } + $script:candidateSquash = @{ + sha = $script:candidateSquash + parents = @(@{ sha = $script:legacySquash }) + files = @(@{ filename = 'tests/cases/124-1.json'; status = 'added' }) + } + } + cases = @{ + $script:legacyHead = @{ scenario = 'one-step'; candidate = $script:baseline } + $script:legacySquash = @{ scenario = 'one-step'; candidate = $script:baseline } + $script:candidateHead = @{ scenario = 'one-step'; candidate = $script:candidate } + $script:candidateSquash = @{ scenario = 'one-step'; candidate = $script:candidate } + } + comments = @{ 7 = @(New-TestReport -Fields @{}) } + } + + Mock Invoke-ReleaseFixtureRequest -ModuleName ReleaseFixture { + $effectiveMethod = $Method ?? 'GET' + $script:calls += [pscustomobject] @{ Method = $effectiveMethod; Path = $Path; Token = $TokenVariable } + if ($Path -cne $script:fixtureApi -and -not $Path.StartsWith("$script:fixtureApi/")) { + throw "Unexpected repository: $Path" + } + $state = $script:repo + $rest = $Path.Substring($script:fixtureApi.Length) + $repoInfo = @{ id = $state.repoId; full_name = 'PSModule/Release-GHRepository-Test' } + switch -Regex ("$effectiveMethod $rest") { + '\AGET \z' { return @{ id = $state.repoId; full_name = 'PSModule/Release-GHRepository-Test'; default_branch = 'main' } } + '\AGET /pulls\?state=open\z' { return $state.open } + '\AGET /git/ref/heads/main\z' { return @{ object = @{ type = 'commit'; sha = $state.main } } } + '\AGET /releases\z' { return $state.releases } + '\AGET /git/matching-refs/tags\z' { return $state.tags } + '\AGET /git/ref/tags/(?.+)\z' { return @{ object = @{ type = 'commit'; sha = $state.tagSha[$Matches.tag] } } } + '\AGET /git/commits/(?[0-9a-f]{40})\z' { + $commit = @{ sha = $Matches.sha } + if ($commit.sha -ceq $script:legacyHead) { + $commit.parents = @(@{ sha = $script:mainSha }) + } + return $commit + } + '\AGET /compare/' { return @{ status = 'ahead' } } + '\AGET /contents/tests/FixtureContract\.json' { + $json = ConvertTo-Json -Compress -Depth 4 -InputObject @{ + schema = 2 + scenarios = @{ + preview = 'release:patch' + staged = 'release:patch' + 'one-step' = 'release:patch' + 'configured-default' = '' + 'missing-decision' = '' + skip = 'release:skip' + 'ci-failure' = 'release:patch' + } + } + return @{ type = 'file'; encoding = 'base64'; content = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($json)) } + } + '\AGET /contents/tests/cases/[^?]+\?ref=(?[0-9a-f]{40})\z' { + $json = ConvertTo-Json -Compress -InputObject $state.cases[$Matches.ref] + return @{ type = 'file'; encoding = 'base64'; content = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($json)) } + } + '\AGET /contents/\.github/workflows/Legacy-Release-Test\.yml\?ref=' { + if (-not $state.workflow) { + throw 'GitHub API GET returned HTTP 404.' + } + return @{ type = 'file' } + } + '\AGET /labels/release%3Apatch\z' { return @{ name = 'release:patch' } } + '\AGET /pulls/(?[0-9]+)\z' { return $state.pulls[[int] $Matches.number] } + '\AGET /commits/(?[0-9a-f]{40})\z' { return $state.squashes[$Matches.sha] } + '\AGET /issues/(?[0-9]+)/comments\z' { return @($state.comments[[int] $Matches.number]) } + '\APOST /git/refs\z' { return @{ ref = $Body.ref } } + '\APUT /contents/tests/cases/(?[^/]+)\.json\z' { + $script:written = $Body + return @{ commit = @{ sha = $script:candidateHead; parents = @(@{ sha = $state.main }) } } + } + '\APOST /pulls\z' { + return @{ + number = 12 + state = 'open' + user = $script:shelly + base = @{ ref = 'main'; repo = $repoInfo; sha = $state.main } + head = @{ ref = $Body.head; repo = $repoInfo; sha = $script:candidateHead } + } + } + default { throw "Unexpected request: $effectiveMethod $Path" } + } + } + } + + Describe 'Start-ReleaseFixtureLegacyCase' { + BeforeEach { + $script:repo.main = $script:mainSha + $script:repo.releases = @() + $script:repo.tags = @() + $script:repo.tagSha = @{} + } + + It 'refuses before writing' -ForEach @( + @{ Name = 'a release'; Setup = { $script:repo.releases = @(@{ tag_name = 'v1.0.0' }) }; Error = '*no releases*' } + @{ Name = 'a tag'; Setup = { $script:repo.tags = @(@{ ref = 'refs/tags/v1.0.0' }) }; Error = '*no releases*' } + @{ + Name = 'an open fixture pull request' + Setup = { $script:repo.open = @(New-TestPull -Number 3 -CaseId '1-1' -Head ('1' * 40) -Squash ('2' * 40)) } + Error = '*already open*' + } + @{ Name = 'a fixture without the legacy workflow'; Setup = { $script:repo.workflow = $false }; Error = '*HTTP 404*' } + @{ Name = 'another repository identity'; Setup = { $script:repo.repoId = 5 }; Error = '*identity*' } + ) { + & $Setup + { Start-ReleaseFixtureLegacyCase -CaseId '123-1' } | Should -Throw $Error + @($script:calls | Where-Object Method -In 'POST', 'PUT').Count | Should -Be 0 + } + + It 'opens only the pinned one-step case with the one fixture token' { + $result = Start-ReleaseFixtureLegacyCase -CaseId '123-1' + $result.lane | Should -BeExactly 'Legacy' + $result.candidate | Should -BeExactly $script:baseline + $result.label | Should -BeExactly 'release:patch' + $writes = @($script:calls | Where-Object Method -In 'POST', 'PUT') + $writes.Count | Should -Be 3 + $script:calls.Token | Select-Object -Unique | Should -BeExactly 'GH_TOKEN' + $case = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($script:written.content)) | ConvertFrom-Json -AsHashtable + $case.scenario | Should -BeExactly 'one-step' + $case.candidate | Should -BeExactly $script:baseline + } + + It 'links the opened pull request when the label request fails' { + Mock Start-ReleaseFixtureLegacyCase { + @{ + number = 12 + url = 'https://github.com/PSModule/Release-GHRepository-Test/pull/12' + caseId = '123-1' + candidate = '750abed0ecab02394554b610dc3aa191e75e3248' + head = 'b' * 40 + } + } + Mock Add-ReleaseFixtureLabel { throw 'GitHub API POST returned HTTP 403.' } + + $driver = Join-Path -Path $PSScriptRoot -ChildPath '..' -AdditionalChildPath '.github', 'scripts', 'Invoke-ReleaseFixture.ps1' + $summary = Join-Path -Path $TestDrive -ChildPath 'summary.md' + Set-Content -LiteralPath $summary -Value '' + $dispatch = @{ + GITHUB_EVENT_NAME = 'workflow_dispatch' + GITHUB_REPOSITORY = 'PSModule/Release-GHRepository' + GITHUB_REF = 'refs/heads/main' + GITHUB_RUN_ID = '123' + GITHUB_RUN_ATTEMPT = '1' + GITHUB_STEP_SUMMARY = $summary + GH_TOKEN = $null + } + $previous = @{} + try { + foreach ($name in $dispatch.Keys) { + $previous[$name] = [Environment]::GetEnvironmentVariable($name) + [Environment]::SetEnvironmentVariable($name, $dispatch[$name]) + } + { & $driver -Mode StartLegacy -Confirm:$false } | Should -Throw '*HTTP 403*' + $text = Get-Content -LiteralPath $summary -Raw + $text | Should -MatchExactly ([regex]::Escape("$script:fixtureUrl/pull/12")) + $text | Should -Not -Match 'Approve and squash merge' + } finally { + foreach ($name in $previous.Keys) { + [Environment]::SetEnvironmentVariable($name, $previous[$name]) + } + } + } + } + + Describe 'Start-ReleaseFixturePairCandidate' { + It 'refuses before writing' -ForEach @( + @{ Name = 'a missing legacy report'; Setup = { $script:repo.comments[7] = @() }; Error = '*No matching*' } + @{ + Name = 'a stale report for another head' + Setup = { $script:repo.comments[7] = @(New-TestReport -Fields @{ head = 'f' * 40 }) } + Error = '*No matching*' + } + @{ + Name = 'a report with another baseline' + Setup = { $script:repo.comments[7] = @(New-TestReport -Fields @{ candidate = $script:candidate }) } + Error = '*No matching*' + } + @{ + Name = 'an unsuccessful oracle' + Setup = { $script:repo.comments[7] = @(New-TestReport -Fields @{ oracle = 'failure' }) } + Error = '*oracle*' + } + @{ + Name = 'a report without the stable tag' + Setup = { $script:repo.comments[7] = @(New-TestReport -Fields @{ tag = $null }) } + Error = '*stable tag*' + } + @{ + Name = 'a run outside the fixture repository' + Setup = { + $run = 'https://github.com/PSModule/Release-GHRepository/actions/runs/60' + $script:repo.comments[7] = @(New-TestReport -Fields @{ run = $run }) + } + Error = '*run URL*' + } + @{ + Name = 'a legacy tag that is not the first patch' + Setup = { + $script:repo.comments[7] = @(New-TestReport -Fields @{ tag = 'v0.1.0' }) + $script:repo.releases = @(@{ tag_name = 'v0.1.0'; draft = $false; prerelease = $false }) + $script:repo.tags = @(@{ ref = 'refs/tags/v0.1.0' }) + $script:repo.tagSha = @{ 'v0.1.0' = $script:legacySquash } + } + Error = '*v0.0.1*' + } + @{ Name = 'a tag that does not point to the squash'; Setup = { $script:repo.tagSha['v0.0.1'] = 'f' * 40 }; Error = '*not the squash*' } + @{ + Name = 'an unrelated second release' + Setup = { $script:repo.releases += @{ tag_name = 'v0.0.2'; draft = $false; prerelease = $false } } + Error = '*only the stable release*' + } + @{ + Name = 'a legacy case with another action pin' + Setup = { + $other = @{ scenario = 'one-step'; candidate = $script:candidate } + $script:repo.cases[$script:legacySquash] = $other + $script:repo.cases[$script:legacyHead] = $other + } + Error = '*pinned baseline*' + } + @{ Name = 'a main that moved after the legacy squash'; Setup = { $script:repo.main = 'f' * 40 }; Error = '*legacy squash*' } + @{ + Name = 'a legacy squash on a different base from the original case' + Setup = { $script:repo.squashes[$script:legacySquash].parents = @(@{ sha = 'f' * 40 }) } + Error = '*legacy squash parent*original case base*' + } + @{ + Name = 'an open fixture pull request' + Setup = { $script:repo.open = @(New-TestPull -Number 4 -CaseId '2-1' -Head ('1' * 40) -Squash ('2' * 40)) } + Error = '*already open*' + } + ) { + & $Setup + { Start-ReleaseFixturePairCandidate -LegacyPullRequest '7' -Candidate $script:candidate -CaseId '124-1' } | Should -Throw $Error + @($script:calls | Where-Object Method -In 'POST', 'PUT').Count | Should -Be 0 + } + + It 'refuses before writing' -ForEach @( + @{ Name = 'the legacy case ID'; Candidate = ('a' * 40); CaseId = '123-1'; Error = '*different case ID*' } + @{ Name = 'the legacy action pin'; Candidate = '750abed0ecab02394554b610dc3aa191e75e3248'; CaseId = '124-1'; Error = '*legacy workflow*' } + ) { + { Start-ReleaseFixturePairCandidate -LegacyPullRequest '7' -Candidate $Candidate -CaseId $CaseId } | Should -Throw $Error + @($script:calls | Where-Object Method -In 'POST', 'PUT').Count | Should -Be 0 + } + + It 'opens a distinct case on the legacy squash with the one fixture token' { + $result = Start-ReleaseFixturePairCandidate -LegacyPullRequest '7' -Candidate $script:candidate -CaseId '124-1' + $result.caseId | Should -BeExactly '124-1' + $result.lane | Should -BeExactly 'Candidate' + $result.candidate | Should -BeExactly $script:candidate + $result.activity | Should -BeExactly 'labeled' + @($script:calls | Where-Object Method -In 'POST', 'PUT').Count | Should -Be 3 + $script:calls.Token | Select-Object -Unique | Should -BeExactly 'GH_TOKEN' + } + } + + Describe 'Get-ReleaseFixturePairEvidence' { + BeforeEach { + $script:repo.main = $script:candidateSquash + $script:repo.pulls[12] = New-TestPull -Number 12 -CaseId '124-1' -Head $script:candidateHead -Squash $script:candidateSquash + $script:repo.releases += @{ tag_name = 'v0.0.2'; draft = $false; prerelease = $false } + $script:repo.tags += @{ ref = 'refs/tags/v0.0.2' } + $script:repo.tagSha['v0.0.2'] = $script:candidateSquash + $script:repo.comments[12] = @( + New-TestReport -Fields @{ + caseId = '124-1' + candidate = $script:candidate + event = 'push' + activity = $null + head = $script:candidateHead + source = $script:candidateSquash + testedSource = $script:candidateSquash + run = "$script:fixtureUrl/actions/runs/61" + tag = 'v0.0.2' + } + ) + } + + It 'passes when each release is relative to its own starting version' { + $result = Get-ReleaseFixturePairEvidence -LegacyPullRequest '7' -CandidatePullRequest '12' + $result.comparison.match | Should -BeTrue + $result.legacy.release.tag | Should -BeExactly 'v0.0.1' + $result.candidate.release.tag | Should -BeExactly 'v0.0.2' + $script:calls.Token | Select-Object -Unique | Should -BeExactly 'GH_TOKEN' + } + + It 'returns a candidate tag that points to another commit so the comparison can show it' { + $script:repo.tagSha['v0.0.2'] = 'f' * 40 + $result = Get-ReleaseFixturePairEvidence -LegacyPullRequest '7' -CandidatePullRequest '12' + $result.comparison.match | Should -BeFalse + @($result.comparison.rows | Where-Object { -not $_.match }).check | Should -Contain 'Candidate release target is its squash' + } + + It 'returns a candidate squash that does not follow the legacy squash' { + $script:repo.squashes[$script:candidateSquash].parents = @(@{ sha = $script:mainSha }) + $result = Get-ReleaseFixturePairEvidence -LegacyPullRequest '7' -CandidatePullRequest '12' + $result.comparison.match | Should -BeFalse + @($result.comparison.rows | Where-Object { -not $_.match }).check | Should -Contain 'Candidate squash parent is the legacy squash' + } + + It 'rejects an unrelated release in the inventory' { + $script:repo.releases += @{ tag_name = 'v0.0.3'; draft = $false; prerelease = $false } + { Get-ReleaseFixturePairEvidence -LegacyPullRequest '7' -CandidatePullRequest '12' } | Should -Throw '*only the stable release*' + } + } + + Describe 'Compare-ReleaseFixturePair' { + BeforeEach { + $script:evidence = { + param($Case, $Parent, $Squash, $Tag) + @{ + case = @{ caseId = $Case; parent = $Parent; source = $Squash } + release = @{ tag = $Tag; target = $Squash } + } + } + $script:legacyEvidence = & $script:evidence '123-1' $script:mainSha $script:legacySquash 'v0.0.1' + } + + It 'matches a sequential patch release' { + $other = & $script:evidence '124-1' $script:legacySquash $script:candidateSquash 'v0.0.2' + $result = Compare-ReleaseFixturePair -Legacy $script:legacyEvidence -Candidate $other + $result.match | Should -BeTrue + $result.rows.Count | Should -Be 6 + } + + It 'reports a as a visible mismatch' -ForEach @( + @{ Name = 'repeated case ID'; Case = '123-1'; Parent = ('d' * 40); Tag = 'v0.0.2'; Check = 'Case IDs differ' } + @{ Name = 'wrong parent'; Case = '124-1'; Parent = ('f' * 40); Tag = 'v0.0.2'; Check = 'Candidate squash parent is the legacy squash' } + @{ + Name = 'wrong increment' + Case = '124-1' + Parent = ('d' * 40) + Tag = 'v0.1.0' + Check = 'Candidate tag is the legacy tag plus one patch' + } + ) { + $other = & $script:evidence $Case $Parent $script:candidateSquash $Tag + $result = Compare-ReleaseFixturePair -Legacy $script:legacyEvidence -Candidate $other + $result.match | Should -BeFalse + @($result.rows | Where-Object { -not $_.match }).check | Should -Contain $Check + $result.rows.Count | Should -Be 6 + } + } +}