diff --git a/.gitattributes b/.gitattributes index 96c2e0d..4088911 100644 --- a/.gitattributes +++ b/.gitattributes @@ -13,3 +13,6 @@ *.png binary *.dll binary *.so binary + +# Fixture seed files must keep the exact bytes of the fixture blobs. +fixtures/release-fixture/seed/** -text -whitespace \ No newline at end of file diff --git a/.github/scripts/Invoke-ReleaseFixture.ps1 b/.github/scripts/Invoke-ReleaseFixture.ps1 index e7f9fb2..1f9c346 100644 --- a/.github/scripts/Invoke-ReleaseFixture.ps1 +++ b/.github/scripts/Invoke-ReleaseFixture.ps1 @@ -14,7 +14,7 @@ param( # 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', 'StartLegacy', 'StartPairCandidate', 'ComparePair')] + [ValidateSet('Resolve', 'Start', 'Run', 'Verify', 'StartLegacy', 'StartPairCandidate', 'ComparePair', 'RunPair', 'RunLegacy')] [string] $Mode, # Producer pull request number in Resolve mode or fixture pull request number in Verify mode. @@ -32,9 +32,15 @@ param( [Parameter()] [string] $Scenario, - # Resolved producer SHA in Start mode. + # Resolved producer SHA in Start, StartPairCandidate, and RunPair modes. [Parameter()] - [string] $Candidate + [string] $Candidate, + + # Exact head SHA of the open legacy fixture pull request to resume in RunPair and RunLegacy modes. + # Omit it in RunPair mode when the legacy pull request is already merged. + [Parameter()] + [AllowEmptyString()] + [string] $LegacyHead ) $ErrorActionPreference = 'Stop' @@ -45,6 +51,44 @@ if ($env:GITHUB_EVENT_NAME -cne 'workflow_dispatch' -or $env:GITHUB_REPOSITORY - } Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath 'ReleaseFixture.psm1') +function Write-ReleaseFixturePairSummary { + <# + .SYNOPSIS + Write the pair evidence and comparison to the job summary. Fail after writing it if any comparison does not match. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Pair + ) + + $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 +} + switch ($Mode) { 'Resolve' { $sha = Resolve-ReleaseFixtureCandidate -PullRequest $PullRequest @@ -71,6 +115,27 @@ switch ($Mode) { Add-ReleaseFixtureLabel -Case $case -Confirm:$false $runType = 'Open pull request' } + 'Run' { + $caseId = "$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" + if (-not $PSCmdlet.ShouldProcess("Fixture case $caseId", 'Run')) { + return + } + $progress = { + param($Line) + Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Value @("- $Line") + Write-Information -MessageData $Line -InformationAction Continue + } + $run = Invoke-ReleaseFixtureRun -Scenario $Scenario -Candidate $Candidate -CaseId $caseId -Progress $progress -Confirm:$false + $summary = "Case: $($run.case.caseId) | Scenario: $($run.case.scenario) | Candidate: $($run.case.candidate)" + if ($null -ne $run.merged) { + $summary += " | Squash SHA: $($run.merged.source)" + if ($null -ne $run.pushReport.tag) { + $summary += " | Tag: $($run.pushReport.tag)" + } + } + Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Value @('', $summary, '') + return + } 'StartLegacy' { $caseId = "$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" if (-not $PSCmdlet.ShouldProcess("Legacy fixture case $caseId", 'Start')) { @@ -107,33 +172,59 @@ switch ($Mode) { 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 ' | ') |" + 'RunPair' { + if (-not $PSCmdlet.ShouldProcess("Baseline-first pair for candidate $Candidate", 'Run')) { + return + } + # Two case IDs per attempt, so the legacy and candidate IDs never collide, even across attempts. + $attempt = [int] $env:GITHUB_RUN_ATTEMPT + $legacyCaseId = "$env:GITHUB_RUN_ID-$(2 * $attempt - 1)" + $candidateCaseId = "$env:GITHUB_RUN_ID-$(2 * $attempt)" + $progress = { + param($Line) + Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Value @("- $Line") + Write-Information -MessageData $Line -InformationAction Continue + } + $parameters = @{ + Candidate = $Candidate + LegacyCaseId = $legacyCaseId + CandidateCaseId = $candidateCaseId + LegacyPullRequest = $LegacyPullRequest + LegacyHead = $LegacyHead + Progress = $progress + } + $pair = Invoke-ReleaseFixturePair @parameters -Confirm:$false + Write-ReleaseFixturePairSummary -Pair $pair + return + } + 'RunLegacy' { + if (-not $PSCmdlet.ShouldProcess('Legacy lane', 'Run')) { + return } - $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 |" + $attempt = [int] $env:GITHUB_RUN_ATTEMPT + $progress = { + param($Line) + Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Value @("- $Line") + Write-Information -MessageData $Line -InformationAction Continue } - 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.' + $parameters = @{ + CaseId = "$env:GITHUB_RUN_ID-$(2 * $attempt - 1)" + LegacyPullRequest = $LegacyPullRequest + LegacyHead = $LegacyHead + Progress = $progress } - Write-Information -MessageData 'The legacy and candidate evidence match.' -InformationAction Continue + $legacy = Invoke-ReleaseFixtureLegacy @parameters -Confirm:$false + Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Value @( + "Legacy baseline verified: [#$($legacy.case.number)]($($legacy.case.url)) | Squash: $($legacy.case.source) | Tag: $($legacy.report.tag)" + '' + "To finish the pair, dispatch run-pair with candidate_pr and legacy_pr=$($legacy.case.number). The merge is not repeated." + '' + ) + return + } + 'ComparePair' { + $pair = Get-ReleaseFixturePairEvidence -LegacyPullRequest $LegacyPullRequest -CandidatePullRequest $PullRequest + Write-ReleaseFixturePairSummary -Pair $pair return } 'Verify' { diff --git a/.github/scripts/ReleaseFixture.psm1 b/.github/scripts/ReleaseFixture.psm1 index da8e12e..47de55b 100644 --- a/.github/scripts/ReleaseFixture.psm1 +++ b/.github/scripts/ReleaseFixture.psm1 @@ -11,7 +11,20 @@ $fixtureId = 1477027955 $fixtureUrl = "https://github.com/$fixtureRepo" $legacyBaseline = '750abed0ecab02394554b610dc3aa191e75e3248' $legacyWorkflowPath = '.github/workflows/Legacy-Release-Test.yml' +# The producer repository owns the trusted fixture files. Fixture main must match this seed before the driver writes a case. +$seedRoot = Join-Path -Path $PSScriptRoot -ChildPath '..' -AdditionalChildPath '..', 'fixtures', 'release-fixture', 'seed' +$trustedPathPattern = '\A(?:\.github/workflows/|tests/|tests-baseline/)' $shaPattern = '\A[0-9a-f]{40}\z' +# The fixture's pull request workflows run as GitHub Actions. Each check name below must succeed once per pull request event. +$actionsAppId = 15368 +$requiredChecks = 'Select the case and record the inventory', 'Test the exact commit' +$failedConclusions = 'failure', 'cancelled', 'timed_out', 'action_required', 'stale', 'startup_failure' +# Only this fixture workflow runs on a pull request. Its suites are the only suites that count as pre-merge evidence. +$prWorkflowFile = 'Release-Test.yml' +$prWorkflowPath = ".github/workflows/$prWorkflowFile" +# The unauthenticated REST limit is 60 requests per hour for each IP. One process may use at most this many of them. +$anonymousLimit = 50 +$script:anonymousRequests = 0 $versionCore = 'v(?0|[1-9][0-9]*)\.(?0|[1-9][0-9]*)\.(?0|[1-9][0-9]*)' $scenarioLabels = @{ preview = 'release:patch' @@ -60,28 +73,47 @@ function Invoke-ReleaseFixtureRequest { [string] $TokenVariable = 'GH_TOKEN', [Parameter()] - [ValidateSet('GET', 'POST', 'PUT')] + [ValidateSet('GET', 'POST', 'PUT', 'PATCH')] [string] $Method = 'GET', [Parameter()] [hashtable] $Body, [Parameter()] - [switch] $Paged + [switch] $Paged, + + # Send no credentials. Only GET for one public fixture commit's check runs and its Release-Test.yml runs is allowed. + [Parameter()] + [switch] $Anonymous ) - $value = [Environment]::GetEnvironmentVariable($TokenVariable) - if ([string]::IsNullOrWhiteSpace($value)) { - throw "$TokenVariable must be set for this step." + $headers = @{ + Accept = 'application/vnd.github+json' + 'X-GitHub-Api-Version' = '2026-03-10' + } + if ($Anonymous) { + $api = [regex]::Escape($fixtureApi) + $workflowFile = [regex]::Escape($prWorkflowFile) + $checkRuns = "$api/commits/[0-9a-f]{40}/check-runs\?per_page=100" + $workflowRuns = "$api/actions/workflows/$workflowFile/runs\?event=pull_request&head_sha=[0-9a-f]{40}&per_page=100" + if ($Method -cne 'GET' -or $null -ne $Body -or $Path -cnotmatch "\A(?:$checkRuns|$workflowRuns)\z") { + throw "An anonymous request may only read the check runs and $prWorkflowFile runs of one fixture commit: $Method $Path" + } + if ($script:anonymousRequests -ge $anonymousLimit) { + throw "This job used its budget of $anonymousLimit unauthenticated requests. Run it again later." + } + $script:anonymousRequests++ + } else { + $value = [Environment]::GetEnvironmentVariable($TokenVariable) + if ([string]::IsNullOrWhiteSpace($value)) { + throw "$TokenVariable must be set for this step." + } + $headers.Authorization = "Bearer $value" } $request = @{ Method = $Method - Headers = @{ - Accept = 'application/vnd.github+json' - Authorization = "Bearer $value" - 'X-GitHub-Api-Version' = '2026-03-10' - } + Headers = $headers MaximumRedirection = 0 ConnectionTimeoutSeconds = 20 OperationTimeoutSeconds = 20 @@ -432,6 +464,77 @@ function Assert-ReleaseFixtureStableRelease { @{ tag = $Tag; target = $target } } +function Get-ReleaseFixtureSeed { + <# + .SYNOPSIS + Read the versioned seed of the trusted fixture files. Return each path with its git blob SHA. + #> + [OutputType([System.Collections.Generic.Dictionary[string, string]])] + [CmdletBinding()] + param() + + if (-not (Test-Path -LiteralPath $seedRoot -PathType Container)) { + throw "The fixture seed directory is missing: $seedRoot" + } + $seed = [System.Collections.Generic.Dictionary[string, string]]::new([StringComparer]::Ordinal) + foreach ($file in Get-ChildItem -LiteralPath $seedRoot -Recurse -File -Force) { + $bytes = [IO.File]::ReadAllBytes($file.FullName) + $prefix = [Text.Encoding]::ASCII.GetBytes("blob $($bytes.Length)`0") + $hash = [Security.Cryptography.SHA1]::HashData([byte[]] ($prefix + $bytes)) + $seed[[IO.Path]::GetRelativePath($seedRoot, $file.FullName).Replace('\', '/')] = [Convert]::ToHexString($hash).ToLowerInvariant() + } + if ($seed.Count -eq 0) { + throw "The fixture seed has no files: $seedRoot" + } + $seed +} + +function Assert-ReleaseFixtureSeed { + <# + .SYNOPSIS + Fail unless the trusted files of fixture main match the versioned seed in this repository. Runtime case data is ignored. + + .EXAMPLE + Assert-ReleaseFixtureSeed -Main ('a' * 40) + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [ValidatePattern('\A[0-9a-f]{40}\z')] + [string] $Main, + + [Parameter()] + [ValidateSet('Candidate', 'Legacy')] + [string] $Lane = 'Candidate' + ) + + $laneInfo = Get-ReleaseFixtureLane -Name $Lane + $seed = Get-ReleaseFixtureSeed + $tree = Invoke-ReleaseFixtureRequest -Path "$($laneInfo.Api)/git/trees/${Main}?recursive=1" -TokenVariable $laneInfo.TokenVariable + if ($tree['truncated'] -ne $false) { + throw "The file list of fixture main at $Main is incomplete, so the trusted files cannot be checked." + } + $actual = [System.Collections.Generic.Dictionary[string, object]]::new([StringComparer]::Ordinal) + foreach ($entry in $tree['tree']) { + if ($entry['type'] -cne 'blob' -or $entry['path'] -cnotmatch $trustedPathPattern -or $entry['path'] -clike 'tests/cases/*') { + continue + } + $actual[$entry['path']] = $entry + } + $missing = @($seed.Keys | Where-Object { -not $actual.ContainsKey($_) } | Sort-Object) + $unexpected = @($actual.Keys | Where-Object { -not $seed.ContainsKey($_) } | Sort-Object) + $drifted = @($seed.Keys | Where-Object { + $actual.ContainsKey($_) -and ($actual[$_]['sha'] -cne $seed[$_] -or $actual[$_]['mode'] -cne '100644') + } | Sort-Object) + if ($missing.Count -or $unexpected.Count -or $drifted.Count) { + $problems = @() + if ($missing.Count) { $problems += "missing: $($missing -join ', ')" } + if ($drifted.Count) { $problems += "drifted: $($drifted -join ', ')" } + if ($unexpected.Count) { $problems += "unexpected: $($unexpected -join ', ')" } + throw "The trusted files of fixture main at $Main do not match the versioned seed ($($problems -join '; '))." + } +} + function Start-ReleaseFixtureCase { <# .SYNOPSIS @@ -496,6 +599,7 @@ function Start-ReleaseFixtureCase { if ($ExpectedMain -cne '' -and $main -cne $ExpectedMain) { throw "Fixture main at $main must be the expected commit $ExpectedMain." } + Assert-ReleaseFixtureSeed -Main $main -Lane $Lane foreach ($requiredFile in $RequiredPath) { $null = Invoke-ReleaseFixtureRequest -Path "$fixtureApi/contents/${requiredFile}?ref=$main" -TokenVariable $token } @@ -1026,13 +1130,536 @@ function Get-ReleaseFixturePairEvidence { } } +function Get-ReleaseFixtureOpenCase { + <# + .SYNOPSIS + Validate an open fixture pull request and bind it to one exact head commit. + #> + [OutputType([hashtable])] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [ValidatePattern('\A[1-9][0-9]*\z')] + [string] $PullRequest, + + # The head commit the caller approved. Any other head is stale. + [Parameter(Mandatory)] + [ValidatePattern('\A[0-9a-f]{40}\z')] + [string] $ExpectedHead, + + [Parameter()] + [ValidateSet('Candidate', 'Legacy')] + [string] $Lane = 'Candidate', + + # Accept only a missing-decision case, which is closed without a merge. Without it, refuse that case. + [Parameter()] + [switch] $ForClose + ) + + $laneInfo = Get-ReleaseFixtureLane -Name $Lane + $token = $laneInfo.TokenVariable + $api = $laneInfo.Api + $url = "$($laneInfo.Url)/pull/$PullRequest" + $pull = Invoke-ReleaseFixtureRequest -Path "$api/pulls/$PullRequest" -TokenVariable $token + 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 'open' -or $pull.merged -isnot [bool] -or $pull.merged) { + throw "The fixture pull request is not open and unmerged: $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.base.sha -cnotmatch $shaPattern) { + throw "The fixture pull request does not have the expected branch and single commit: $url" + } + if ($pull.head.sha -cne $ExpectedHead) { + throw "The fixture pull request head $($pull.head.sha) is not the approved head $ExpectedHead. See $url" + } + $caseId = $caseRef.Groups[1].Value + $head = $pull.head.sha + $base = $pull.base.sha + $main = Get-ReleaseFixtureMain -RepositoryApi $api -TokenVariable $token + if ($base -cne $main) { + throw "The fixture pull request base $base is stale. Fixture main is $main. See $url" + } + + $path = "tests/cases/$caseId.json" + $commit = Invoke-ReleaseFixtureRequest -Path "$api/commits/$head" -TokenVariable $token + if ($commit.sha -cne $head -or $commit.parents.Count -ne 1 -or $commit.parents[0].sha -cne $base -or + $commit.files.Count -ne 1 -or $commit.files[0].filename -cne $path -or $commit.files[0].status -cne 'added') { + throw "Expected a head commit at $head with parent $base that only adds $path." + } + $payload = Get-ReleaseFixtureJson -Path $path -Commit $head -Lane $Lane + if ($payload.Count -ne 2 -or $payload.candidate -isnot [string] -or $payload.candidate -cnotmatch $shaPattern -or + $payload.scenario -isnot [string] -or $payload.scenario -cnotin $scenarioLabels.Keys) { + throw "The case payload at the fixture pull request head is not valid: $url" + } + if ($payload.scenario -ceq 'missing-decision' -and -not $ForClose) { + throw "The missing-decision case must be closed without merging: $url" + } + if ($payload.scenario -cne 'missing-decision' -and $ForClose) { + throw "Only a missing-decision case may be closed without merging: $url" + } + $label = $scenarioLabels[$payload.scenario] + $label = $scenarioLabels[$payload.scenario] + $labels = @($pull.labels | ForEach-Object { $_['name'] }) + if (($labels -join ' ') -cne $label) { + throw "The fixture pull request labels must be exactly '$label' for the $($payload.scenario) scenario. See $url" + } + $activity = 'opened' + if ($label -cne '') { + $activity = 'labeled' + } + @{ + lane = $Lane + number = $pull.number + url = $url + caseId = $caseId + candidate = $payload.candidate + scenario = $payload.scenario + event = 'pull_request' + activity = $activity + head = $head + base = $base + label = $label + } +} + +function Wait-ReleaseFixtureCheck { + <# + .SYNOPSIS + Wait for the exact head commit's fixture checks. Fail on a failed check or a timeout. + + .DESCRIPTION + A labeled case has two pull request events, opened and labeled. Each event must finish every required check with success. + #> + [OutputType([void])] + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Case, + + [Parameter()] + [double] $TimeoutSeconds = 600, + + [Parameter()] + [double] $PollSeconds = 30 + ) + + $laneInfo = Get-ReleaseFixtureLane -Name ($Case['lane'] ?? 'Candidate') + $expectedSuites = 1 + if ($Case.label -cne '') { + $expectedSuites = 2 + } + $branch = "release-fixture/$($Case.caseId)" + $elapsed = [Diagnostics.Stopwatch]::StartNew() + $missing = @() + do { + # First find the completed Release-Test.yml runs of this exact pull request and head. Their suites are the only trusted suites. + $runsPath = "$($laneInfo.Api)/actions/workflows/$prWorkflowFile/runs?event=pull_request&head_sha=$($Case.head)&per_page=100" + $runsResponse = Invoke-ReleaseFixtureRequest -Path $runsPath -Anonymous + $workflowRuns = $runsResponse['workflow_runs'] + if ($workflowRuns -isnot [array] -or $runsResponse['total_count'] -ne $workflowRuns.Count -or $workflowRuns.Count -gt 100) { + throw "GitHub did not return a complete $prWorkflowFile run list for $($Case.head)." + } + $running = $false + $trustedSuites = @() + foreach ($workflowRun in $workflowRuns) { + $numbers = @($workflowRun['pull_requests'] | ForEach-Object { $_['number'] }) + if ($workflowRun['path'] -cne $prWorkflowPath -or $workflowRun['event'] -cne 'pull_request' -or + $workflowRun['head_sha'] -cne $Case.head -or $workflowRun['head_branch'] -cne $branch -or + $workflowRun['repository']?['id'] -ne $laneInfo.Id -or $workflowRun['head_repository']?['id'] -ne $laneInfo.Id -or + $Case.number -notin $numbers -or $null -eq $workflowRun['check_suite_id']) { + throw "Workflow run $($workflowRun['id']) is not a $prWorkflowFile run for pull request #$($Case.number) at $($Case.head)." + } + if ($workflowRun['status'] -cne 'completed') { + $running = $true + } elseif ($workflowRun['conclusion'] -cne 'success') { + throw "Fixture workflow run $($workflowRun['id']) concluded $($workflowRun['conclusion']). See $($workflowRun['html_url'])" + } else { + $trustedSuites += $workflowRun['check_suite_id'] + } + } + $missing = @() + if ($trustedSuites.Count -lt $expectedSuites) { + $missing = @("$($trustedSuites.Count) of $expectedSuites successful $prWorkflowFile runs") + } + if (-not $running -and $missing.Count -eq 0) { + # Then require the named jobs inside those trusted suites. + $checkPath = "$($laneInfo.Api)/commits/$($Case.head)/check-runs?per_page=100" + $response = Invoke-ReleaseFixtureRequest -Path $checkPath -Anonymous + $runs = $response['check_runs'] + if ($runs -isnot [array] -or $response['total_count'] -ne $runs.Count -or $runs.Count -gt 100) { + throw "GitHub did not return a complete check run list for $($Case.head)." + } + $pending = $false + foreach ($run in $runs) { + if ($run['head_sha'] -cne $Case.head) { + throw "Fixture check '$($run['name'])' belongs to $($run['head_sha']), not the approved head $($Case.head)." + } + if ($run['status'] -cne 'completed') { + $pending = $true + } elseif ($run['conclusion'] -cin $failedConclusions) { + throw "Fixture check '$($run['name'])' concluded $($run['conclusion']) for $($Case.head). See $($run['html_url'])" + } elseif ($run['conclusion'] -cnotin 'success', 'skipped', 'neutral') { + throw "Fixture check '$($run['name'])' has an unexpected conclusion for $($Case.head)." + } + } + # A suite counts only when it is a trusted suite and holds every required job with success. + $complete = 0 + $bySuite = @($runs | Where-Object { $_['app']['id'] -eq $actionsAppId -and $_['check_suite']['id'] -in $trustedSuites } | + Group-Object { $_['check_suite']['id'] }) + foreach ($suite in $bySuite) { + $passed = @($suite.Group | Where-Object { $_['conclusion'] -ceq 'success' } | ForEach-Object { $_['name'] }) + $absent = @($requiredChecks | Where-Object { $_ -cnotin $passed }) + if ($absent.Count -eq 0) { + $complete++ + } else { + $missing += "suite $($suite.Name) lacks $($absent -join ', ')" + } + } + if ($complete -lt $expectedSuites) { + $missing += "$complete of $expectedSuites complete suites" + } else { + $missing = @() + } + $running = $pending + } + if (-not $running -and $missing.Count -eq 0) { + return + } + if ($elapsed.Elapsed.TotalSeconds -lt $TimeoutSeconds) { + Start-Sleep -Milliseconds ([int] (1000 * [Math]::Min($PollSeconds, [Math]::Max(0, $TimeoutSeconds - $elapsed.Elapsed.TotalSeconds)))) + } + } while ($elapsed.Elapsed.TotalSeconds -lt $TimeoutSeconds) + $detail = 'checks are still running' + if (-not $running -and $missing.Count -gt 0) { + $detail = "required successful checks are missing: $($missing -join ', ')" + } + throw "Fixture checks for $($Case.head) did not pass in time: $detail. See $($Case.url)." +} + +function Merge-ReleaseFixtureCase { + <# + .SYNOPSIS + Squash merge an open fixture pull request after its exact head passes the fixture checks. + + .DESCRIPTION + The merge request carries the approved head SHA, so GitHub refuses it if the head moved. The result must be one squash commit + that adds only the case file and has the validated base as its only parent. + #> + [OutputType([hashtable])] + [CmdletBinding(SupportsShouldProcess)] + param( + [Parameter(Mandatory)] + [ValidatePattern('\A[1-9][0-9]*\z')] + [string] $PullRequest, + + [Parameter(Mandatory)] + [ValidatePattern('\A[0-9a-f]{40}\z')] + [string] $ExpectedHead, + + [Parameter()] + [ValidateSet('Candidate', 'Legacy')] + [string] $Lane = 'Candidate', + + [Parameter()] + [double] $TimeoutSeconds = 600, + + [Parameter()] + [double] $PollSeconds = 30 + ) + + $laneInfo = Get-ReleaseFixtureLane -Name $Lane + $case = Get-ReleaseFixtureOpenCase -PullRequest $PullRequest -ExpectedHead $ExpectedHead -Lane $Lane + # The head holds the trusted files that run after the merge. This covers a resumed case as well as a new one. + Assert-ReleaseFixtureSeed -Main $ExpectedHead -Lane $Lane + Wait-ReleaseFixtureCheck -Case $case -TimeoutSeconds $TimeoutSeconds -PollSeconds $PollSeconds + # Read the pull request again so a push or a main change during the wait stops the merge. + $case = Get-ReleaseFixtureOpenCase -PullRequest $PullRequest -ExpectedHead $ExpectedHead -Lane $Lane + if (-not $PSCmdlet.ShouldProcess($case.url, "Squash merge head $ExpectedHead")) { + return + } + $mergePath = "$($laneInfo.Api)/pulls/$PullRequest/merge" + $result = Invoke-ReleaseFixtureRequest -Method PUT -Path $mergePath -TokenVariable $laneInfo.TokenVariable -Body @{ + sha = $ExpectedHead + merge_method = 'squash' + } + if ($result['merged'] -isnot [bool] -or -not $result['merged'] -or $result['sha'] -cnotmatch $shaPattern) { + throw "GitHub did not merge the fixture pull request: $($case.url)" + } + $merged = Get-MergedReleaseFixtureCase -PullRequest $PullRequest -Lane $Lane + if ($merged.source -cne $result['sha'] -or $merged.head -cne $ExpectedHead -or $merged.parent -cne $case.base -or + $merged.caseId -cne $case.caseId -or $merged.candidate -cne $case.candidate -or $merged.scenario -cne $case.scenario) { + throw "The merged fixture pull request does not match the approved case, head, and base: $($case.url)" + } + $merged +} + +function Close-ReleaseFixtureCase { + <# + .SYNOPSIS + Close an open missing-decision fixture pull request without merging it. + + .DESCRIPTION + Validate the same case, head, base, scope, and labels as a merge first. Then send one request that only sets the state to closed. + #> + [OutputType([hashtable])] + [CmdletBinding(SupportsShouldProcess)] + param( + [Parameter(Mandatory)] + [ValidatePattern('\A[1-9][0-9]*\z')] + [string] $PullRequest, + + [Parameter(Mandatory)] + [ValidatePattern('\A[0-9a-f]{40}\z')] + [string] $ExpectedHead + ) + + $laneInfo = Get-ReleaseFixtureLane -Name 'Candidate' + $case = Get-ReleaseFixtureOpenCase -PullRequest $PullRequest -ExpectedHead $ExpectedHead -ForClose + if (-not $PSCmdlet.ShouldProcess($case.url, 'Close without merging')) { + return + } + $result = Invoke-ReleaseFixtureRequest -Method PATCH -Path "$($laneInfo.Api)/pulls/$PullRequest" -TokenVariable $laneInfo.TokenVariable -Body @{ + state = 'closed' + } + if ($result['state'] -cne 'closed' -or $result['merged'] -isnot [bool] -or $result['merged']) { + throw "GitHub did not close the fixture pull request without a merge: $($case.url)" + } + $case +} + +function Invoke-ReleaseFixtureRun { + <# + .SYNOPSIS + Run one ordinary scenario: open the case, verify the open report, then merge it and verify the push report. + + .DESCRIPTION + A missing-decision case has no merge. After the open report is verified, close only that validated pull request. + #> + [OutputType([hashtable])] + [CmdletBinding(SupportsShouldProcess)] + param( + [Parameter(Mandatory)] + [string] $Scenario, + + [Parameter(Mandatory)] + [ValidatePattern('\A[0-9a-f]{40}\z')] + [string] $Candidate, + + [Parameter(Mandatory)] + [ValidatePattern('\A[1-9][0-9]*-[1-9][0-9]*\z')] + [string] $CaseId, + + # Receives one progress line for each completed step. + [Parameter()] + [scriptblock] $Progress = {}, + + [Parameter()] + [double] $TimeoutSeconds = 600, + + [Parameter()] + [double] $PollSeconds = 30 + ) + + if (-not $PSCmdlet.ShouldProcess("Fixture case $CaseId", "Run the $Scenario scenario")) { + return + } + $case = Start-ReleaseFixtureCase -Scenario $Scenario -Candidate $Candidate -CaseId $CaseId -Confirm:$false + Add-ReleaseFixtureLabel -Case $case -Confirm:$false + & $Progress "Opened fixture pull request [#$($case.number)]($($case.url)) at head $($case.head)." + $openReport = Wait-ReleaseFixtureReport -Case $case + & $Progress "Verified open report [$($openReport.run)]($($openReport.run))." + + if ($case.scenario -ceq 'missing-decision') { + $null = Close-ReleaseFixtureCase -PullRequest ([string] $case.number) -ExpectedHead $case.head -Confirm:$false + & $Progress "Closed pull request #$($case.number) without merging." + return @{ case = $case; openReport = $openReport; merged = $null; pushReport = $null } + } + + $merged = Merge-ReleaseFixtureCase -PullRequest ([string] $case.number) -ExpectedHead $case.head -Lane 'Candidate' ` + -TimeoutSeconds $TimeoutSeconds -PollSeconds $PollSeconds -Confirm:$false + & $Progress "Checks passed and squash merged pull request #$($case.number) as $($merged.source)." + $pushReport = Wait-ReleaseFixtureReport -Case $merged + & $Progress "Verified push report [$($pushReport.run)]($($pushReport.run))." + @{ case = $case; openReport = $openReport; merged = $merged; pushReport = $pushReport } +} + +function Invoke-ReleaseFixtureLegacy { + <# + .SYNOPSIS + Finish the legacy lane alone: open or resume the legacy case, merge it after its checks pass, and verify v0.0.1. + + .DESCRIPTION + This needs no candidate. Without LegacyPullRequest, open a new legacy case. With LegacyPullRequest and LegacyHead, resume that + open legacy pull request after validating its exact head, base, payload, labels, and the empty release inventory. Never write + to a resumed pull request before its checks pass. + #> + [OutputType([hashtable])] + [CmdletBinding(SupportsShouldProcess)] + param( + [Parameter(Mandatory)] + [ValidatePattern('\A[1-9][0-9]*-[1-9][0-9]*\z')] + [string] $CaseId, + + [Parameter()] + [AllowEmptyString()] + [ValidatePattern('\A(?:[1-9][0-9]*)?\z')] + [string] $LegacyPullRequest = '', + + [Parameter()] + [AllowEmptyString()] + [ValidatePattern('\A(?:[0-9a-f]{40})?\z')] + [string] $LegacyHead = '', + + # Receives one progress line for each completed step. + [Parameter()] + [scriptblock] $Progress = {}, + + [Parameter()] + [double] $TimeoutSeconds = 600, + + [Parameter()] + [double] $PollSeconds = 30 + ) + + if (($LegacyPullRequest -ceq '') -ne ($LegacyHead -ceq '')) { + throw 'Supply both the legacy pull request number and its exact head SHA to resume, or neither to start a new legacy case.' + } + if (-not $PSCmdlet.ShouldProcess('Fixture repository', 'Run the legacy lane')) { + return + } + + if ($LegacyPullRequest -ceq '') { + $legacyOpen = Start-ReleaseFixtureLegacyCase -CaseId $CaseId -Confirm:$false + Add-ReleaseFixtureLabel -Case $legacyOpen -Confirm:$false + $LegacyPullRequest = [string] $legacyOpen.number + $LegacyHead = $legacyOpen.head + & $Progress "Opened legacy fixture pull request [#$LegacyPullRequest]($($legacyOpen.url)) at head $LegacyHead." + } else { + $legacyOpen = Get-ReleaseFixtureOpenCase -PullRequest $LegacyPullRequest -ExpectedHead $LegacyHead -Lane 'Legacy' + if ($legacyOpen.scenario -cne 'one-step' -or $legacyOpen.candidate -cne $legacyBaseline) { + throw "The legacy case must use the one-step scenario with the pinned baseline $legacyBaseline. See $($legacyOpen.url)." + } + Assert-ReleaseFixtureRepository -Lane 'Legacy' + Assert-ReleaseFixtureEmptyInventory -Lane 'Legacy' + foreach ($open in (Invoke-ReleaseFixtureRequest -Path "$fixtureApi/pulls?state=open" -Paged)) { + if ($open.head.ref -clike 'release-fixture/*' -and $open.number -ne $legacyOpen.number -and + (Test-ReleaseFixturePullRequest -PullRequest $open)) { + throw "Fixture pull request #$($open.number) is also open. Finish or close it before the pair runs." + } + } + & $Progress "Resumed legacy fixture pull request [#$LegacyPullRequest]($($legacyOpen.url)) at head $LegacyHead." + } + + $merged = Merge-ReleaseFixtureCase -PullRequest $LegacyPullRequest -ExpectedHead $LegacyHead -Lane 'Legacy' ` + -TimeoutSeconds $TimeoutSeconds -PollSeconds $PollSeconds -Confirm:$false + & $Progress "Checks passed and squash merged legacy pull request #$LegacyPullRequest as $($merged.source)." + $report = Wait-ReleaseFixtureReport -Case $merged + $evidence = Get-ReleaseFixtureLegacyEvidence -PullRequest $LegacyPullRequest + & $Progress "Verified legacy bot report [$($report.run)]($($report.run)) and tag $($report.tag)." + $evidence +} + +function Invoke-ReleaseFixturePair { + <# + .SYNOPSIS + Run the whole baseline-first pair: legacy, then candidate, with fixture merges and bot report checks. + + .DESCRIPTION + Without LegacyPullRequest, open a new legacy case. With LegacyPullRequest and LegacyHead, resume that open legacy pull request + after validating its exact head, base, payload, labels, and the empty release inventory. Never write to a resumed pull request + before its checks pass. + #> + [OutputType([hashtable])] + [CmdletBinding(SupportsShouldProcess)] + param( + [Parameter(Mandatory)] + [ValidatePattern('\A[0-9a-f]{40}\z')] + [string] $Candidate, + + [Parameter(Mandatory)] + [ValidatePattern('\A[1-9][0-9]*-[1-9][0-9]*\z')] + [string] $LegacyCaseId, + + [Parameter(Mandatory)] + [ValidatePattern('\A[1-9][0-9]*-[1-9][0-9]*\z')] + [string] $CandidateCaseId, + + [Parameter()] + [AllowEmptyString()] + [ValidatePattern('\A(?:[1-9][0-9]*)?\z')] + [string] $LegacyPullRequest = '', + + [Parameter()] + [AllowEmptyString()] + [ValidatePattern('\A(?:[0-9a-f]{40})?\z')] + [string] $LegacyHead = '', + + # Receives one progress line for each completed step. + [Parameter()] + [scriptblock] $Progress = {}, + + [Parameter()] + [double] $TimeoutSeconds = 600, + + [Parameter()] + [double] $PollSeconds = 30 + ) + + if ($LegacyPullRequest -ceq '' -and $LegacyHead -cne '') { + throw 'A legacy head SHA needs the legacy pull request number.' + } + if (-not $PSCmdlet.ShouldProcess('Fixture repository', 'Run the baseline-first pair')) { + return + } + $wait = @{ TimeoutSeconds = $TimeoutSeconds; PollSeconds = $PollSeconds } + + if ($LegacyPullRequest -cne '' -and $LegacyHead -ceq '') { + # The legacy pull request is already merged. Verify it exactly and continue without a second merge. + $legacy = Get-ReleaseFixtureLegacyEvidence -PullRequest $LegacyPullRequest + & $Progress "Continued from verified merged legacy pull request #$LegacyPullRequest ($($legacy.case.source)), tag $($legacy.report.tag)." + } else { + $legacyParameters = @{ + CaseId = $LegacyCaseId + LegacyPullRequest = $LegacyPullRequest + LegacyHead = $LegacyHead + Progress = $Progress + } + $legacy = Invoke-ReleaseFixtureLegacy @legacyParameters @wait -Confirm:$false + $LegacyPullRequest = [string] $legacy.case.number + } + + $candidateOpen = Start-ReleaseFixturePairCandidate -LegacyPullRequest $LegacyPullRequest -Candidate $Candidate ` + -CaseId $CandidateCaseId -Confirm:$false + Add-ReleaseFixtureLabel -Case $candidateOpen -Confirm:$false + $candidatePullRequest = [string] $candidateOpen.number + & $Progress "Opened candidate fixture pull request [#$candidatePullRequest]($($candidateOpen.url)) at head $($candidateOpen.head)." + $openReport = Wait-ReleaseFixtureReport -Case $candidateOpen + & $Progress "Verified candidate open report [$($openReport.run)]($($openReport.run))." + $null = Merge-ReleaseFixtureCase -PullRequest $candidatePullRequest -ExpectedHead $candidateOpen.head -Lane 'Candidate' @wait -Confirm:$false + & $Progress "Checks passed and squash merged candidate pull request #$candidatePullRequest." + + Get-ReleaseFixturePairEvidence -LegacyPullRequest $LegacyPullRequest -CandidatePullRequest $candidatePullRequest +} + Export-ModuleMember -Function @( + 'Get-ReleaseFixtureOpenCase' + 'Close-ReleaseFixtureCase' + 'Invoke-ReleaseFixtureRun' + 'Wait-ReleaseFixtureCheck' + 'Merge-ReleaseFixtureCase' + 'Invoke-ReleaseFixturePair' + 'Invoke-ReleaseFixtureLegacy' + 'Get-ReleaseFixtureLegacyEvidence' 'Start-ReleaseFixtureLegacyCase' 'Start-ReleaseFixturePairCandidate' 'Get-ReleaseFixturePairEvidence' 'Compare-ReleaseFixturePair' 'Resolve-ReleaseFixtureCandidate' 'Start-ReleaseFixtureCase' + 'Assert-ReleaseFixtureSeed' 'Add-ReleaseFixtureLabel' 'Get-MergedReleaseFixtureCase' 'Find-ReleaseFixtureReport' diff --git a/.github/workflows/Fixture-Driver-Test.yml b/.github/workflows/Fixture-Driver-Test.yml index e41ebaa..efaf015 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, ./tests/ReleaseFixturePair.Tests.ps1 + run: Invoke-Pester -CI -Path ./tests/ReleaseFixture.Tests.ps1, ./tests/ReleaseFixturePair.Tests.ps1, ./tests/ReleaseFixtureMerge.Tests.ps1 diff --git a/.github/workflows/Fixture-Pair-Test.yml b/.github/workflows/Fixture-Pair-Test.yml index 593d419..aa6c9c2 100644 --- a/.github/workflows/Fixture-Pair-Test.yml +++ b/.github/workflows/Fixture-Pair-Test.yml @@ -5,18 +5,23 @@ on: # 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) + description: Pair step (run-pair does everything; run-legacy finishes only the before result; the others are manual steps for the same pair) type: choice - default: start-legacy + default: run-pair options: + - run-pair + - run-legacy - start-legacy - start-candidate - compare candidate_pr: - description: Open producer pull request number to test (start-candidate only) + description: Open producer pull request number to test (run-pair and start-candidate) type: string legacy_pr: - description: Merged legacy fixture pull request number (start-candidate and compare) + description: Legacy fixture pull request number (open for resume with legacy_head; merged for run-pair, start-candidate, and compare) + type: string + legacy_head: + description: Exact head SHA of the open legacy fixture pull request (run-pair and run-legacy resume only, with legacy_pr) type: string candidate_fixture_pr: description: Merged candidate fixture pull request number (compare only) @@ -34,6 +39,125 @@ defaults: shell: pwsh jobs: + RunPair: + name: Run the whole pair with fixture merges + if: >- + github.event_name == 'workflow_dispatch' && + github.repository == 'PSModule/Release-GHRepository' && + github.ref == 'refs/heads/main' && + inputs.step == 'run-pair' + runs-on: ubuntu-24.04 + timeout-minutes: 50 + 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 }} + LEGACY_HEAD: ${{ inputs.legacy_head }} + 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:CANDIDATE_FIXTURE_PR) { + throw 'Supply the producer pull request number. Do not supply a candidate fixture pull request number.' + } + if ($env:LEGACY_HEAD -and -not $env:LEGACY_PR) { + throw 'A legacy head SHA needs the legacy pull request number.' + } + if ($env:LEGACY_PR -cnotmatch '\A(?:[1-9][0-9]*)?\z' -or $env:LEGACY_HEAD -cnotmatch '\A(?:[0-9a-f]{40})?\z') { + throw 'The legacy pull request must be a number and the head must be a full lowercase SHA.' + } + + - 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, test, merge, and verify both cases, then compare them + env: + GH_TOKEN: ${{ steps.fixture-token.outputs.token }} + CANDIDATE_SHA: ${{ steps.candidate.outputs.sha }} + LEGACY_PR: ${{ inputs.legacy_pr }} + LEGACY_HEAD: ${{ inputs.legacy_head }} + run: ./.github/scripts/Invoke-ReleaseFixture.ps1 -Mode RunPair -Candidate $env:CANDIDATE_SHA -LegacyPullRequest $env:LEGACY_PR -LegacyHead $env:LEGACY_HEAD + RunLegacy: + name: Finish the legacy baseline without a candidate + if: >- + github.event_name == 'workflow_dispatch' && + github.repository == 'PSModule/Release-GHRepository' && + github.ref == 'refs/heads/main' && + inputs.step == 'run-legacy' + runs-on: ubuntu-24.04 + timeout-minutes: 30 + permissions: + contents: read + steps: + - name: Confirm the exact repository, ref, and inputs + env: + CANDIDATE_PR: ${{ inputs.candidate_pr }} + LEGACY_PR: ${{ inputs.legacy_pr }} + LEGACY_HEAD: ${{ inputs.legacy_head }} + 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:CANDIDATE_FIXTURE_PR) { + throw 'The run-legacy step takes no candidate input.' + } + if ([bool] $env:LEGACY_PR -ne [bool] $env:LEGACY_HEAD) { + throw 'To resume, supply both the open legacy pull request number and its exact head SHA. Otherwise supply neither.' + } + if ($env:LEGACY_PR -and ($env:LEGACY_PR -cnotmatch '\A[1-9][0-9]*\z' -or $env:LEGACY_HEAD -cnotmatch '\A[0-9a-f]{40}\z')) { + throw 'The legacy pull request must be a number and the head must be a full lowercase SHA.' + } + + - 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 or resume, test, merge, and verify the legacy case + env: + GH_TOKEN: ${{ steps.fixture-token.outputs.token }} + LEGACY_PR: ${{ inputs.legacy_pr }} + LEGACY_HEAD: ${{ inputs.legacy_head }} + run: ./.github/scripts/Invoke-ReleaseFixture.ps1 -Mode RunLegacy -LegacyPullRequest $env:LEGACY_PR -LegacyHead $env:LEGACY_HEAD StartLegacy: name: Open the legacy baseline pull request if: >- @@ -51,11 +175,12 @@ jobs: CANDIDATE_PR: ${{ inputs.candidate_pr }} LEGACY_PR: ${{ inputs.legacy_pr }} CANDIDATE_FIXTURE_PR: ${{ inputs.candidate_fixture_pr }} + LEGACY_HEAD: ${{ inputs.legacy_head }} 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) { + if ($env:CANDIDATE_PR -or $env:LEGACY_PR -or $env:CANDIDATE_FIXTURE_PR -or $env:LEGACY_HEAD) { throw 'The start-legacy step takes no pull request inputs.' } @@ -99,12 +224,13 @@ jobs: CANDIDATE_PR: ${{ inputs.candidate_pr }} LEGACY_PR: ${{ inputs.legacy_pr }} CANDIDATE_FIXTURE_PR: ${{ inputs.candidate_fixture_pr }} + LEGACY_HEAD: ${{ inputs.legacy_head }} 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) { + $env:CANDIDATE_FIXTURE_PR -or $env:LEGACY_HEAD) { throw 'Supply the producer pull request number and the merged legacy pull request number only.' } @@ -156,12 +282,13 @@ jobs: CANDIDATE_PR: ${{ inputs.candidate_pr }} LEGACY_PR: ${{ inputs.legacy_pr }} CANDIDATE_FIXTURE_PR: ${{ inputs.candidate_fixture_pr }} + LEGACY_HEAD: ${{ inputs.legacy_head }} 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) { + $env:CANDIDATE_PR -or $env:LEGACY_HEAD) { throw 'Supply only the merged legacy and candidate fixture pull request numbers.' } diff --git a/.github/workflows/Fixture-Test.yml b/.github/workflows/Fixture-Test.yml index e444536..7ce2cee 100644 --- a/.github/workflows/Fixture-Test.yml +++ b/.github/workflows/Fixture-Test.yml @@ -5,7 +5,7 @@ on: # 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) + description: Scenario to run (ignored for verification) type: choice default: preview options: @@ -20,7 +20,7 @@ on: 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) + description: Merged fixture pull request number (recovery only; verifies the push instead of running a case) type: string permissions: {} @@ -34,15 +34,16 @@ defaults: shell: pwsh jobs: - Start: - name: Open and verify a fixture pull request + Run: + name: Run a scenario and verify its reports 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 + # Up to ten minutes each for the open report, the fixture checks, and the push report. + timeout-minutes: 40 permissions: contents: read pull-requests: read @@ -77,12 +78,12 @@ jobs: permission-contents: write permission-pull-requests: write - - name: Start the case and verify the pull request report + - name: Run the case, merge it with the fixture token, and verify both reports 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 + run: ./.github/scripts/Invoke-ReleaseFixture.ps1 -Mode Run -Scenario $env:SCENARIO -Candidate $env:CANDIDATE_SHA Verify: name: Verify the fixture push report diff --git a/.github/workflows/Linter.yml b/.github/workflows/Linter.yml index 68ffc08..ce93ada 100644 --- a/.github/workflows/Linter.yml +++ b/.github/workflows/Linter.yml @@ -28,6 +28,8 @@ jobs: uses: super-linter/super-linter@4ce20838b8ab83717e78138c5b3a1407148e0918 # v8.7.0 env: GITHUB_TOKEN: ${{ github.token }} + # The fixture seed is an exact copy of fixture files. Linting must not require changes to it. + FILTER_REGEX_EXCLUDE: .*/fixtures/release-fixture/seed/.* VALIDATE_BIOME_FORMAT: false VALIDATE_JSCPD: false VALIDATE_JSON_PRETTIER: false diff --git a/docs/Fixture-Acceptance-Spec.md b/docs/Fixture-Acceptance-Spec.md new file mode 100644 index 0000000..6a25f9f --- /dev/null +++ b/docs/Fixture-Acceptance-Spec.md @@ -0,0 +1,46 @@ +# Fixture test acceptance specification + +Status: intent record. This document states the goal. It does not claim that the current workflows meet it. +For the current implementation, see [Fixture-Test.md](Fixture-Test.md). + +## Intent + +A contribution to this repository must prove that the action works. The proof comes from real runs against a real test +repository. It must not use mocks. One commit on a pull request must be enough to start it. No person takes any +action for each run. + +## Requirements + +1. **Automatic start.** A pull request commit starts the verification. The exact producer commit SHA is the code under test. +2. **Isolation and initial state.** The tests run in a test repository that is separate from production. Before each run, + the harness checks that this repository is in the expected clean state, and it fails if it is not. +3. **Case matrix.** A fixed, deterministic set of scenarios runs. Each scenario uses real GitHub pull request events and + real default-branch events. A case that must publish creates a real release and tag. A case that must not publish + (for example, `preview`, `skip`, or a failure case) has an explicit assertion that no release or tag changed. +4. **Evidence.** Each case produces its own outcome evidence. A source other than the candidate code checks that evidence. + The evidence is bound to the producer SHA, the case, and the pull request head. For a publish path, it is also bound + to the tested squash commit and the tag target. +5. **No per-run approval.** No person approves or merges a test repository pull request for a run. +6. **Secret and write boundaries.** Only the trusted harness does provisioning, fixture setup, pull request + orchestration, cleanup, and evidence checks. Candidate jobs never receive provisioning credentials and cannot write to + production. A candidate job may publish releases and tags only in its own isolated fixture, with a least-privilege token + scoped to that fixture. +7. **Visible failure.** Stale, missing, failed, or timed-out evidence fails the run. +8. **Producer-owned fixtures.** This repository owns the versioned fixture seeds, scenario definitions, and expected + results. Tests use an exact trusted revision of them. + +## Design decision + +The lifecycle is a static test repository, `PSModule/Release-GHRepository-Test`, with the fixed repository ID. The harness +checks the repository and its trusted files before it writes. A fresh or template repository, several fixtures, or several +repositories remain possible later. Any design must meet requirements 1 to 8. + +## Status of the static design + +These three items are different. Do not treat one as proof of another. + +| Item | Meaning | Status | +| --- | --- | --- | +| Seed ownership | This repository holds the versioned trusted fixture files in `fixtures/release-fixture/seed`. The write path fails if fixture `main` differs from them. | Implemented as a preflight. It checks the seed. It does not copy the seed to the fixture. | +| One-time authorization | An organization owner must replace the inherited ruleset for the fixture only, so the Shelly App can merge fixture pull requests without a person. | Not done. No workflow can do it. | +| Automatic repeatable matrix | One producer commit runs the whole case matrix, in order, with cleanup between cases. | Missing. Today a maintainer dispatches one scenario. | diff --git a/docs/Fixture-Test.md b/docs/Fixture-Test.md index bbb6ade..2724331 100644 --- a/docs/Fixture-Test.md +++ b/docs/Fixture-Test.md @@ -1,24 +1,68 @@ # Test a release candidate in the fixture repository +The goal of this harness is in the [fixture acceptance specification](Fixture-Acceptance-Spec.md). This guide describes the +current implementation, which does not yet meet that specification. + +Rollout order: + +1. Prove the current published action against real GitHub fixtures. +2. Land the harness independently, before #109. +3. Adapt the fixture matrix, and test the exact #109 candidate. Do not weaken the legacy assertions. + +## Trusted fixture seed + +This repository owns the trusted fixture files in `fixtures/release-fixture/seed`. They are the workflows, the scenario +contract, and the runner, oracle, and baseline scripts with their tests. The seed is the exact content of fixture `main` at +`d1a37576ffdb4be89cc183df6a5700d3e2769d9c`. Runtime case data (`tests/cases/`) and other files, such as the README, are not +part of the seed. + +Before it writes a case, the driver reads the file list of fixture `main` and compares each trusted file (`.github/workflows/`, +`tests/`, and `tests-baseline/`, except `tests/cases/`) with the seed by git blob SHA. A missing, changed, or extra file fails the +run before any write. The check uses the seed in the producer commit that runs the workflow. The preflight reads and does not +repair the fixture. To change a trusted fixture file, change the seed in a producer pull request, and then update the fixture +`main` to match it. The merge of an open case, including the resume of a legacy case, runs the same check on the case head before +it merges, so a resumed case with changed trusted files is refused. Path matching is case-sensitive and includes hidden paths. + +The seed files keep their exact bytes (`-text -whitespace` in `.gitattributes`). Do not reformat them. + +Maintenance check: `Assert-ReleaseFixtureSeed -Main ` with a read token prints nothing when the files match. + +The `Run`, `RunPair`, and `RunLegacy` modes need this authorization first. See the [acceptance specification](Fixture-Acceptance-Spec.md) +for the difference between seed ownership, the one-time authorization, and the missing automatic matrix. + 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 | +| Input | Run a case | Verify a push (recovery) | | --- | --- | --- | | `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 | +| `candidate_pr` | Number of an open pull request from this repository to `main`. Omit it to test the dispatched producer `main`, if it 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` +`Mode`, `DefaultBump`, `ReleasePlan`, and `WhatIf` inputs and the `Decision`, `BumpSource`, `ReleasePlan`, and `ReleaseVersion` 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. +One dispatch runs one scenario from start to finish. No person approves or merges a fixture pull request. The job uses the +fixture-only Shelly token. Candidate code never receives this token, and the App never approves its own pull request. + +1. The driver opens a fixture pull request for the exact candidate SHA, adds the scenario label, and links the pull request in the job + summary. It waits up to ten minutes for the open report: the `labeled` event, or the `opened` event if the case has no label. +2. For every scenario except `missing-decision`, the driver waits for the fixture checks of the exact head (see the check rules in + the pair section), and then squash merges with the merge API bound to that head SHA. The merge result must be one squash commit that + adds only the case file. It then waits up to ten minutes for the push report for the exact squash commit and checks the bot's + verification and oracle results, not the overall workflow status. The `ci-failure`, `skip`, and `preview` scenarios use the same flow. + Their reports must have `tag: null`. +3. For `missing-decision`, the driver verifies the open report and then closes only that validated pull request without a merge. + +If a run stops after the merge (for example, a timeout while it waits for the push report), dispatch again with `fixture_pr`. The driver +uses a read-only token and links the final run for the exact squash commit. Do not use this recovery path for any other purpose. + +The job fails visibly if the checks are stale, failed, cancelled, timed out, or missing, or if the head changed. It then leaves the open +fixture pull request for inspection. Close it, or fix the cause and finish it, before you start another case. +Fixture Test does not run all scenarios in one dispatch and has no push trigger. + +The prerequisite from the pair section applies: an organization owner must give the Shelly App the pull-request-only bypass first. The `staged`, `one-step`, and `configured-default` push reports must include a stable tag. All other reports must use `tag: null`. @@ -57,8 +101,53 @@ Minimum setup: - 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. +### Run the whole pair automatically (`run-pair`, default) + +`run-pair` does the full comparison in one job. No person approves or merges a fixture pull request. The job uses the fixture-only +Shelly token. Candidate code never receives this token, and the App never approves its own pull request. + +For each lane, the driver does these steps: + +1. It opens the fixture pull request for the exact case. For the candidate lane, the producer SHA comes from the explicit + `candidate_pr` number (an open pull request from this repository). +2. It waits up to the timeout for the fixture checks of the exact head. The reads are unauthenticated and GET-only. They are limited + to one fixture commit: the runs of `Release-Test.yml` for the event `pull_request`, and the check runs. Only `Release-Test.yml` + runs count (the legacy workflow runs only on closed). Each accepted run must be complete with success, and must match the exact + workflow path, event, head SHA, case branch, fixture repository (as base and head), and pull request number. Any other run for that + head fails the job. The driver then reads the check runs, checks that every one has the exact head SHA, and groups the required jobs + `Select the case and record the inventory` and `Test the exact commit` by check suite. A suite counts only if it is one of the + accepted suites and has both jobs, from the Actions app, with success. A labeled case needs two such suites. +3. It squash merges with the merge API bound to the exact head SHA. GitHub rejects the call if the head changed. +4. It verifies the squash (one parent, one added case file) and the bot report, oracle, and inventory. + +The job fails visibly if the pull request, case, head, or scope is not the expected one, or if a check is stale, failed, cancelled, +timed out, or missing. A failed job leaves the fixture pull request open for inspection. The pinned `v2.0.3` SHA is not changed. + +To resume the already-open legacy fixture pull request, set `legacy_pr` and `legacy_head` together. For fixture pull request 6, use +`legacy_pr=6` and `legacy_head=0fa1d098056ee2988386d18f4e5e740da98c4139`. The driver then checks that the pull request is open, is +by Shelly, has this head, and sits on the current fixture `main` (`d1a37576ffdb4be89cc183df6a5700d3e2769d9c`). It also checks that +the head adds only its case file with the `v2.0.3` pin and the `release:patch` label, that the inventory is empty, and that no other +fixture pull request is open. The resume does not change the pull request until all checks pass. + +One-time prerequisites (an organization owner must do these; no workflow can): + +- Replace the inherited GitHub Flow ruleset (ID `19735208`) for `Release-GHRepository-Test` only. Use equivalent protection with the + Shelly App (App ID `4528702`) as a bypass actor for pull requests only. + +The Shelly App needs no `Checks` permission. Do not add it. The unauthenticated read has the GitHub limit of 60 requests each hour for each runner IP address. The driver polls every 30 seconds, and one poll uses one request while a run is still pending (two when the runs are complete). A wait of ten minutes therefore uses at most about 40 requests. Each process also stops itself after 50 unauthenticated requests, which is the budget for both lanes of one job. If GitHub refuses the read, the job fails. + +### Get the before result first (`run-legacy`) + +`run-legacy` needs no candidate input. It opens a new legacy case, or resumes the open legacy pull request when you set `legacy_pr` and `legacy_head` together. It waits for the checks, squash merges with the head-bound merge, and verifies the bot report and the tag `v0.0.1`. It uses the same code as `run-pair` and needs the same token and prerequisites. + +To finish the pair later, run `run-pair` with `candidate_pr` and `legacy_pr` only (no `legacy_head`). The driver verifies the merged legacy case with the same exact checks (head, one-file squash, report, tag, release target, and unchanged fixture `main`). It does not merge the legacy case again. A merged case with a different state fails the job. + +Step-by-step modes remain available when the steps below are selected. + | Step | Inputs | Result | | --- | --- | --- | +| `run-pair` | `candidate_pr`; optional `legacy_pr` with `legacy_head` (resume an open case) or alone (continue from a merged case) | Runs both lanes, merges, verifies, and compares. | +| `run-legacy` | Optional `legacy_pr` with `legacy_head` | Finishes only the legacy lane. | | `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. | @@ -96,7 +185,7 @@ with that inventory. 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, ./tests/ReleaseFixturePair.Tests.ps1 +Invoke-Pester -Path ./tests/ReleaseFixture.Tests.ps1, ./tests/ReleaseFixturePair.Tests.ps1, ./tests/ReleaseFixtureMerge.Tests.ps1 ``` These tests substitute the driver's REST boundary. They do not use credentials or exercise the live fixture workflows. diff --git a/fixtures/release-fixture/seed/.github/workflows/Legacy-Baseline.yml b/fixtures/release-fixture/seed/.github/workflows/Legacy-Baseline.yml new file mode 100644 index 0000000..12eeefd --- /dev/null +++ b/fixtures/release-fixture/seed/.github/workflows/Legacy-Baseline.yml @@ -0,0 +1,121 @@ +name: Legacy baseline + +on: + pull_request: + branches: [main, 'integration/**'] + paths: + - '.github/workflows/Legacy-Baseline.yml' + - '.github/workflows/Legacy-Release-Test.yml' + - 'tests-baseline/**' + - 'tests/LegacyCase.psm1' + - 'tests/LegacyCase.Tests.ps1' + - 'tests/Invoke-LegacyFixture.ps1' + - 'tests/ReleaseInventory.psm1' + +permissions: {} + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + LEGACY_ACTION_SHA: 750abed0ecab02394554b610dc3aa191e75e3248 # PSModule/Release-GHRepository v2.0.3 + +jobs: + Simulated: + name: Run the pinned v2.0.3 logic against doubles + runs-on: ubuntu-24.04 + permissions: + contents: read + steps: + - name: Check out the fixture + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + persist-credentials: false + + - name: Check out the pinned legacy action + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + repository: PSModule/Release-GHRepository + ref: ${{ env.LEGACY_ACTION_SHA }} + path: .release-action + persist-credentials: false + + - name: Install the modules the action uses + shell: pwsh + run: | + Install-PSResource -Name GitHub, PSSemVer, powershell-yaml -Repository PSGallery -TrustRepository + Get-Module GitHub, PSSemVer, powershell-yaml -ListAvailable | Format-Table Name, Version + + - name: Test the baseline scenarios + uses: PSModule/Invoke-Pester@4ff33199141fdf22568990b6107fe3148ae93a1c # v5.1.0 + env: + LEGACY_ACTION_PATH: ${{ github.workspace }}/.release-action + with: + Path: tests-baseline + Version: 6.1.0 + + - name: Test the legacy lane guard and verdict + shell: pwsh + run: | + Install-PSResource -Name Pester -Version 6.1.0 -Repository PSGallery -TrustRepository + Import-Module Pester -RequiredVersion 6.1.0 + $result = Invoke-Pester -Path tests/LegacyCase.Tests.ps1 -Output Detailed -PassThru + if ($result.FailedCount -gt 0 -or $result.TotalCount -eq 0) { throw 'The lane tests failed.' } + + WhatIf: + name: Run the real composite in WhatIf mode with a read-only token + runs-on: ubuntu-24.04 + permissions: + contents: read + steps: + - name: Check out the fixture + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + persist-credentials: false + + - name: Check out the pinned legacy action + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + repository: PSModule/Release-GHRepository + ref: ${{ env.LEGACY_ACTION_SHA }} + path: .release-action + persist-credentials: false + + - name: Record the release and tag inventory + id: before + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + run: | + $releases = gh api --paginate "repos/$env:GITHUB_REPOSITORY/releases" --jq '.[] | "\(.id) \(.tag_name)"' + if ($LASTEXITCODE -ne 0) { throw 'The release read failed.' } + $tags = gh api --paginate "repos/$env:GITHUB_REPOSITORY/tags" --jq '.[] | "\(.name) \(.commit.sha)"' + if ($LASTEXITCODE -ne 0) { throw 'The tag read failed.' } + $state = @($releases) + @($tags) -join ';' + Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value "state=$state" + + - name: Preview with the legacy inputs + uses: ./.release-action + env: + GH_TOKEN: ${{ github.token }} + with: + AutoPatching: 'false' + AutoCleanup: 'false' + CreateMajorTag: 'false' + CreateMinorTag: 'false' + PatchLabels: release:patch + WhatIf: 'true' + + - name: Confirm the preview wrote nothing + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + BEFORE: ${{ steps.before.outputs.state }} + run: | + $releases = gh api --paginate "repos/$env:GITHUB_REPOSITORY/releases" --jq '.[] | "\(.id) \(.tag_name)"' + if ($LASTEXITCODE -ne 0) { throw 'The release read failed.' } + $tags = gh api --paginate "repos/$env:GITHUB_REPOSITORY/tags" --jq '.[] | "\(.name) \(.commit.sha)"' + if ($LASTEXITCODE -ne 0) { throw 'The tag read failed.' } + $state = @($releases) + @($tags) -join ';' + if ($state -cne $env:BEFORE) { throw 'The WhatIf preview changed the release or tag inventory.' } diff --git a/fixtures/release-fixture/seed/.github/workflows/Legacy-Release-Test.yml b/fixtures/release-fixture/seed/.github/workflows/Legacy-Release-Test.yml new file mode 100644 index 0000000..cc3390f --- /dev/null +++ b/fixtures/release-fixture/seed/.github/workflows/Legacy-Release-Test.yml @@ -0,0 +1,176 @@ +name: Legacy release integration + +on: + pull_request: + branches: [main] + types: [closed] + +permissions: {} + +concurrency: + group: Release-GHRepository-Test + queue: max + +jobs: + Select: + name: Verify the merged legacy case + if: >- + ${{ github.repository == 'PSModule/Release-GHRepository-Test' + && github.repository_id == '1477027955' + && github.event_name == 'pull_request' && github.event.action == 'closed' + && github.event.pull_request.merged == true && github.event.pull_request.base.ref == 'main' + && github.event.pull_request.head.repo.id == github.event.pull_request.base.repo.id + && github.event.pull_request.head.repo.full_name == github.repository + && github.event.pull_request.base.repo.full_name == github.repository + && github.event.pull_request.user.id == 314722336 + && github.event.pull_request.user.login == 'psmodule-s-shelly[bot]' + && startsWith(github.event.pull_request.head.ref, 'release-fixture/') }} + runs-on: ubuntu-24.04 + permissions: + contents: read + pull-requests: read + outputs: + caseId: ${{ steps.fixture.outputs.caseId }} + candidate: ${{ steps.fixture.outputs.candidate }} + scenario: ${{ steps.fixture.outputs.scenario }} + pullRequest: ${{ steps.fixture.outputs.pullRequest }} + head: ${{ steps.fixture.outputs.head }} + source: ${{ steps.fixture.outputs.source }} + steps: + - name: Check out the exact squash commit + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ github.event.pull_request.merge_commit_sha }} + persist-credentials: false + + - name: Verify the case, squash commit, and author + id: fixture + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + run: ./tests/Invoke-LegacyFixture.ps1 -Stage Select + + CI: + name: Test the exact squash commit + needs: Select + if: ${{ needs.Select.outputs.caseId != '' }} + runs-on: ubuntu-24.04 + permissions: + contents: read + outputs: + testedSha: ${{ steps.source.outputs.sha }} + steps: + - name: Check out the exact squash commit + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ needs.Select.outputs.source }} + persist-credentials: false + + - name: Test case selection and inventory assertions + uses: PSModule/Invoke-Pester@4ff33199141fdf22568990b6107fe3148ae93a1c # v5.1.0 + with: + Path: tests + Version: 6.1.0 + + - name: Record the tested SHA + id: source + shell: pwsh + env: + SOURCE: ${{ needs.Select.outputs.source }} + run: | + $sha = git rev-parse HEAD + if ($LASTEXITCODE -ne 0 -or $sha -cne $env:SOURCE) { + throw 'CI did not test the squash commit.' + } + Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value "sha=$sha" + + Gate: + name: Require current main and calculate the expected tag + needs: [Select, CI] + if: ${{ needs.Select.outputs.caseId != '' && needs.CI.outputs.testedSha == needs.Select.outputs.source }} + runs-on: ubuntu-24.04 + permissions: + contents: read + outputs: + before: ${{ steps.gate.outputs.before }} + expectedTag: ${{ steps.gate.outputs.expectedTag }} + steps: + - name: Check out the exact squash commit + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ needs.Select.outputs.source }} + persist-credentials: false + + - name: Check main and calculate the expected tag + id: gate + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + FIXTURE_SOURCE: ${{ needs.Select.outputs.source }} + run: ./tests/Invoke-LegacyFixture.ps1 -Stage Gate + + Publish: + name: Publish the legacy release + needs: [Select, CI, Gate] + if: ${{ needs.Gate.result == 'success' }} + runs-on: ubuntu-24.04 + permissions: + contents: write + steps: + # The action runs git push origin --tags. Git needs the job token even when no local tag exists. + - name: Check out the exact squash commit with the job token + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ needs.Select.outputs.source }} + persist-credentials: true + + - name: Check main and the expected tag again + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + FIXTURE_SOURCE: ${{ needs.Select.outputs.source }} + run: ./tests/Invoke-LegacyFixture.ps1 -Stage Gate + + - name: Publish with the published legacy action + uses: PSModule/Release-GHRepository@750abed0ecab02394554b610dc3aa191e75e3248 # v2.0.3 + env: + GH_TOKEN: ${{ github.token }} + with: + AutoPatching: 'false' + AutoCleanup: 'false' + CreateMajorTag: 'false' + CreateMinorTag: 'false' + PatchLabels: release:patch + WhatIf: 'false' + + Verify: + name: Verify the fixture result + needs: [Select, CI, Gate, Publish] + if: ${{ !cancelled() && needs.Select.result == 'success' && needs.Select.outputs.caseId != '' }} + runs-on: ubuntu-24.04 + permissions: + contents: read + pull-requests: write + steps: + - name: Check out the exact squash commit + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ needs.Select.outputs.source }} + persist-credentials: false + + - name: Verify and report the case + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + FIXTURE_CASE_ID: ${{ needs.Select.outputs.caseId }} + FIXTURE_CANDIDATE: ${{ needs.Select.outputs.candidate }} + FIXTURE_SCENARIO: ${{ needs.Select.outputs.scenario }} + FIXTURE_PR: ${{ needs.Select.outputs.pullRequest }} + FIXTURE_HEAD: ${{ needs.Select.outputs.head }} + FIXTURE_SOURCE: ${{ needs.Select.outputs.source }} + FIXTURE_BEFORE: ${{ needs.Gate.outputs.before }} + FIXTURE_EXPECTED_TAG: ${{ needs.Gate.outputs.expectedTag }} + FIXTURE_CI: ${{ needs.CI.result }} + FIXTURE_TESTED_SHA: ${{ needs.CI.outputs.testedSha }} + FIXTURE_PUBLISH: ${{ needs.Publish.result }} + run: ./tests/Invoke-LegacyFixture.ps1 -Stage Verify diff --git a/fixtures/release-fixture/seed/.github/workflows/Release-Test.yml b/fixtures/release-fixture/seed/.github/workflows/Release-Test.yml new file mode 100644 index 0000000..3d598ba --- /dev/null +++ b/fixtures/release-fixture/seed/.github/workflows/Release-Test.yml @@ -0,0 +1,226 @@ +name: Release integration + +on: + pull_request: + branches: [main] + types: [opened, reopened, synchronize, labeled, unlabeled, edited] + push: + branches: [main] + +permissions: {} + +concurrency: + group: Release-GHRepository-Test + queue: max + +jobs: + Prepare: + name: Select the case and record the inventory + if: >- + ${{ github.repository == 'PSModule/Release-GHRepository-Test' + && github.repository_id == '1477027955' + && (github.event_name == 'push' || github.event.pull_request.head.repo.id == github.event.repository.id) }} + runs-on: ubuntu-24.04 + permissions: + contents: read + pull-requests: read + outputs: + caseId: ${{ steps.fixture.outputs.caseId }} + candidate: ${{ steps.fixture.outputs.candidate }} + scenario: ${{ steps.fixture.outputs.scenario }} + pullRequest: ${{ steps.fixture.outputs.pullRequest }} + head: ${{ steps.fixture.outputs.head }} + before: ${{ steps.fixture.outputs.before }} + defaultBump: ${{ steps.fixture.outputs.defaultBump }} + whatIf: ${{ steps.fixture.outputs.whatIf }} + steps: + - name: Check out the fixture + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Prepare the case + id: fixture + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + run: ./tests/Invoke-ReleaseFixture.ps1 -Stage Prepare + + Plan: + name: Calculate the version + needs: Prepare + if: ${{ needs.Prepare.outputs.caseId != '' }} + runs-on: ubuntu-24.04 + permissions: + contents: read + pull-requests: read + outputs: + calculate: ${{ steps.calculate.outcome }} + control: >- + ${{ steps.control.outcome == 'success' && steps.control.outputs.Decision == 'release' + && steps.control.outputs.BumpSource == 'ActionInput' && steps.control.outputs.ReleaseVersion != '' + && steps.control.outputs.ReleasePlan != '' }} + decision: ${{ steps.calculate.outputs.Decision }} + bumpSource: ${{ steps.calculate.outputs.BumpSource }} + version: ${{ steps.calculate.outputs.ReleaseVersion }} + plan: ${{ steps.calculate.outputs.ReleasePlan }} + steps: + - name: Check out the fixture + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Check out the exact candidate + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + repository: PSModule/Release-GHRepository + ref: ${{ needs.Prepare.outputs.candidate }} + path: .release-action + persist-credentials: false + + - name: Confirm the case can calculate with a default bump + id: control + if: ${{ needs.Prepare.outputs.scenario == 'missing-decision' }} + uses: ./.release-action + with: + Mode: calculate + DefaultBump: patch + + - name: Calculate the version + id: calculate + uses: ./.release-action + with: + Mode: calculate + DefaultBump: ${{ needs.Prepare.outputs.defaultBump }} + + CI: + name: Test the exact commit + needs: [Prepare, Plan] + if: ${{ !cancelled() && needs.Prepare.result == 'success' }} + runs-on: ubuntu-24.04 + permissions: + contents: read + outputs: + testedSha: ${{ steps.source.outputs.sha }} + fault: ${{ steps.fault.outcome }} + steps: + - name: Check out the fixture + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Test case selection and inventory assertions + uses: PSModule/Invoke-Pester@4ff33199141fdf22568990b6107fe3148ae93a1c # v5.1.0 + with: + Path: tests + Version: 6.1.0 + + - name: Record the tested SHA + id: source + shell: pwsh + run: | + $sha = git rev-parse HEAD + if ($LASTEXITCODE -ne 0 -or $sha -cne $env:GITHUB_SHA) { + throw 'CI did not test the run commit.' + } + Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value "sha=$sha" + + - name: Inject a failure only on the pushed commit + id: fault + if: ${{ github.event_name == 'push' && needs.Prepare.outputs.scenario == 'ci-failure' }} + shell: pwsh + run: throw 'Intentional CI failure on the pushed fixture commit.' + + Publish: + name: Publish the tested commit + needs: [Prepare, Plan, CI] + if: >- + ${{ success() && github.event_name == 'push' && github.ref == 'refs/heads/main' + && needs.Prepare.outputs.caseId != '' && needs.Plan.outputs.decision == 'release' + && needs.CI.outputs.testedSha == github.sha }} + runs-on: ubuntu-24.04 + permissions: + contents: write + pull-requests: read + steps: + - name: Check out the tested commit + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Check out the exact candidate + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + repository: PSModule/Release-GHRepository + ref: ${{ needs.Prepare.outputs.candidate }} + path: .release-action + persist-credentials: false + + - name: Require the staged handoff + if: ${{ needs.Prepare.outputs.scenario != 'one-step' }} + shell: pwsh + env: + RELEASE_PLAN: ${{ needs.Plan.outputs.plan }} + run: | + if ([string]::IsNullOrWhiteSpace($env:RELEASE_PLAN)) { + throw 'The staged publisher requires an unchanged plan from this run.' + } + + - name: Publish with the plan + if: ${{ needs.Prepare.outputs.scenario != 'one-step' }} + uses: ./.release-action + with: + Mode: publish + DefaultBump: ${{ needs.Prepare.outputs.defaultBump }} + ReleasePlan: ${{ needs.Plan.outputs.plan }} + WhatIf: ${{ needs.Prepare.outputs.whatIf }} + + - name: Calculate and publish in one step + if: ${{ needs.Prepare.outputs.scenario == 'one-step' }} + uses: ./.release-action + with: + Mode: publish + DefaultBump: ${{ needs.Prepare.outputs.defaultBump }} + WhatIf: ${{ needs.Prepare.outputs.whatIf }} + + Verify: + name: Verify the fixture result + needs: [Prepare, Plan, CI, Publish] + if: ${{ !cancelled() && needs.Prepare.result == 'success' && needs.Prepare.outputs.caseId != '' }} + runs-on: ubuntu-24.04 + permissions: + contents: read + pull-requests: write + steps: + - name: Check out the fixture + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Verify and report the case + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + FIXTURE_CASE_ID: ${{ needs.Prepare.outputs.caseId }} + FIXTURE_CANDIDATE: ${{ needs.Prepare.outputs.candidate }} + FIXTURE_SCENARIO: ${{ needs.Prepare.outputs.scenario }} + FIXTURE_PR: ${{ needs.Prepare.outputs.pullRequest }} + FIXTURE_HEAD: ${{ needs.Prepare.outputs.head }} + FIXTURE_BEFORE: ${{ needs.Prepare.outputs.before }} + FIXTURE_PLAN: ${{ needs.Plan.result }} + FIXTURE_CALCULATE: ${{ needs.Plan.outputs.calculate }} + FIXTURE_CONTROL: ${{ needs.Plan.outputs.control }} + FIXTURE_DECISION: ${{ needs.Plan.outputs.decision }} + FIXTURE_BUMP_SOURCE: ${{ needs.Plan.outputs.bumpSource }} + FIXTURE_VERSION: ${{ needs.Plan.outputs.version }} + FIXTURE_HAS_PLAN: ${{ needs.Plan.outputs.plan != '' }} + FIXTURE_CI: ${{ needs.CI.result }} + FIXTURE_TESTED_SHA: ${{ needs.CI.outputs.testedSha }} + FIXTURE_FAULT: ${{ needs.CI.outputs.fault }} + FIXTURE_PUBLISH: ${{ needs.Publish.result }} + run: ./tests/Invoke-ReleaseFixture.ps1 -Stage Verify diff --git a/fixtures/release-fixture/seed/tests-baseline/LegacyAction.psm1 b/fixtures/release-fixture/seed/tests-baseline/LegacyAction.psm1 new file mode 100644 index 0000000..0a1183d --- /dev/null +++ b/fixtures/release-fixture/seed/tests-baseline/LegacyAction.psm1 @@ -0,0 +1,98 @@ +function Invoke-LegacyAction { + <# + .SYNOPSIS + Runs the pinned v2.0.3 src/main.ps1 unchanged against a synthetic event and gh/git doubles. + + .DESCRIPTION + Nothing reaches GitHub. The doubles answer the two read calls the action makes and record every + other call as a write. The real GitHub module supplies LogGroup and the notice commands. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [string] $ActionPath, + + [Parameter(Mandatory)] + [System.Collections.IDictionary] $PullRequest, + + [System.Collections.IDictionary] $Inputs = @{}, + + [object[]] $Releases = @(), + + [string] $Action = 'closed' + ) + + $defaults = @{ + AutoCleanup = 'true'; AutoPatching = 'true'; ConfigurationFile = '.github/auto-release.yml' + CreateMajorTag = 'true'; CreateMinorTag = 'true'; DatePrereleaseFormat = ''; IgnoreLabels = 'NoRelease' + IncrementalPrerelease = 'true'; MajorLabels = 'major, breaking'; MinorLabels = 'minor, feature' + PatchLabels = 'patch, fix'; UsePRBodyAsReleaseNotes = 'true'; UsePRTitleAsReleaseName = 'false' + UsePRTitleAsNotesHeading = 'true'; VersionPrefix = 'v'; WhatIf = 'false' + } + $workspace = Join-Path ([IO.Path]::GetTempPath()) "legacy-$([guid]::NewGuid().ToString('N'))" + $null = New-Item -ItemType Directory -Path $workspace + $eventPath = Join-Path $workspace 'event.json' + @{ action = $Action; pull_request = $PullRequest } | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $eventPath + + $saved = @{} + $names = @($defaults.Keys | ForEach-Object { "PSMODULE_AUTO_RELEASE_INPUT_$_" }) + 'GITHUB_EVENT_PATH' + foreach ($name in $names) { $saved[$name] = [Environment]::GetEnvironmentVariable($name) } + $global:LegacyActionCalls = [System.Collections.Generic.List[string]]::new() + $global:LegacyActionReleases = ConvertTo-Json -InputObject @($Releases) -Compress -AsArray + Push-Location -LiteralPath $workspace + try { + foreach ($key in $defaults.Keys) { + $value = if ($Inputs.Contains($key)) { $Inputs[$key] } else { $defaults[$key] } + [Environment]::SetEnvironmentVariable("PSMODULE_AUTO_RELEASE_INPUT_$key", $value) + } + $env:GITHUB_EVENT_PATH = $eventPath + + function global:gh { + $line = $args -join ' ' + $global:LASTEXITCODE = 0 + if ($line -like 'repo view *') { return '{"defaultBranchRef":{"name":"main"}}' } + if ($line -like 'release list *') { return $global:LegacyActionReleases } + $global:LegacyActionCalls.Add("gh $line") + } + function global:git { + $global:LASTEXITCODE = 0 + $global:LegacyActionCalls.Add("git $($args -join ' ')") + } + function global:Install-PSResource { } + + $output = & (Join-Path $ActionPath 'src/main.ps1') *>&1 | Out-String + [PSCustomObject]@{ Output = $output; Writes = @($global:LegacyActionCalls) } + } finally { + Pop-Location + foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $saved[$name]) } + Remove-Item -Path function:global:gh, function:global:git, function:global:Install-PSResource -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $workspace -Recurse -Force -ErrorAction SilentlyContinue + } +} + +function New-LegacyPullRequest { + <# + .SYNOPSIS + Builds the pull_request payload fields the pinned action reads, in the shape GitHub sends. + #> + [CmdletBinding()] + [OutputType([System.Collections.IDictionary])] + param( + [string[]] $Label = @(), + [bool] $Merged = $true, + [string] $Base = 'main' + ) + + @{ + number = 3 + title = 'Synthetic fixture change' + body = 'Synthetic body.' + state = 'closed' + merged = $Merged + labels = @($Label | ForEach-Object { @{ name = $_ } }) + base = @{ ref = $Base } + head = @{ ref = 'release-fixture/1-1' } + } +} + +Export-ModuleMember -Function Invoke-LegacyAction, New-LegacyPullRequest diff --git a/fixtures/release-fixture/seed/tests-baseline/LegacyBaseline.Tests.ps1 b/fixtures/release-fixture/seed/tests-baseline/LegacyBaseline.Tests.ps1 new file mode 100644 index 0000000..1f53761 --- /dev/null +++ b/fixtures/release-fixture/seed/tests-baseline/LegacyBaseline.Tests.ps1 @@ -0,0 +1,118 @@ +BeforeAll { + Import-Module (Join-Path $PSScriptRoot 'LegacyAction.psm1') -Force + Import-Module GitHub, PSSemVer, powershell-yaml + + $script:actionPath = $env:LEGACY_ACTION_PATH + if (-not $actionPath -or -not (Test-Path -LiteralPath (Join-Path $actionPath 'src/main.ps1'))) { + throw 'Set LEGACY_ACTION_PATH to a checkout of PSModule/Release-GHRepository at the pinned SHA.' + } + $script:pinned = '750abed0ecab02394554b610dc3aa191e75e3248' + $head = git -C $actionPath rev-parse HEAD + if ($head -cne $pinned) { throw "The action checkout is at [$head], not the pinned [$pinned]." } + + # The inputs the legacy publishing job sets. Everything else keeps the action default. + $script:legacyInputs = @{ + AutoPatching = 'false'; AutoCleanup = 'false'; CreateMajorTag = 'false'; CreateMinorTag = 'false' + PatchLabels = 'release:patch' + } + $script:push = 'git push origin --tags --force' +} + +Describe 'Pinned v2.0.3 baseline with the legacy inputs' { + It 'publishes the first stable release from an empty inventory (simulated writes)' { + $result = Invoke-LegacyAction -ActionPath $actionPath -Inputs $legacyInputs ` + -PullRequest (New-LegacyPullRequest -Label 'release:patch') + + $result.Writes | Should -HaveCount 2 + $result.Writes[0] | Should -BeLike 'gh release create v0.0.1 --title v0.0.1 --notes *' + $result.Writes[1] | Should -BeExactly $push + } + + It 'bumps the patch of the latest stable release' { + $latest = @{ tagName = 'v1.2.3'; isLatest = $true; isDraft = $false; isPrerelease = $false; name = 'v1.2.3' } + $result = Invoke-LegacyAction -ActionPath $actionPath -Inputs $legacyInputs -Releases @($latest) ` + -PullRequest (New-LegacyPullRequest -Label 'release:patch') + + $result.Writes[0] | Should -BeLike 'gh release create v1.2.4 *' + $result.Writes | Should -HaveCount 2 + } + + It 'previews without any write when WhatIf is on' { + $result = Invoke-LegacyAction -ActionPath $actionPath -Inputs ($legacyInputs + @{ WhatIf = 'true' }) ` + -PullRequest (New-LegacyPullRequest -Label 'release:patch') + + $result.Writes | Should -BeNullOrEmpty + $result.Output | Should -Match 'WhatIf: git push origin --tags --force' + } + + # The action's "Skipping release creation" path runs inside LogGroup, so its return leaves only + # that block. The script goes on and releases the unchanged version. Candidate requires a decision. + It 'does not skip without a decision: it releases the unchanged version (v0.0.0 on an empty inventory)' { + $result = Invoke-LegacyAction -ActionPath $actionPath -Inputs $legacyInputs -PullRequest (New-LegacyPullRequest) + + $result.Output | Should -Match 'Skipping release creation, exiting\.' + $result.Writes[0] | Should -BeLike 'gh release create v0.0.0 *' + } + + It 'tries to recreate the latest release without a decision, which gh rejects in a real run' { + $latest = @{ tagName = 'v1.2.3'; isLatest = $true; isDraft = $false; isPrerelease = $false; name = 'v1.2.3' } + $result = Invoke-LegacyAction -ActionPath $actionPath -Inputs $legacyInputs -Releases @($latest) ` + -PullRequest (New-LegacyPullRequest -Label 'release:skip') + + $result.Writes[0] | Should -BeLike 'gh release create v1.2.3 *' + } + It 'skips with its own NoRelease ignore label' { + $result = Invoke-LegacyAction -ActionPath $actionPath -Inputs $legacyInputs ` + -PullRequest (New-LegacyPullRequest -Label 'release:patch', 'NoRelease') + + $result.Writes | Should -BeNullOrEmpty + $result.Output | Should -Match 'Ignoring release creation\.' + } + + It 'lets an unnamespaced bump label override the explicit patch label' { + $result = Invoke-LegacyAction -ActionPath $actionPath -Inputs $legacyInputs ` + -PullRequest (New-LegacyPullRequest -Label 'release:patch', 'major') + + $result.Writes[0] | Should -BeLike 'gh release create v1.0.0 *' + } + + It 'writes nothing for an unmerged pull request or another base' { + foreach ($pr in (New-LegacyPullRequest -Label 'release:patch' -Merged $false), + (New-LegacyPullRequest -Label 'release:patch' -Base 'dev')) { + (Invoke-LegacyAction -ActionPath $actionPath -Inputs $legacyInputs -PullRequest $pr).Writes | + Should -BeNullOrEmpty + } + } +} + +Describe 'Pinned v2.0.3 defaults that the legacy inputs turn off' { + It 'patches without a decision label when auto-patching is on (the default)' { + $result = Invoke-LegacyAction -ActionPath $actionPath -PullRequest (New-LegacyPullRequest) + + $result.Writes[0] | Should -BeLike 'gh release create v0.0.1 *' + } + + It 'treats release:skip as no decision, so auto-patching still releases' { + $result = Invoke-LegacyAction -ActionPath $actionPath -PullRequest (New-LegacyPullRequest -Label 'release:skip') + + $result.Writes[0] | Should -BeLike 'gh release create v0.0.1 *' + } + + It 'moves the major and minor alias tags with git when they are on' { + $result = Invoke-LegacyAction -ActionPath $actionPath -PullRequest (New-LegacyPullRequest) + + $result.Writes | Should -Contain 'git tag -f v0 main' + $result.Writes | Should -Contain 'git tag -f v0.0 main' + } +} + +Describe 'Pinned v2.0.3 configuration file' { + It 'overrides the workflow inputs when the file is present' { + $file = Join-Path $TestDrive 'auto-release.yml' + Set-Content -LiteralPath $file -Value 'AutoPatching: true' + $result = Invoke-LegacyAction -ActionPath $actionPath -PullRequest (New-LegacyPullRequest) ` + -Inputs ($legacyInputs + @{ ConfigurationFile = $file }) + + $result.Writes[0] | Should -BeLike 'gh release create v0.0.1 *' + } +} diff --git a/fixtures/release-fixture/seed/tests/FixtureContract.json b/fixtures/release-fixture/seed/tests/FixtureContract.json new file mode 100644 index 0000000..c21d3a8 --- /dev/null +++ b/fixtures/release-fixture/seed/tests/FixtureContract.json @@ -0,0 +1,12 @@ +{ + "schema": 2, + "scenarios": { + "preview": "release:patch", + "staged": "release:patch", + "one-step": "release:patch", + "configured-default": "", + "missing-decision": "", + "skip": "release:skip", + "ci-failure": "release:patch" + } +} diff --git a/fixtures/release-fixture/seed/tests/Invoke-LegacyFixture.ps1 b/fixtures/release-fixture/seed/tests/Invoke-LegacyFixture.ps1 new file mode 100644 index 0000000..ec4a208 --- /dev/null +++ b/fixtures/release-fixture/seed/tests/Invoke-LegacyFixture.ps1 @@ -0,0 +1,162 @@ +#Requires -Version 7.4 +[CmdletBinding()] +param( + [Parameter(Mandatory)] + [ValidateSet('Select', 'Gate', 'Verify')] + [string] $Stage +) + +$ErrorActionPreference = 'Stop' +Import-Module (Join-Path $PSScriptRoot 'ReleaseInventory.psm1') +Import-Module (Join-Path $PSScriptRoot 'LegacyCase.psm1') + +if ($env:GITHUB_REPOSITORY -cne 'PSModule/Release-GHRepository-Test' -or $env:GITHUB_REPOSITORY_ID -ne '1477027955' -or + $env:GITHUB_EVENT_NAME -cne 'pull_request') { + throw 'This suite runs only for pull requests in PSModule/Release-GHRepository-Test.' +} +$repository = $env:GITHUB_REPOSITORY + +function Get-GitHubCollection { + <# + .SYNOPSIS + Reads every page and distinguishes an empty collection from a failed read. + #> + param([string] $Resource) + + $response = gh api --paginate --slurp "${Resource}?per_page=100" + if ($LASTEXITCODE -ne 0) { throw "GitHub API read failed for [$Resource]." } + + $pages = ConvertFrom-Json -InputObject ($response -join "`n") -AsHashtable -NoEnumerate + if ($pages -isnot [array] -or $pages.Count -eq 0) { throw "GitHub returned no pages for [$Resource]." } + foreach ($page in $pages) { + if ($page -isnot [array]) { throw "GitHub returned an invalid page for [$Resource]." } + $page + } +} + +function Get-ReleaseInventory { + <# + .SYNOPSIS + Reads the tag targets and release identities of the legacy repository. + #> + @{ + tags = @( + Get-GitHubCollection -Resource "repos/$repository/tags" | ForEach-Object { + @{ name = $_.name; sha = $_.commit.sha } + } + ) + releases = @( + Get-GitHubCollection -Resource "repos/$repository/releases" | ForEach-Object { + @{ tag = $_.tag_name; id = $_.id; draft = $_.draft; prerelease = $_.prerelease } + } + ) + } +} + +function Get-MainSha { + $sha = gh api "repos/$repository/git/ref/heads/main" --jq .object.sha + if ($LASTEXITCODE -ne 0 -or $sha -cnotmatch '\A[0-9a-f]{40}\z') { throw 'Could not read main.' } + $sha +} + +function Get-CaseFile { + param([string] $Id, [string] $Ref) + + $content = gh api -H 'Accept: application/vnd.github.raw+json' "repos/$repository/contents/tests/cases/${Id}.json?ref=$Ref" + if ($LASTEXITCODE -ne 0) { throw "Could not read case [$Id] at [$Ref]." } + $content -join "`n" +} + +$eventPayload = Get-Content -LiteralPath $env:GITHUB_EVENT_PATH -Raw | ConvertFrom-Json -AsHashtable + +if ($Stage -ceq 'Select') { + $pullRequest = $eventPayload.pull_request + $caseId = [regex]::Match([string] $pullRequest.head.ref, '\Arelease-fixture/([1-9][0-9]*-[1-9][0-9]*)\z').Groups[1].Value + $squash = [string] $pullRequest.merge_commit_sha + if (-not $caseId -or $squash -cnotmatch '\A[0-9a-f]{40}\z') { throw 'The pull request does not identify a case and squash commit.' } + + $squashCase = Get-CaseFile -Id $caseId -Ref $squash + if (-not (Test-LegacyCase -CaseJson $squashCase)) { + Write-Information "Case [$caseId] is not pinned to the legacy action. The candidate lane owns it." -InformationAction Continue + return + } + + $commit = gh api "repos/$repository/commits/$squash" | ConvertFrom-Json -AsHashtable + if ($LASTEXITCODE -ne 0) { throw "Could not read the squash commit [$squash]." } + $case = Get-LegacyFixtureCase -EventPayload $eventPayload -Repository $repository ` + -RepositoryId ([long] $env:GITHUB_REPOSITORY_ID) -Commit $commit -CommitFiles @($commit.files) ` + -HeadCase (Get-CaseFile -Id $caseId -Ref $pullRequest.head.sha) -SquashCase $squashCase + + # v2.0.3 lets this file override the workflow inputs. The path uses a backslash by default. + foreach ($configuration in '.github/auto-release.yml', '.github\auto-release.yml') { + if (Test-Path -LiteralPath $configuration) { throw "The legacy configuration [$configuration] must not exist." } + } + + Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value @( + "caseId=$($case.Id)" + "candidate=$($case.Candidate)" + "scenario=$($case.Scenario)" + "pullRequest=$($case.PullRequest)" + "head=$($case.Head)" + "source=$($case.Source)" + ) + return +} + +if ($Stage -ceq 'Gate') { + $inventory = Get-ReleaseInventory + $latestTag = '' + if (@($inventory.releases).Count -gt 0) { + $latestTag = gh api "repos/$repository/releases/latest" --jq .tag_name + if ($LASTEXITCODE -ne 0) { throw 'Could not read the latest release.' } + } + $expectedTag = Get-LegacyExpectedTag -MainSha (Get-MainSha) -Source $env:FIXTURE_SOURCE -Inventory $inventory -LatestTag $latestTag + if ($env:GITHUB_OUTPUT) { + Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value @( + "before=$(Get-ReleaseInventoryFingerprint -Inventory $inventory)" + "expectedTag=$expectedTag" + ) + } + return +} + +$report = [ordered]@{ + schema = 2 + caseId = $env:FIXTURE_CASE_ID + candidate = $env:FIXTURE_CANDIDATE + scenario = $env:FIXTURE_SCENARIO + event = $env:GITHUB_EVENT_NAME + activity = $eventPayload.action + source = $env:FIXTURE_SOURCE + head = $env:FIXTURE_HEAD + run = "$env:GITHUB_SERVER_URL/$env:GITHUB_REPOSITORY/actions/runs/$env:GITHUB_RUN_ID" + attempt = $env:GITHUB_RUN_ATTEMPT + ci = $env:FIXTURE_CI + testedSource = $env:FIXTURE_TESTED_SHA + publish = $env:FIXTURE_PUBLISH + tag = $null + oracle = 'failure' + verified = $false +} + +try { + if ($report.ci -cne 'success' -or $report.testedSource -cne $report.source) { + throw "Expected CI to pass at the squash commit [$($report.source)]." + } + if ($report.publish -cne 'success') { throw 'Expected the publishing job to succeed.' } + if ((Get-MainSha) -cne $report.source) { throw 'Main moved during the run.' } + + $after = Get-ReleaseInventory + $tag = $env:FIXTURE_EXPECTED_TAG + if ($tag -cnotmatch '\Av[0-9]+\.[0-9]+\.[0-9]+\z') { throw 'The gate did not supply a stable expected tag.' } + Assert-ReleaseInventory -Before $env:FIXTURE_BEFORE -After $after -Source $report.source -ExpectedTag $tag + $report.tag = $tag + $report.oracle = 'success' + $report.verified = $true +} finally { + $body = @('', '```json', (ConvertTo-Json $report -Compress), '```') -join "`n" + Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Value $body + + gh api --method POST "repos/$repository/issues/$env:FIXTURE_PR/comments" -f "body=$body" --silent + if ($LASTEXITCODE -ne 0) { throw "Could not report the fixture result on PR [$env:FIXTURE_PR]." } +} diff --git a/fixtures/release-fixture/seed/tests/Invoke-ReleaseFixture.ps1 b/fixtures/release-fixture/seed/tests/Invoke-ReleaseFixture.ps1 new file mode 100644 index 0000000..2ccfcb6 --- /dev/null +++ b/fixtures/release-fixture/seed/tests/Invoke-ReleaseFixture.ps1 @@ -0,0 +1,171 @@ +#Requires -Version 7.4 +[CmdletBinding()] +param( + [Parameter(Mandatory)] + [ValidateSet('Prepare', 'Verify')] + [string] $Stage +) + +$ErrorActionPreference = 'Stop' +Import-Module (Join-Path $PSScriptRoot 'ReleaseInventory.psm1') + +if ($env:GITHUB_REPOSITORY -cne 'PSModule/Release-GHRepository-Test' -or $env:GITHUB_REPOSITORY_ID -ne '1477027955' -or + $env:GITHUB_EVENT_NAME -cnotin @('pull_request', 'push') -or + $env:GITHUB_SHA -cnotmatch '\A[0-9a-f]{40}\z') { + throw 'This suite runs only for PRs and pushes in PSModule/Release-GHRepository-Test.' +} + +function Get-GitHubCollection { + <# + .SYNOPSIS + Reads every page and distinguishes an empty collection from a failed read. + #> + param([string] $Resource) + + $response = gh api --paginate --slurp "${Resource}?per_page=100" + if ($LASTEXITCODE -ne 0) { throw "GitHub API read failed for [$Resource]." } + + $pages = ConvertFrom-Json -InputObject ($response -join "`n") -AsHashtable -NoEnumerate + if ($pages -isnot [array] -or $pages.Count -eq 0) { + throw "GitHub returned no inventory pages for [$Resource]." + } + foreach ($page in $pages) { + if ($page -isnot [array]) { throw "GitHub returned an invalid page for [$Resource]." } + $page + } +} + +function Get-ReleaseInventory { + <# + .SYNOPSIS + Reads the tag targets and release identities needed to verify a fixture run. + #> + @{ + tags = @( + Get-GitHubCollection -Resource "repos/$env:GITHUB_REPOSITORY/tags" | ForEach-Object { + @{ name = $_.name; sha = $_.commit.sha } + } + ) + releases = @( + Get-GitHubCollection -Resource "repos/$env:GITHUB_REPOSITORY/releases" | ForEach-Object { + @{ tag = $_.tag_name; id = $_.id; draft = $_.draft; prerelease = $_.prerelease } + } + ) + } +} + +$isPush = $env:GITHUB_EVENT_NAME -ceq 'push' +$eventPayload = Get-Content -LiteralPath $env:GITHUB_EVENT_PATH -Raw | ConvertFrom-Json -AsHashtable + +if ($Stage -ceq 'Prepare') { + Import-Module (Join-Path $PSScriptRoot 'ReleaseCase.psm1') + $pullRequests = if ($isPush) { + if ($eventPayload.ref -cne 'refs/heads/main' -or $eventPayload.after -cne $env:GITHUB_SHA -or $eventPayload.deleted) { + throw 'The push must identify an exact fixture commit on main.' + } + Get-GitHubCollection -Resource "repos/$env:GITHUB_REPOSITORY/commits/$env:GITHUB_SHA/pulls" + } else { + $eventPayload.pull_request + } + $case = Get-ReleaseFixtureCase -Path $PSScriptRoot -EventName $env:GITHUB_EVENT_NAME -Source $env:GITHUB_SHA ` + -PullRequests @($pullRequests | Where-Object { $_ }) + if (-not $case) { + Write-Information 'No active release case. Run only the fixture tests.' -InformationAction Continue + return + } + + $before = Get-ReleaseInventoryFingerprint -Inventory (Get-ReleaseInventory) + $defaultBump = if ($case.Scenario -ceq 'configured-default') { 'patch' } else { 'none' } + $whatIf = if ($case.Scenario -ceq 'preview') { 'true' } else { 'false' } + Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value @( + "caseId=$($case.Id)" + "candidate=$($case.Candidate)" + "scenario=$($case.Scenario)" + "pullRequest=$($case.PullRequest)" + "head=$($case.Head)" + "before=$before" + "defaultBump=$defaultBump" + "whatIf=$whatIf" + ) + return +} + +$scenario = $env:FIXTURE_SCENARIO +$report = [ordered]@{ + schema = 2 + caseId = $env:FIXTURE_CASE_ID + candidate = $env:FIXTURE_CANDIDATE + scenario = $scenario + event = $env:GITHUB_EVENT_NAME + activity = $eventPayload.action + source = $env:GITHUB_SHA + head = $env:FIXTURE_HEAD + run = "$env:GITHUB_SERVER_URL/$env:GITHUB_REPOSITORY/actions/runs/$env:GITHUB_RUN_ID" + attempt = $env:GITHUB_RUN_ATTEMPT + plan = $env:FIXTURE_PLAN + decision = $env:FIXTURE_DECISION + bumpSource = $env:FIXTURE_BUMP_SOURCE + version = $env:FIXTURE_VERSION + ci = $env:FIXTURE_CI + testedSource = $env:FIXTURE_TESTED_SHA + publish = $env:FIXTURE_PUBLISH + tag = $null + oracle = 'failure' + verified = $false +} + +try { + $expectMissing = $scenario -ceq 'missing-decision' + $expectSkip = $scenario -ceq 'skip' + $expectFailure = $isPush -and $scenario -ceq 'ci-failure' + $expectPublish = $isPush -and -not ($expectMissing -or $expectSkip -or $expectFailure) + + $planResult = if ($expectMissing) { 'failure' } else { 'success' } + if ($report.plan -cne $planResult -or $env:FIXTURE_CALCULATE -cne $planResult) { + throw "Expected the Calculate step and Plan job to report [$planResult]." + } + if ($expectMissing -and $env:FIXTURE_CONTROL -cne 'true') { + throw 'The missing-decision case must first calculate a release with a configured default.' + } + if ($expectMissing -or $expectSkip) { + $expectedDecision = if ($expectMissing) { '' } else { 'skip' } + if ($report.decision -cne $expectedDecision -or $report.version -or $env:FIXTURE_HAS_PLAN -cne 'false') { + throw 'A missing or skipped decision must not supply a version or plan.' + } + } else { + $expectedSource = if ($scenario -ceq 'configured-default') { 'ActionInput' } else { 'release:patch' } + if ($report.decision -cne 'release' -or $report.bumpSource -cne $expectedSource -or + -not $report.version -or $env:FIXTURE_HAS_PLAN -cne 'true') { + throw "Expected Calculate to supply a version and plan from [$expectedSource]." + } + } + + $ciResult = if ($expectFailure) { 'failure' } else { 'success' } + $faultResult = if ($expectFailure) { 'failure' } else { 'skipped' } + if ($report.ci -cne $ciResult -or $env:FIXTURE_FAULT -cne $faultResult -or $report.testedSource -cne $report.source) { + throw "Expected CI [$ciResult] and the intentional fault [$faultResult] at [$($report.source)]." + } + + $publishResult = if ($expectPublish) { 'success' } else { 'skipped' } + if ($report.publish -cne $publishResult) { + throw "Expected Publish to report [$publishResult]." + } + + $expectedTag = if ($expectPublish -and $scenario -cne 'preview') { + if ($report.version -cnotmatch '^[0-9]+\.[0-9]+\.[0-9]+$') { + throw "Expected a stable version for publication, not [$($report.version)]." + } + "v$($report.version)" + } + Assert-ReleaseInventory -Before $env:FIXTURE_BEFORE -After (Get-ReleaseInventory) -Source $report.source -ExpectedTag $expectedTag + $report.tag = $expectedTag + $report.oracle = 'success' + $report.verified = $true +} finally { + $body = @('', '```json', (ConvertTo-Json $report -Compress), '```') -join "`n" + Add-Content -LiteralPath $env:GITHUB_STEP_SUMMARY -Value $body + + $pullRequest = $env:FIXTURE_PR + gh api --method POST "repos/$env:GITHUB_REPOSITORY/issues/$pullRequest/comments" -f "body=$body" --silent + if ($LASTEXITCODE -ne 0) { throw "Could not report the fixture result on PR [$pullRequest]." } +} diff --git a/fixtures/release-fixture/seed/tests/LegacyCase.Tests.ps1 b/fixtures/release-fixture/seed/tests/LegacyCase.Tests.ps1 new file mode 100644 index 0000000..ad16535 --- /dev/null +++ b/fixtures/release-fixture/seed/tests/LegacyCase.Tests.ps1 @@ -0,0 +1,182 @@ +BeforeAll { + Import-Module (Join-Path $PSScriptRoot 'LegacyCase.psm1') -Force + + $script:repository = 'PSModule/Release-GHRepository-Test' + $script:candidate = '750abed0ecab02394554b610dc3aa191e75e3248' + $script:squash = 'c' * 40 + $script:workflow = Get-Content -LiteralPath (Join-Path $PSScriptRoot '..\.github\workflows\Legacy-Release-Test.yml') -Raw +} + +Describe 'Legacy fixture case' { + BeforeEach { + $caseFile = "{`"scenario`":`"one-step`",`"candidate`":`"$candidate`"}" + $script:arguments = @{ + Repository = $repository + RepositoryId = 1477027955 + EventPayload = @{ + action = 'closed' + pull_request = @{ + number = 3 + merged = $true + user = @{ id = 314722336; login = 'psmodule-s-shelly[bot]' } + base = @{ ref = 'main'; repo = @{ id = 1477027955; full_name = $repository } } + head = @{ ref = 'release-fixture/123-1'; sha = 'b' * 40; repo = @{ id = 1477027955; full_name = $repository } } + labels = @(@{ name = 'release:patch' }) + merge_commit_sha = $squash + } + } + Commit = @{ + sha = $squash + parents = @(@{ sha = 'a' * 40 }) + commit = @{ verification = @{ verified = $true } } + } + CommitFiles = @(@{ filename = 'tests/cases/123-1.json'; status = 'added' }) + HeadCase = $caseFile + SquashCase = $caseFile + } + } + + It 'accepts the verified one-step squash for the pinned candidate' { + $case = Get-LegacyFixtureCase @arguments + + $case.Id | Should -BeExactly '123-1' + $case.Source | Should -BeExactly $squash + $case.Head | Should -BeExactly ('b' * 40) + $case.Candidate | Should -BeExactly $candidate + $case.Scenario | Should -BeExactly 'one-step' + } + + It 'rejects another repository or repository ID' { + $arguments.Repository = 'PSModule/Release-GHRepository-Test-Legacy' + { Get-LegacyFixtureCase @arguments } | Should -Throw '*Only*' + $arguments.Repository = $repository + $arguments.RepositoryId = 77 + { Get-LegacyFixtureCase @arguments } | Should -Throw '*Only*' + } + + It 'rejects ' -ForEach @( + @{ Name = 'an unmerged pull request'; Change = { $arguments.EventPayload.pull_request.merged = $false } } + @{ Name = 'a fork'; Change = { $arguments.EventPayload.pull_request.head.repo.id = 5 } } + @{ Name = 'a head repo with another name'; Change = { $arguments.EventPayload.pull_request.head.repo.full_name = 'x/y' } } + @{ Name = 'a base other than main'; Change = { $arguments.EventPayload.pull_request.base.ref = 'dev' } } + @{ Name = 'another author'; Change = { $arguments.EventPayload.pull_request.user.id = 42 } } + @{ Name = 'an ordinary branch'; Change = { $arguments.EventPayload.pull_request.head.ref = 'feature/x' } } + @{ Name = 'a non-numeric run ID'; Change = { $arguments.EventPayload.pull_request.head.ref = 'release-fixture/abc-1' } } + @{ Name = 'another release label'; Change = { $arguments.EventPayload.pull_request.labels = @(@{ name = 'release:minor' }) } } + @{ Name = 'a second release label'; Change = { $arguments.EventPayload.pull_request.labels += @{ name = 'release:skip' } } } + @{ Name = 'a legacy major label'; Change = { $arguments.EventPayload.pull_request.labels += @{ name = 'major' } } } + @{ Name = 'a legacy feature label'; Change = { $arguments.EventPayload.pull_request.labels += @{ name = 'feature' } } } + @{ Name = 'a legacy ignore label'; Change = { $arguments.EventPayload.pull_request.labels += @{ name = 'NoRelease' } } } + @{ Name = 'an unrelated extra label'; Change = { $arguments.EventPayload.pull_request.labels += @{ name = 'documentation' } } } + @{ Name = 'a missing label'; Change = { $arguments.EventPayload.pull_request.labels = @() } } + @{ Name = 'an unverified squash'; Change = { $arguments.Commit.commit.verification.verified = $false } } + @{ Name = 'a merge commit with two parents'; Change = { $arguments.Commit.parents += @{ sha = 'd' * 40 } } } + @{ Name = 'a squash that is not the merge commit'; Change = { $arguments.Commit.sha = 'e' * 40 } } + @{ Name = 'an extra changed file'; Change = { $arguments.CommitFiles += @{ filename = 'README.md'; status = 'modified' } } } + @{ Name = 'a modified case file'; Change = { $arguments.CommitFiles[0].status = 'modified' } } + @{ Name = 'a case file for another run'; Change = { $arguments.CommitFiles[0].filename = 'tests/cases/9-9.json' } } + @{ Name = 'a case that changed after review'; Change = { $arguments.SquashCase = '{"scenario":"one-step","candidate":"' + ('f' * 40) + '"}' } } + @{ Name = 'another scenario'; Change = { + $other = '{"scenario":"staged","candidate":"' + $candidate + '"}' + $arguments.HeadCase = $other; $arguments.SquashCase = $other + } + } + @{ Name = 'another candidate'; Change = { + $other = '{"scenario":"one-step","candidate":"' + ('f' * 40) + '"}' + $arguments.HeadCase = $other; $arguments.SquashCase = $other + } + } + @{ Name = 'an extra case property'; Change = { + $other = '{"scenario":"one-step","candidate":"' + $candidate + '","x":1}' + $arguments.HeadCase = $other; $arguments.SquashCase = $other + } + } + ) { + & $Change + { Get-LegacyFixtureCase @arguments } | Should -Throw + } +} + +Describe 'Legacy case routing' { + It 'owns only cases pinned to the published legacy action' { + Test-LegacyCase -CaseJson "{`"scenario`":`"one-step`",`"candidate`":`"$candidate`"}" | Should -BeTrue + Test-LegacyCase -CaseJson ('{"scenario":"one-step","candidate":"' + ('f' * 40) + '"}') | Should -BeFalse + Test-LegacyCase -CaseJson 'not json' | Should -BeFalse + Test-LegacyCase -CaseJson '[]' | Should -BeFalse + } +} + +Describe 'Legacy publication gate' { + BeforeEach { + $script:inventory = @{ + tags = @(@{ name = 'v1.2.9'; sha = 'a' * 40 }, @{ name = 'v1.2.10'; sha = 'b' * 40 }) + releases = @(@{ tag = 'v1.2.9'; id = 1; draft = $false; prerelease = $false }, @{ tag = 'v1.2.10'; id = 2; draft = $false; prerelease = $false }) + } + } + + It 'starts at v0.0.1 in an empty inventory' { + Get-LegacyExpectedTag -MainSha $squash -Source $squash -Inventory @{ tags = @(); releases = @() } | + Should -BeExactly 'v0.0.1' + } + + It 'bumps the patch number of the latest release numerically' { + Get-LegacyExpectedTag -MainSha $squash -Source $squash -Inventory $inventory -LatestTag 'v1.2.10' | + Should -BeExactly 'v1.2.11' + } + + It 'rejects ' -ForEach @( + @{ Name = 'a main that moved'; Change = { $script:main = 'd' * 40 } } + @{ Name = 'a latest tag that is not stable'; Change = { $script:latest = 'v1.2.3-beta1' } } + @{ Name = 'releases without a latest release'; Change = { $script:latest = '' } } + @{ Name = 'an existing tag for the next version'; Change = { $inventory.tags += @{ name = 'v1.2.11'; sha = 'c' * 40 } } } + @{ Name = 'an existing release for the next version'; Change = { + $inventory.releases += @{ tag = 'v1.2.11'; id = 3; draft = $true; prerelease = $false } + } + } + ) { + $script:main = $squash + $script:latest = 'v1.2.10' + & $Change + { Get-LegacyExpectedTag -MainSha $main -Source $squash -Inventory $inventory -LatestTag $latest } | Should -Throw + } +} + +Describe 'Legacy workflow contract' { + It 'invokes the pinned published action with legacy inputs only' { + $workflow | Should -Match 'uses: PSModule/Release-GHRepository@750abed0ecab02394554b610dc3aa191e75e3248' + foreach ($input in "AutoPatching: 'false'", "AutoCleanup: 'false'", "CreateMajorTag: 'false'", + "CreateMinorTag: 'false'", 'PatchLabels: release:patch', "WhatIf: 'false'") { + $workflow | Should -Match ([regex]::Escape($input)) + } + $workflow | Should -Not -Match '(?m)^\s+(Mode|ReleasePlan|DefaultBump):' + (Join-Path $PSScriptRoot '..\.github\auto-release.yml') | Should -Not -Exist + } + + It 'grants contents write only to the publishing job' { + ([regex]::Matches($workflow, 'contents: write')).Count | Should -Be 1 + $publish = $workflow.Substring($workflow.IndexOf(' Publish:'), $workflow.IndexOf(' Verify:') - $workflow.IndexOf(' Publish:')) + $publish | Should -Match 'contents: write' + $workflow | Should -Match '(?m)^permissions: \{\}' + } + + It 'uses only the job token and never persists it outside the publishing job' { + $workflow | Should -Not -Match 'secrets\.' + ([regex]::Matches($workflow, 'persist-credentials: true')).Count | Should -Be 1 + $workflow | Should -Not -Match 'pull_request_target|workflow_dispatch|\bpush:' + } + + It 'shares the candidate lane concurrency group and runs jobs only for legacy cases' { + $workflow | Should -Match '(?m)^ group: Release-GHRepository-Test$' + ([regex]::Matches($workflow, "needs\.Select\.outputs\.caseId != ''")).Count | Should -BeGreaterOrEqual 3 + } + + It 'guards on this repository, a merged Shelly case, and main' { + foreach ($guard in "github.repository == 'PSModule/Release-GHRepository-Test'", + "github.repository_id == '1477027955'", + "github.event.action == 'closed'", 'github.event.pull_request.merged == true', + 'head.repo.id == github.event.pull_request.base.repo.id', 'user.id == 314722336', + "'psmodule-s-shelly[bot]'", "'release-fixture/'") { + $workflow | Should -Match ([regex]::Escape($guard)) + } + } +} diff --git a/fixtures/release-fixture/seed/tests/LegacyCase.psm1 b/fixtures/release-fixture/seed/tests/LegacyCase.psm1 new file mode 100644 index 0000000..42befc3 --- /dev/null +++ b/fixtures/release-fixture/seed/tests/LegacyCase.psm1 @@ -0,0 +1,156 @@ +$script:Repository = 'PSModule/Release-GHRepository-Test' +$script:RepositoryId = 1477027955 +$script:LegacyCandidate = '750abed0ecab02394554b610dc3aa191e75e3248' + +function Get-LegacyFixtureCase { + <# + .SYNOPSIS + Validates a merged Shelly legacy fixture pull request and returns its case. + + .DESCRIPTION + Accepts only the one-step case for the pinned legacy candidate. Any other input throws, so a + caller cannot publish from an ordinary, forked, unverified or widened pull request. + #> + [CmdletBinding()] + [OutputType([PSCustomObject])] + param( + [Parameter(Mandatory)] + [System.Collections.IDictionary] $EventPayload, + + [Parameter(Mandatory)] + [string] $Repository, + + [Parameter(Mandatory)] + [long] $RepositoryId, + + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Commit, + + [Parameter(Mandatory)] + [AllowEmptyCollection()] + [System.Collections.IDictionary[]] $CommitFiles, + + [Parameter(Mandatory)] + [string] $HeadCase, + + [Parameter(Mandatory)] + [string] $SquashCase + ) + + if ($Repository -cne $script:Repository -or $RepositoryId -ne $script:RepositoryId) { + throw "Only [$script:Repository] can publish a legacy fixture." + } + $pullRequest = $EventPayload.pull_request + if ($EventPayload.action -cne 'closed' -or $pullRequest -isnot [System.Collections.IDictionary] -or + $pullRequest.merged -isnot [bool] -or -not $pullRequest.merged -or $pullRequest.base.ref -cne 'main') { + throw 'The legacy fixture requires a merged pull request closed into main.' + } + if ($RepositoryId -le 0 -or $pullRequest.base.repo.id -ne $RepositoryId -or $pullRequest.head.repo.id -ne $RepositoryId -or + $pullRequest.base.repo.full_name -cne $Repository -or $pullRequest.head.repo.full_name -cne $Repository) { + throw 'The pull request head and base must be this repository, by name and numeric ID.' + } + if ($pullRequest.user.id -ne 314722336 -or $pullRequest.user.login -cne 'psmodule-s-shelly[bot]') { + throw 'Only Shelly can open a legacy fixture case.' + } + + $caseRef = [regex]::Match([string] $pullRequest.head.ref, '\Arelease-fixture/([1-9][0-9]*-[1-9][0-9]*)\z') + $squash = [string] $pullRequest.merge_commit_sha + $head = [string] $pullRequest.head.sha + if (-not $caseRef.Success -or $pullRequest.number -le 0 -or $squash -cnotmatch '\A[0-9a-f]{40}\z' -or + $head -cnotmatch '\A[0-9a-f]{40}\z') { + throw 'The case pull request must identify its run, attempt, number, head SHA and squash SHA.' + } + $caseId = $caseRef.Groups[1].Value + + if ($pullRequest.labels -isnot [array]) { throw 'GitHub did not return labels for the pull request.' } + $labels = @($pullRequest.labels | ForEach-Object { $_.name }) + # v2.0.3 also reads unnamespaced labels such as major, breaking, minor, feature and NoRelease. + if ($labels.Count -ne 1 -or $labels[0] -cne 'release:patch') { + throw 'The legacy fixture requires [release:patch] as the only label.' + } + + if ($Commit.sha -cne $squash -or @($Commit.parents).Count -ne 1 -or $Commit.commit.verification.verified -ne $true) { + throw 'The merge commit must be one verified squash commit with a single parent.' + } + $casePath = "tests/cases/$caseId.json" + if ($CommitFiles.Count -ne 1 -or $CommitFiles[0].filename -cne $casePath -or $CommitFiles[0].status -cne 'added') { + throw "The squash commit must add only [$casePath]." + } + + if ($HeadCase -cne $SquashCase) { throw 'The case file differs between the PR head and the squash commit.' } + $case = ConvertFrom-Json -InputObject $SquashCase -AsHashtable -NoEnumerate + if ($case -isnot [System.Collections.IDictionary] -or $case.Count -ne 2 -or $case.scenario -cne 'one-step' -or + $case.candidate -cne $script:LegacyCandidate) { + throw "The case file must be the one-step scenario pinned to [$script:LegacyCandidate]." + } + + [PSCustomObject]@{ + Id = $caseId + Scenario = $case.scenario + Candidate = $case.candidate + PullRequest = [int] $pullRequest.number + Head = $head + Source = $squash + } +} + +function Test-LegacyCase { + <# + .SYNOPSIS + Tells whether a case file pins the published legacy action, so the legacy lane owns the case. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [string] $CaseJson + ) + + try { $case = ConvertFrom-Json -InputObject $CaseJson -AsHashtable -NoEnumerate } catch { return $false } + $case -is [System.Collections.IDictionary] -and $case.candidate -is [string] -and $case.candidate -ceq $script:LegacyCandidate +} + +function Get-LegacyExpectedTag { + <# + .SYNOPSIS + Checks that main is still the squash commit and returns the tag that v2.0.3 must create. + + .DESCRIPTION + The repository also holds candidate releases, so the inventory is not empty. v2.0.3 bumps the patch + number of the latest release, or starts at v0.0.1 when there is none. The new tag must not exist yet. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [string] $MainSha, + + [Parameter(Mandatory)] + [string] $Source, + + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Inventory, + + [AllowEmptyString()] + [string] $LatestTag = '' + ) + + if ($MainSha -cne $Source) { throw "Main moved from [$Source] to [$MainSha]. Do not publish." } + + $expected = if ([string]::IsNullOrEmpty($LatestTag)) { + if (@($Inventory.releases).Count -ne 0) { throw 'The inventory has releases but GitHub reports no latest release.' } + 'v0.0.1' + } else { + $version = [regex]::Match($LatestTag, '\Av([0-9]+)\.([0-9]+)\.([0-9]+)\z') + if (-not $version.Success) { throw "The latest release tag [$LatestTag] is not a stable v.. tag." } + 'v{0}.{1}.{2}' -f $version.Groups[1].Value, $version.Groups[2].Value, ([bigint] $version.Groups[3].Value + 1) + } + if (@($Inventory.tags | Where-Object name -CEQ $expected).Count -ne 0 -or + @($Inventory.releases | Where-Object tag -CEQ $expected).Count -ne 0) { + throw "The tag or release [$expected] already exists. Do not publish." + } + $expected +} + +Export-ModuleMember -Function Get-LegacyFixtureCase, Get-LegacyExpectedTag, Test-LegacyCase + diff --git a/fixtures/release-fixture/seed/tests/ReleaseCase.Tests.ps1 b/fixtures/release-fixture/seed/tests/ReleaseCase.Tests.ps1 new file mode 100644 index 0000000..6a09f12 --- /dev/null +++ b/fixtures/release-fixture/seed/tests/ReleaseCase.Tests.ps1 @@ -0,0 +1,99 @@ +BeforeAll { + Import-Module (Join-Path $PSScriptRoot 'ReleaseCase.psm1') -Force + + $script:caseRoot = $TestDrive + $script:candidate = 'a' * 40 + $script:head = 'b' * 40 + $script:source = 'c' * 40 + $null = New-Item -ItemType Directory -Path (Join-Path $caseRoot 'cases') + $script:descriptor = Join-Path -Path $caseRoot -ChildPath 'cases' -AdditionalChildPath '123-1.json' + Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'FixtureContract.json') -Destination $caseRoot +} + +Describe 'Release fixture case selection' { + BeforeEach { + $script:pr = @{ + number = 5 + user = @{ id = 314722336; login = 'psmodule-s-shelly[bot]' } + base = @{ ref = 'main'; repo = @{ id = 1477027955 } } + head = @{ ref = 'release-fixture/123-1'; sha = $head; repo = @{ id = 1477027955 } } + labels = @(@{ name = 'release:patch' }) + merged_at = '2026-11-29T12:00:00Z' + merge_commit_sha = $source + } + @{ scenario = 'staged'; candidate = $candidate } | ConvertTo-Json | Set-Content -LiteralPath $descriptor + } + + It 'selects the exact candidate and head for a labeled fixture pull request' { + $case = Get-ReleaseFixtureCase -Path $caseRoot -EventName pull_request -Source $source -PullRequests @($pr) + + $case.Id | Should -BeExactly '123-1' + $case.Candidate | Should -BeExactly $candidate + $case.Scenario | Should -BeExactly 'staged' + $case.Head | Should -BeExactly $head + $case.PullRequest | Should -Be 5 + } + + It 'defers a pull request while it waits for its release label' { + $pr.labels = @() + Get-ReleaseFixtureCase -Path $caseRoot -EventName pull_request -Source $source -PullRequests @($pr) | + Should -BeNullOrEmpty + } + + It 'selects a label-free scenario on the opening event' { + @{ scenario = 'missing-decision'; candidate = $candidate } | ConvertTo-Json | Set-Content -LiteralPath $descriptor + $pr.labels = @(@{ name = 'documentation' }) + + $case = Get-ReleaseFixtureCase -Path $caseRoot -EventName pull_request -Source $source -PullRequests @($pr) + $case.Scenario | Should -BeExactly 'missing-decision' + } + + It 'leaves a case pinned to the published legacy action to the legacy lane' { + @{ scenario = 'one-step'; candidate = '750abed0ecab02394554b610dc3aa191e75e3248' } | ConvertTo-Json | Set-Content -LiteralPath $descriptor + + Get-ReleaseFixtureCase -Path $caseRoot -EventName pull_request -Source $source -PullRequests @($pr) | + Should -BeNullOrEmpty + $pr.labels = @(@{ name = 'release:patch' }, @{ name = 'major' }) + Get-ReleaseFixtureCase -Path $caseRoot -EventName push -Source $source -PullRequests @($pr) | + Should -BeNullOrEmpty + } + + It 'does not select a fixture case from a fork' { + $pr.head.repo.id = 42 + Get-ReleaseFixtureCase -Path $caseRoot -EventName pull_request -Source $source -PullRequests @($pr) | + Should -BeNullOrEmpty + } + + It 'rejects a reserved case branch opened by someone other than Shelly' { + $pr.user.id = 42 + { Get-ReleaseFixtureCase -Path $caseRoot -EventName pull_request -Source $source -PullRequests @($pr) } | + Should -Throw '*Shelly*' + } + + It 'rejects a candidate branch instead of a fixed SHA' { + @{ scenario = 'staged'; candidate = 'main' } | ConvertTo-Json | Set-Content -LiteralPath $descriptor + { Get-ReleaseFixtureCase -Path $caseRoot -EventName pull_request -Source $source -PullRequests @($pr) } | + Should -Throw '*candidate SHA*' + } + + It 'selects a case only at its exact squash commit' { + $case = Get-ReleaseFixtureCase -Path $caseRoot -EventName push -Source $source -PullRequests @($pr) + $case.PullRequest | Should -Be 5 + $case.Head | Should -BeExactly $head + + Get-ReleaseFixtureCase -Path $caseRoot -EventName push -Source ('d' * 40) -PullRequests @($pr) | + Should -BeNullOrEmpty + } + + It 'does not reuse a descriptor from main on a maintenance push' { + $pr.head.ref = 'maintenance' + Get-ReleaseFixtureCase -Path $caseRoot -EventName push -Source $source -PullRequests @($pr) | + Should -BeNullOrEmpty + } + + It 'rejects a squash commit whose case no longer has the required label' { + $pr.labels = @(@{ name = 'release:minor' }) + { Get-ReleaseFixtureCase -Path $caseRoot -EventName push -Source $source -PullRequests @($pr) } | + Should -Throw '*release:patch*' + } +} diff --git a/fixtures/release-fixture/seed/tests/ReleaseCase.psm1 b/fixtures/release-fixture/seed/tests/ReleaseCase.psm1 new file mode 100644 index 0000000..9b68586 --- /dev/null +++ b/fixtures/release-fixture/seed/tests/ReleaseCase.psm1 @@ -0,0 +1,92 @@ +function Get-ReleaseFixtureCase { + <# + .SYNOPSIS + Finds the case for a Shelly pull request or its exact squash commit. + #> + [CmdletBinding()] + [OutputType([PSCustomObject])] + param( + [Parameter(Mandatory)] + [string] $Path, + + [Parameter(Mandatory)] + [ValidateSet('pull_request', 'push')] + [string] $EventName, + + [Parameter(Mandatory)] + [ValidatePattern('\A[0-9a-f]{40}\z')] + [string] $Source, + + [Parameter(Mandatory)] + [AllowEmptyCollection()] + [System.Collections.IDictionary[]] $PullRequests + ) + + $associated = @($PullRequests | Where-Object { + $_.base.ref -ceq 'main' -and $_.base.repo.id -eq 1477027955 -and $_.head.repo.id -eq 1477027955 -and + ($EventName -ceq 'pull_request' -or ($_.merged_at -and $_.merge_commit_sha -ceq $Source)) + }) + if ($associated.Count -eq 0) { return } + if ($associated.Count -ne 1) { throw 'Expected one fixture pull request for the run commit.' } + + $pullRequest = $associated[0] + $branch = [string] $pullRequest.head.ref + if (-not $branch.StartsWith('release-fixture/', [StringComparison]::Ordinal)) { return } + if ($pullRequest.user.id -ne 314722336 -or $pullRequest.user.login -cne 'psmodule-s-shelly[bot]') { + throw 'Only Shelly can open an integration case on a release-fixture branch.' + } + + $caseRef = [regex]::Match($branch, '\Arelease-fixture/([1-9][0-9]*-[1-9][0-9]*)\z') + if (-not $caseRef.Success -or $pullRequest.number -le 0 -or $pullRequest.head.sha -cnotmatch '\A[0-9a-f]{40}\z') { + throw 'The case pull request must identify its run, attempt, number, and exact head SHA.' + } + + $caseId = $caseRef.Groups[1].Value + $casePath = Join-Path -Path $Path -ChildPath 'cases' -AdditionalChildPath "$caseId.json" + $file = Get-Item -LiteralPath $casePath -ErrorAction Stop + if ($file.PSIsContainer -or $file.LinkType -or $file.Length -gt 1024) { + throw "Expected a small JSON case file for [$caseId]." + } + $case = Get-Content -LiteralPath $file.FullName -Raw | ConvertFrom-Json -AsHashtable -NoEnumerate + $contract = Get-Content -LiteralPath (Join-Path $Path 'FixtureContract.json') -Raw | ConvertFrom-Json -AsHashtable + if ($contract.schema -ne 2 -or $contract.scenarios -isnot [System.Collections.IDictionary]) { + throw 'The fixture contract must define schema 2 scenarios.' + } + if ($case -isnot [System.Collections.IDictionary] -or $case.Count -ne 2 -or + $case.scenario -isnot [string] -or $case.scenario -cnotin $contract.scenarios.Keys) { + throw "Case [$caseId] must contain a supported scenario and a candidate SHA." + } + if ($case.candidate -isnot [string] -or $case.candidate -cnotmatch '\A[0-9a-f]{40}\z' -or $case.candidate -ceq ('0' * 40)) { + throw "Case [$caseId] must pin a full lowercase candidate SHA." + } + # The published legacy action has no Mode or plan inputs. Legacy-Release-Test.yml owns these cases. + if ($case.candidate -ceq '750abed0ecab02394554b610dc3aa191e75e3248') { return } + if ($EventName -ceq 'push' -and $case.scenario -ceq 'missing-decision') { + throw 'Close the missing-decision pull request without merging it.' + } + + if ($pullRequest.labels -isnot [array]) { throw "GitHub did not return labels for case [$caseId]." } + $labels = @($pullRequest.labels | ForEach-Object { $_.name } | Where-Object { $_ -like 'release:*' }) + $expectedLabel = $contract.scenarios[$case.scenario] + if ($expectedLabel -and $labels.Count -eq 0 -and $EventName -ceq 'pull_request') { + Write-Information "Case [$caseId] is waiting for [$expectedLabel]." -InformationAction Continue + return + } + if ($expectedLabel) { + if ($labels.Count -ne 1 -or $labels[0] -cne $expectedLabel) { + throw "Case [$caseId] requires only the [$expectedLabel] release label." + } + } elseif ($labels.Count -ne 0) { + throw "Case [$caseId] must have no release label." + } + + [PSCustomObject]@{ + Id = $caseId + Scenario = $case.scenario + Candidate = $case.candidate + PullRequest = $pullRequest.number + Head = $pullRequest.head.sha + } +} + +Export-ModuleMember -Function Get-ReleaseFixtureCase diff --git a/fixtures/release-fixture/seed/tests/ReleaseInventory.Tests.ps1 b/fixtures/release-fixture/seed/tests/ReleaseInventory.Tests.ps1 new file mode 100644 index 0000000..e5725f7 --- /dev/null +++ b/fixtures/release-fixture/seed/tests/ReleaseInventory.Tests.ps1 @@ -0,0 +1,57 @@ +BeforeAll { + Import-Module (Join-Path $PSScriptRoot 'ReleaseInventory.psm1') -Force + + $script:oldSource = 'a' * 40 + $script:testedSource = 'b' * 40 + $script:before = @{ + tags = @(@{ name = 'v0.0.1'; sha = $oldSource }) + releases = @(@{ tag = 'v0.0.1'; id = 1; draft = $false; prerelease = $false }) + } + $script:fingerprint = Get-ReleaseInventoryFingerprint -Inventory $before +} + +Describe 'The release fixture inventory oracle' { + It 'accepts an unchanged inventory after a case that must not publish' { + { Assert-ReleaseInventory -Before $fingerprint -After $before -Source $testedSource } | + Should -Not -Throw + } + + It 'detects an unintended tag even when it points to an earlier commit' { + $after = @{ tags = $before.tags + @{ name = 'v0.0.2'; sha = $oldSource }; releases = $before.releases } + { Assert-ReleaseInventory -Before $fingerprint -After $after -Source $testedSource } | + Should -Throw '*inventory changed*' + } + + It 'accepts one stable release and one tag for the tested commit' { + $after = @{ + tags = @(@{ name = 'v0.0.2'; sha = $testedSource }) + $before.tags + releases = @(@{ tag = 'v0.0.2'; id = 2; draft = $false; prerelease = $false }) + $before.releases + } + { Assert-ReleaseInventory -Before $fingerprint -After $after -Source $testedSource -ExpectedTag 'v0.0.2' } | + Should -Not -Throw + } + + It 'rejects a matching version tag at the wrong commit' { + $after = @{ + tags = $before.tags + @{ name = 'v0.0.2'; sha = $oldSource } + releases = $before.releases + @{ tag = 'v0.0.2'; id = 2; draft = $false; prerelease = $false } + } + { Assert-ReleaseInventory -Before $fingerprint -After $after -Source $testedSource -ExpectedTag 'v0.0.2' } | + Should -Throw '*tested commit*' + } + + It 'rejects a reserved tag without a stable release record' { + $after = @{ tags = $before.tags + @{ name = 'v0.0.2'; sha = $testedSource }; releases = $before.releases } + { Assert-ReleaseInventory -Before $fingerprint -After $after -Source $testedSource -ExpectedTag 'v0.0.2' } | + Should -Throw '*stable release record*' + } + + It 'rejects an alias as an unexpected extra write' { + $after = @{ + tags = $before.tags + @(@{ name = 'v0.0.2'; sha = $testedSource }, @{ name = 'v0'; sha = $testedSource }) + releases = $before.releases + @{ tag = 'v0.0.2'; id = 2; draft = $false; prerelease = $false } + } + { Assert-ReleaseInventory -Before $fingerprint -After $after -Source $testedSource -ExpectedTag 'v0.0.2' } | + Should -Throw '*inventory changed*' + } +} diff --git a/fixtures/release-fixture/seed/tests/ReleaseInventory.psm1 b/fixtures/release-fixture/seed/tests/ReleaseInventory.psm1 new file mode 100644 index 0000000..2c76c7e --- /dev/null +++ b/fixtures/release-fixture/seed/tests/ReleaseInventory.psm1 @@ -0,0 +1,79 @@ +function Get-ReleaseInventoryFingerprint { + <# + .SYNOPSIS + Fingerprints the observable tag targets and release identities in an inventory. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Inventory + ) + + $orderedInventory = [ordered]@{ + tags = @( + foreach ($tag in ($Inventory.tags | Sort-Object -Property name -CaseSensitive)) { + if (-not $tag.name -or $tag.sha -cnotmatch '^[0-9a-f]{40}$') { + throw 'GitHub returned an invalid tag in the fixture inventory.' + } + [ordered]@{ name = $tag.name; sha = $tag.sha } + } + ) + releases = @( + foreach ($release in ($Inventory.releases | Sort-Object -Property id)) { + if (-not $release.tag -or $release.id -le 0 -or + $release.draft -isnot [bool] -or $release.prerelease -isnot [bool]) { + throw 'GitHub returned an invalid release in the fixture inventory.' + } + [ordered]@{ tag = $release.tag; id = $release.id; draft = $release.draft; prerelease = $release.prerelease } + } + ) + } + + $json = ConvertTo-Json -InputObject $orderedInventory -Compress -Depth 4 + [Convert]::ToHexString([System.Security.Cryptography.SHA256]::HashData([System.Text.Encoding]::UTF8.GetBytes($json))) +} + +function Assert-ReleaseInventory { + <# + .SYNOPSIS + Verifies that only the expected stable release and exact tag were added. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [string] $Before, + + [Parameter(Mandatory)] + [System.Collections.IDictionary] $After, + + [Parameter(Mandatory)] + [string] $Source, + + [string] $ExpectedTag + ) + + if ($ExpectedTag) { + $tags = @($After.tags | Where-Object name -CEQ $ExpectedTag) + if ($tags.Count -ne 1 -or $tags[0].sha -cne $Source) { + throw "Expected one tag [$ExpectedTag] at the tested commit [$Source]." + } + + $releases = @($After.releases | Where-Object tag -CEQ $ExpectedTag) + if ($releases.Count -ne 1 -or $releases[0].id -le 0 -or + $releases[0].draft -ne $false -or $releases[0].prerelease -ne $false) { + throw "Expected one stable release record for [$ExpectedTag]." + } + + $After = @{ + tags = @($After.tags | Where-Object name -CNE $ExpectedTag) + releases = @($After.releases | Where-Object tag -CNE $ExpectedTag) + } + } + + if ((Get-ReleaseInventoryFingerprint -Inventory $After) -cne $Before) { + throw 'The release or tag inventory changed outside the expected publication.' + } +} + +Export-ModuleMember -Function Get-ReleaseInventoryFingerprint, Assert-ReleaseInventory diff --git a/tests/Get-TestSeedTree.ps1 b/tests/Get-TestSeedTree.ps1 new file mode 100644 index 0000000..3107353 --- /dev/null +++ b/tests/Get-TestSeedTree.ps1 @@ -0,0 +1,24 @@ +function Get-TestSeedTree { + <# + .SYNOPSIS + Describe the trusted seed files as a fixture tree response, using an independent git blob hash. + #> + [OutputType([hashtable])] + [CmdletBinding()] + param() + + $seedPath = Join-Path -Path $PSScriptRoot -ChildPath '..' -AdditionalChildPath 'fixtures', 'release-fixture', 'seed' + $root = (Resolve-Path -LiteralPath $seedPath).Path + $entries = foreach ($file in Get-ChildItem -LiteralPath $root -Recurse -File -Force) { + $bytes = [IO.File]::ReadAllBytes($file.FullName) + $prefix = [Text.Encoding]::ASCII.GetBytes("blob $($bytes.Length)`0") + $hash = [Security.Cryptography.SHA1]::HashData([byte[]] ($prefix + $bytes)) + @{ + type = 'blob' + mode = '100644' + path = [IO.Path]::GetRelativePath($root, $file.FullName).Replace('\', '/') + sha = [Convert]::ToHexString($hash).ToLowerInvariant() + } + } + @{ truncated = $false; tree = @($entries) } +} diff --git a/tests/ReleaseFixture.Tests.ps1 b/tests/ReleaseFixture.Tests.ps1 index ad73127..5b2d887 100644 --- a/tests/ReleaseFixture.Tests.ps1 +++ b/tests/ReleaseFixture.Tests.ps1 @@ -2,6 +2,7 @@ BeforeAll { Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..' -AdditionalChildPath '.github', 'scripts', 'ReleaseFixture.psm1') + . (Join-Path -Path $PSScriptRoot -ChildPath 'Get-TestSeedTree.ps1') $script:candidate = 'a' * 40 $script:headSha = 'b' * 40 @@ -296,6 +297,40 @@ Describe 'Find-ReleaseFixtureReport' { } } +Describe 'Assert-ReleaseFixtureSeed' { + BeforeEach { + $script:fixtureTree = Get-TestSeedTree + Mock Invoke-ReleaseFixtureRequest -ModuleName ReleaseFixture { $script:fixtureTree } + } + + It 'covers the hidden workflow files with the blob SHAs that the fixture API returned' { + # Recorded from the git tree of fixture main d1a37576. This does not use the module or the test helper. + $known = @{ + '.github/workflows/Legacy-Baseline.yml' = '12eeefd061b223e47fc20a88e473cc5fadd2df99' + '.github/workflows/Legacy-Release-Test.yml' = 'cc3390f7937fd5d3de4a31c010811e3331179073' + '.github/workflows/Release-Test.yml' = '3d598ba59a8ef49f7224cfd70339310a2301b286' + } + $seed = InModuleScope ReleaseFixture { Get-ReleaseFixtureSeed } + $seed.Count | Should -Be 14 + foreach ($path in $known.Keys) { + $seed[$path] | Should -BeExactly $known[$path] + } + { Assert-ReleaseFixtureSeed -Main $script:mainSha } | Should -Not -Throw + } + + It 'rejects a fixture file that only differs in letter case' { + $entry = $script:fixtureTree.tree | Where-Object path -CEQ 'tests/FixtureContract.json' + $entry.path = 'tests/fixturecontract.json' + $message = '*missing: tests/FixtureContract.json*unexpected: tests/fixturecontract.json*' + { Assert-ReleaseFixtureSeed -Main $script:mainSha } | Should -Throw $message + } + + It 'rejects a fixture file with another mode' { + $script:fixtureTree.tree[0].mode = '120000' + { Assert-ReleaseFixtureSeed -Main $script:mainSha } | Should -Throw '*drifted*' + } +} + Describe 'Start-ReleaseFixtureCase' { BeforeEach { $script:active = @() @@ -303,11 +338,13 @@ Describe 'Start-ReleaseFixtureCase' { $script:prBody = $null $script:caseWrite = $null $script:contractAtMain = $false + $script:fixtureTree = Get-TestSeedTree Mock Invoke-ReleaseFixtureRequest -ModuleName ReleaseFixture { $effectiveMethod = $Method ?? 'GET' switch ("$effectiveMethod $Path") { "GET $script:fixture" { $script:fixtureRepo + @{ default_branch = 'main' } } + "GET $script:fixture/git/trees/${script:mainSha}?recursive=1" { $script:fixtureTree } "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" { @@ -353,6 +390,36 @@ Describe 'Start-ReleaseFixtureCase' { } } + It 'refuses to write when the trusted fixture files drifted from the seed' { + $script:fixtureTree.tree[0].sha = 'e' * 40 + { Start-ReleaseFixtureCase -Scenario 'staged' -Candidate $script:candidate -CaseId '123-2' } | + Should -Throw '*drifted*' + Should -Invoke -CommandName Invoke-ReleaseFixtureRequest -ModuleName ReleaseFixture -Times 0 -Exactly -ParameterFilter { + $Method -in 'POST', 'PUT' + } + } + + It 'refuses to write when a trusted fixture file is missing' { + $script:fixtureTree.tree = @($script:fixtureTree.tree | Select-Object -Skip 1) + { Start-ReleaseFixtureCase -Scenario 'staged' -Candidate $script:candidate -CaseId '123-2' } | + Should -Throw '*missing*' + Should -Invoke -CommandName Invoke-ReleaseFixtureRequest -ModuleName ReleaseFixture -Times 0 -Exactly -ParameterFilter { + $Method -in 'POST', 'PUT' + } + } + + It 'refuses to write when a seed file was added to the fixture' { + $script:fixtureTree.tree += @{ type = 'blob'; mode = '100644'; path = 'tests/Extra.ps1'; sha = 'e' * 40 } + { Start-ReleaseFixtureCase -Scenario 'staged' -Candidate $script:candidate -CaseId '123-2' } | + Should -Throw '*unexpected*' + } + + It 'ignores runtime case data and files outside the trusted tree' { + $script:fixtureTree.tree += @{ type = 'blob'; mode = '100644'; path = 'tests/cases/122-1.json'; sha = 'e' * 40 } + $script:fixtureTree.tree += @{ type = 'blob'; mode = '100644'; path = 'README.md'; sha = 'e' * 40 } + (Start-ReleaseFixtureCase -Scenario 'staged' -Candidate $script:candidate -CaseId '123-2').number | Should -Be 40 + } + 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 "" diff --git a/tests/ReleaseFixtureMerge.Tests.ps1 b/tests/ReleaseFixtureMerge.Tests.ps1 new file mode 100644 index 0000000..1de20b7 --- /dev/null +++ b/tests/ReleaseFixtureMerge.Tests.ps1 @@ -0,0 +1,690 @@ +#Requires -Version 7.4 + +BeforeAll { + Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..' -AdditionalChildPath '.github', 'scripts', 'ReleaseFixture.psm1') + . (Join-Path -Path $PSScriptRoot -ChildPath 'Get-TestSeedTree.ps1') + + $script:baseline = '750abed0ecab02394554b610dc3aa191e75e3248' + $script:mainSha = 'c' * 40 + $script:head = 'b' * 40 + $script:squash = 'd' * 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-TestCheck { + <# + .SYNOPSIS + Create an anonymous check run. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'In-memory.')] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [string] $Name, + + [Parameter(Mandatory)] + [int] $Suite, + + [Parameter()] + [string] $Status = 'completed', + + [Parameter()] + [AllowNull()] + [string] $Conclusion = 'success' + ) + + @{ + name = $Name + status = $Status + conclusion = $Conclusion + html_url = "$script:fixtureUrl/actions/runs/1/job/$Suite" + head_sha = $script:head + app = @{ id = 15368 } + check_suite = @{ id = $Suite } + } + } + + function New-TestWorkflowRun { + <# + .SYNOPSIS + Create a pull request workflow run for the exact test case. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'In-memory.')] + [OutputType([hashtable])] + param( + [Parameter(Mandatory)] + [int] $Suite, + + [Parameter()] + [string] $Status = 'completed', + + [Parameter()] + [AllowNull()] + [string] $Conclusion = 'success' + ) + + @{ + id = 1000 + $Suite + path = '.github/workflows/Release-Test.yml' + event = 'pull_request' + head_sha = $script:head + head_branch = 'release-fixture/123-1' + status = $Status + conclusion = $Conclusion + check_suite_id = $Suite + html_url = "$script:fixtureUrl/actions/runs/$(1000 + $Suite)" + repository = @{ id = 1477027955 } + head_repository = @{ id = 1477027955 } + pull_requests = @(@{ number = 6 }) + } + } + + function New-TestCheckSet { + <# + .SYNOPSIS + Create the successful required checks for some pull request events. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'In-memory.')] + [OutputType([hashtable[]])] + param( + [Parameter(Mandatory)] + [int[]] $Suite + ) + + foreach ($id in $Suite) { + New-TestCheck -Name 'Select the case and record the inventory' -Suite $id + New-TestCheck -Name 'Test the exact commit' -Suite $id + New-TestCheck -Name 'Verify the fixture result' -Suite $id -Conclusion 'skipped' + } + } +} + +Describe 'Deterministic fixture merge' { + BeforeEach { + $script:calls = @() + $repoInfo = @{ id = 1477027955; full_name = 'PSModule/Release-GHRepository-Test' } + $script:repo = @{ + main = $script:mainSha + checks = @(New-TestCheckSet -Suite 1, 2) + tree = Get-TestSeedTree + runs = @((New-TestWorkflowRun -Suite 1), (New-TestWorkflowRun -Suite 2)) + pull = @{ + state = 'open' + merged = $false + number = 6 + commits = 1 + user = $script:shelly + labels = @(@{ name = 'release:patch' }) + base = @{ ref = 'main'; repo = $repoInfo; sha = $script:mainSha } + head = @{ ref = 'release-fixture/123-1'; repo = $repoInfo; sha = $script:head } + } + commit = @{ + sha = $script:head + parents = @(@{ sha = $script:mainSha }) + files = @(@{ filename = 'tests/cases/123-1.json'; status = 'added' }) + } + payload = @{ scenario = 'one-step'; candidate = $script:baseline } + merge = @{ merged = $true; sha = $script:squash } + close = @{ state = 'closed'; merged = $false } + } + + Mock Invoke-ReleaseFixtureRequest -ModuleName ReleaseFixture { + $effectiveMethod = $Method ?? 'GET' + $script:calls += [pscustomobject] @{ + Method = $effectiveMethod; Path = $Path; Token = $TokenVariable; Body = $Body; Anonymous = [bool] $Anonymous + } + $state = $script:repo + $rest = $Path.Substring($script:fixtureApi.Length) + switch -Regex ("$effectiveMethod $rest") { + '\AGET /pulls/6\z' { return $state.pull } + '\AGET /git/ref/heads/main\z' { return @{ object = @{ type = 'commit'; sha = $state.main } } } + '\AGET /git/trees/(?[0-9a-f]{40})\?recursive=1\z' { return $state.tree } + '\AGET /actions/workflows/Release-Test\.yml/runs\?event=pull_request&head_sha=[0-9a-f]{40}&per_page=100\z' { + return @{ total_count = $state.runs.Count; workflow_runs = @($state.runs) } + } + '\AGET /commits/(?[0-9a-f]{40})/check-runs\?per_page=100\z' { + return @{ total_count = $state.checks.Count; check_runs = @($state.checks) } + } + '\AGET /commits/(?[0-9a-f]{40})\z' { + if ($Matches.sha -ceq $script:squash) { + return @{ + sha = $script:squash + parents = @(@{ sha = $script:mainSha }) + files = @(@{ filename = 'tests/cases/123-1.json'; status = 'added' }) + } + } + return $state.commit + } + '\AGET /contents/tests/cases/123-1\.json\?ref=[0-9a-f]{40}\z' { + $json = ConvertTo-Json -Compress -InputObject $state.payload + return @{ type = 'file'; encoding = 'base64'; content = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($json)) } + } + '\APUT /pulls/6/merge\z' { + $state.pull.state = 'closed' + $state.pull.merged = $true + $state.pull.merge_commit_sha = $script:squash + return $state.merge + } + '\APATCH /pulls/6\z' { + $state.pull.state = 'closed' + return @{ state = $state.close.state; merged = $state.close.merged } + } + default { throw "Unexpected request: $effectiveMethod $Path" } + } + } + } + + Describe 'Get-ReleaseFixtureOpenCase' { + It 'returns the exact case for the approved head' { + $case = Get-ReleaseFixtureOpenCase -PullRequest 6 -ExpectedHead $script:head -Lane Legacy + $case.caseId | Should -BeExactly '123-1' + $case.base | Should -BeExactly $script:mainSha + $case.label | Should -BeExactly 'release:patch' + $case.activity | Should -BeExactly 'labeled' + } + + It 'refuses ' -ForEach @( + @{ Name = 'a stale head'; Setup = { $script:repo.pull.head.sha = '1' * 40 }; Error = '*not the approved head*' } + @{ Name = 'a stale base'; Setup = { $script:repo.main = '2' * 40 }; Error = '*base*stale*' } + @{ Name = 'a merged pull request'; Setup = { $script:repo.pull.merged = $true }; Error = '*not open*' } + @{ + Name = 'a pull request by another user' + Setup = { $script:repo.pull.user = @{ id = 1; login = 'x'; type = 'User' } } + Error = '*opened by Shelly*' + } + @{ Name = 'a missing label'; Setup = { $script:repo.pull.labels = @() }; Error = '*labels must be exactly*' } + @{ Name = 'an extra label'; Setup = { $script:repo.pull.labels += @{ name = 'release:minor' } }; Error = '*labels must be exactly*' } + @{ Name = 'a second commit'; Setup = { $script:repo.pull.commits = 2 }; Error = '*single commit*' } + @{ + Name = 'a changed file list' + Setup = { $script:repo.commit.files += @{ filename = 'README.md'; status = 'added' } } + Error = '*only adds*' + } + @{ Name = 'a head with another parent'; Setup = { $script:repo.commit.parents = @(@{ sha = '3' * 40 }) }; Error = '*only adds*' } + @{ Name = 'a missing-decision case'; Setup = { $script:repo.payload.scenario = 'missing-decision' }; Error = '*closed without merging*' } + ) { + & $Setup + { Get-ReleaseFixtureOpenCase -PullRequest 6 -ExpectedHead $script:head -Lane Legacy } | Should -Throw $Error + } + } + + Describe 'Wait-ReleaseFixtureCheck' { + BeforeEach { + $script:case = @{ + lane = 'Legacy'; head = $script:head; url = "$script:fixtureUrl/pull/6"; label = 'release:patch'; number = 6; caseId = '123-1' + } + } + + It 'passes when both pull request events passed every required check' { + { Wait-ReleaseFixtureCheck -Case $script:case -TimeoutSeconds 1 -PollSeconds 0 } | Should -Not -Throw + } + + It 'needs only one event for a case without a label' { + $script:repo.checks = @(New-TestCheckSet -Suite 1) + $script:case.label = '' + { Wait-ReleaseFixtureCheck -Case $script:case -TimeoutSeconds 1 -PollSeconds 0 } | Should -Not -Throw + } + + It 'fails at once on a check' -ForEach @( + @{ Name = 'failed'; Conclusion = 'failure' } + @{ Name = 'cancelled'; Conclusion = 'cancelled' } + @{ Name = 'timed out'; Conclusion = 'timed_out' } + ) { + $script:repo.checks = @(New-TestCheckSet -Suite 1, 2) + (New-TestCheck -Name 'Extra' -Suite 2 -Conclusion $Conclusion) + { Wait-ReleaseFixtureCheck -Case $script:case -TimeoutSeconds 60 -PollSeconds 0 } | Should -Throw "*concluded $Conclusion*" + } + + It 'times out on a missing event' { + $script:repo.checks = @(New-TestCheckSet -Suite 1) + { Wait-ReleaseFixtureCheck -Case $script:case -TimeoutSeconds 0.2 -PollSeconds 0.05 } | Should -Throw '*1 of 2 complete suites*' + } + + It 'times out on a running check' { + $script:repo.checks = @(New-TestCheckSet -Suite 1, 2) + (New-TestCheck -Name 'Extra' -Suite 2 -Status 'in_progress' -Conclusion $null) + { Wait-ReleaseFixtureCheck -Case $script:case -TimeoutSeconds 0.2 -PollSeconds 0.05 } | Should -Throw '*still running*' + } + + It 'reads check runs without credentials' { + Wait-ReleaseFixtureCheck -Case $script:case -TimeoutSeconds 1 -PollSeconds 0 + $reads = @($script:calls | Where-Object Path -Like '*/check-runs*') + $reads.Count | Should -BeGreaterThan 0 + $reads.Anonymous | Should -Not -Contain $false + } + + It 'rejects a check run for another head' { + $script:repo.checks[0].head_sha = '1' * 40 + { Wait-ReleaseFixtureCheck -Case $script:case -TimeoutSeconds 1 -PollSeconds 0 } | Should -Throw '*not the approved head*' + } + + It 'needs every required job in the same suite' { + $script:repo.checks = @( + New-TestCheck -Name 'Select the case and record the inventory' -Suite 1 + New-TestCheck -Name 'Test the exact commit' -Suite 2 + New-TestCheck -Name 'Select the case and record the inventory' -Suite 3 + New-TestCheck -Name 'Test the exact commit' -Suite 4 + ) + { Wait-ReleaseFixtureCheck -Case $script:case -TimeoutSeconds 0.2 -PollSeconds 0.05 } | Should -Throw '*lacks Test the exact commit*' + } + + It 'does not accept a success from another app' { + $script:repo.checks = @(New-TestCheckSet -Suite 1, 2) + $script:repo.checks[0].app.id = 99 + { Wait-ReleaseFixtureCheck -Case $script:case -TimeoutSeconds 0.2 -PollSeconds 0.05 } | Should -Throw '*missing*' + } + + It 'does not count same-named jobs in a suite of an unrelated workflow' { + $script:repo.checks = @(New-TestCheckSet -Suite 1, 2, 3) + $script:repo.runs = @(New-TestWorkflowRun -Suite 1) + $wait = @{ Case = $script:case; TimeoutSeconds = 0.2; PollSeconds = 0.05 } + { Wait-ReleaseFixtureCheck @wait } | Should -Throw '*1 of 2 successful Release-Test.yml runs*' + } + + It 'does not count a trusted suite that lacks a required job' { + $script:repo.checks = @(New-TestCheckSet -Suite 1) + (New-TestCheck -Name 'Test the exact commit' -Suite 2) + { Wait-ReleaseFixtureCheck -Case $script:case -TimeoutSeconds 0.2 -PollSeconds 0.05 } | Should -Throw '*suite 2 lacks Select the case*' + } + + It 'reads only the exact workflow runs, and reads check runs only after they pass' { + Wait-ReleaseFixtureCheck -Case $script:case -TimeoutSeconds 1 -PollSeconds 0 + $reads = @($script:calls | Where-Object Anonymous) + $runsPath = "$script:fixtureApi/actions/workflows/Release-Test.yml/runs?event=pull_request&head_sha=$script:head&per_page=100" + $reads.Path | Should -Contain $runsPath + $reads[-1].Path | Should -BeLike '*/check-runs?per_page=100' + } + + It 'waits on a running workflow run without reading check runs' { + $script:repo.runs = @((New-TestWorkflowRun -Suite 1), (New-TestWorkflowRun -Suite 2 -Status 'in_progress' -Conclusion $null)) + { Wait-ReleaseFixtureCheck -Case $script:case -TimeoutSeconds 0.2 -PollSeconds 0.05 } | Should -Throw '*still running*' + @($script:calls | Where-Object Path -Like '*/check-runs*').Count | Should -Be 0 + } + + It 'fails at once on a failed workflow run' { + $script:repo.runs = @((New-TestWorkflowRun -Suite 1), (New-TestWorkflowRun -Suite 2 -Conclusion 'failure')) + { Wait-ReleaseFixtureCheck -Case $script:case -TimeoutSeconds 60 -PollSeconds 0 } | Should -Throw '*workflow run 1002 concluded failure*' + } + + It 'rejects a workflow run that is not bound to ' -ForEach @( + @{ Name = 'the workflow file'; Setup = { $script:repo.runs[0].path = '.github/workflows/Other.yml' } } + @{ Name = 'the event'; Setup = { $script:repo.runs[0].event = 'push' } } + @{ Name = 'the head'; Setup = { $script:repo.runs[0].head_sha = '1' * 40 } } + @{ Name = 'the branch'; Setup = { $script:repo.runs[0].head_branch = 'release-fixture/9-9' } } + @{ Name = 'the repository'; Setup = { $script:repo.runs[0].repository.id = 1 } } + @{ Name = 'the head repository'; Setup = { $script:repo.runs[0].head_repository.id = 1 } } + @{ Name = 'the pull request'; Setup = { $script:repo.runs[0].pull_requests = @(@{ number = 7 }) } } + ) { + & $Setup + $wait = @{ Case = $script:case; TimeoutSeconds = 1; PollSeconds = 0 } + { Wait-ReleaseFixtureCheck @wait } | Should -Throw '*not a Release-Test.yml run for pull request #6*' + } + } + + Describe 'Close-ReleaseFixtureCase' { + BeforeEach { + $script:repo.payload.scenario = 'missing-decision' + $script:repo.pull.labels = @() + } + + It 'closes only the validated missing-decision pull request without merging' { + $closed = Close-ReleaseFixtureCase -PullRequest 6 -ExpectedHead $script:head -Confirm:$false + $closed.scenario | Should -BeExactly 'missing-decision' + $writes = @($script:calls | Where-Object Method -NE 'GET') + $writes.Count | Should -Be 1 + $writes[0].Method | Should -BeExactly 'PATCH' + $writes[0].Path | Should -BeExactly "$script:fixtureApi/pulls/6" + $writes[0].Body.Keys | Should -BeExactly 'state' + $writes[0].Body.state | Should -BeExactly 'closed' + } + + It 'refuses without a write' -ForEach @( + @{ Name = 'a stale head'; Setup = { $script:repo.pull.head.sha = '1' * 40 }; Error = '*not the approved head*' } + @{ Name = 'another scenario'; Setup = { $script:repo.payload.scenario = 'preview' }; Error = '*Only a missing-decision*' } + @{ Name = 'a merged pull request'; Setup = { $script:repo.pull.merged = $true }; Error = '*not open*' } + ) { + & $Setup + { Close-ReleaseFixtureCase -PullRequest 6 -ExpectedHead $script:head -Confirm:$false } | Should -Throw $Error + @($script:calls | Where-Object Method -NE 'GET').Count | Should -Be 0 + } + + It 'fails when GitHub reports a merge' { + $script:repo.close = @{ state = 'closed'; merged = $true } + { Close-ReleaseFixtureCase -PullRequest 6 -ExpectedHead $script:head -Confirm:$false } | Should -Throw '*without a merge*' + } + } + + Describe 'Invoke-ReleaseFixtureRun' { + BeforeEach { + $script:order = @() + $script:open = @{ + number = 6; url = 'u'; caseId = '123-1'; scenario = 'one-step'; head = $script:head; candidate = 'c'; event = 'pull_request' + } + Mock Start-ReleaseFixtureCase -ModuleName ReleaseFixture { $script:order += 'start'; $script:open } + Mock Add-ReleaseFixtureLabel -ModuleName ReleaseFixture { $script:order += 'label' } + Mock Wait-ReleaseFixtureReport -ModuleName ReleaseFixture { + $script:order += "report:$($Case.event)" + @{ run = 'https://github.com/PSModule/Release-GHRepository-Test/actions/runs/1'; tag = $null } + } + Mock Merge-ReleaseFixtureCase -ModuleName ReleaseFixture { $script:order += 'merge'; @{ number = 6; event = 'push'; source = 'sq' } } + Mock Close-ReleaseFixtureCase -ModuleName ReleaseFixture { $script:order += 'close' } + } + + It 'opens, verifies the open report, merges the exact head, and verifies the push report' { + $run = Invoke-ReleaseFixtureRun -Scenario one-step -Candidate ('a' * 40) -CaseId '123-1' -Confirm:$false + $script:order -join ',' | Should -BeExactly 'start,label,report:pull_request,merge,report:push' + Should -Invoke Merge-ReleaseFixtureCase -ModuleName ReleaseFixture -Times 1 -Exactly -ParameterFilter { + $PullRequest -ceq '6' -and $ExpectedHead -ceq $script:head -and $Lane -ceq 'Candidate' + } + Should -Invoke Close-ReleaseFixtureCase -ModuleName ReleaseFixture -Times 0 -Exactly + $run.merged.source | Should -BeExactly 'sq' + } + + It 'closes without merging for missing-decision after the open report' { + $script:open.scenario = 'missing-decision' + $run = Invoke-ReleaseFixtureRun -Scenario missing-decision -Candidate ('a' * 40) -CaseId '123-1' -Confirm:$false + $script:order -join ',' | Should -BeExactly 'start,label,report:pull_request,close' + Should -Invoke Merge-ReleaseFixtureCase -ModuleName ReleaseFixture -Times 0 -Exactly + $run.merged | Should -BeNullOrEmpty + } + + It 'does not merge when the open report is missing' { + Mock Wait-ReleaseFixtureReport -ModuleName ReleaseFixture { throw 'No matching pull_request report' } + { Invoke-ReleaseFixtureRun -Scenario one-step -Candidate ('a' * 40) -CaseId '123-1' -Confirm:$false } | Should -Throw '*No matching*' + Should -Invoke Merge-ReleaseFixtureCase -ModuleName ReleaseFixture -Times 0 -Exactly + } + } + + Describe 'Merge-ReleaseFixtureCase' { + It 'binds the squash merge to the approved head and verifies the squash' { + $merged = Merge-ReleaseFixtureCase -PullRequest 6 -ExpectedHead $script:head -Lane Legacy -TimeoutSeconds 1 -PollSeconds 0 -Confirm:$false + $merged.source | Should -BeExactly $script:squash + $merged.parent | Should -BeExactly $script:mainSha + $merged.event | Should -BeExactly 'pull_request' + $merged.activity | Should -BeExactly 'closed' + $writes = @($script:calls | Where-Object Method -NE 'GET') + $writes.Count | Should -Be 1 + $writes[0].Path | Should -BeExactly "$script:fixtureApi/pulls/6/merge" + $writes[0].Body.sha | Should -BeExactly $script:head + $writes[0].Body.merge_method | Should -BeExactly 'squash' + $writes[0].Token | Should -BeExactly 'GH_TOKEN' + } + + It 'does not write when ' -ForEach @( + @{ Name = 'the head is stale'; Setup = { $script:repo.pull.head.sha = '1' * 40 }; Error = '*not the approved head*' } + @{ + Name = 'a check failed' + Setup = { $script:repo.checks += New-TestCheck -Name 'Extra' -Suite 1 -Conclusion 'failure' } + Error = '*concluded failure*' + } + @{ Name = 'a check is missing'; Setup = { $script:repo.checks = @() }; Error = '*did not pass in time*' } + @{ + Name = 'the trusted files drifted' + Setup = { $script:repo.tree.tree[0].sha = 'e' * 40 } + Error = '*do not match the versioned seed*' + } + ) { + & $Setup + $merge = @{ PullRequest = 6; ExpectedHead = $script:head; Lane = 'Legacy'; TimeoutSeconds = 0.2; PollSeconds = 0.05; Confirm = $false } + { Merge-ReleaseFixtureCase @merge } | Should -Throw $Error + @($script:calls | Where-Object Method -NE 'GET').Count | Should -Be 0 + } + + It 'fails visibly when GitHub refuses the merge' { + $script:repo.merge = @{ merged = $false; sha = $null } + { Merge-ReleaseFixtureCase -PullRequest 6 -ExpectedHead $script:head -Lane Legacy -TimeoutSeconds 1 -PollSeconds 0 -Confirm:$false } | + Should -Throw '*did not merge*' + } + + It 'does not write under WhatIf' { + $merge = @{ PullRequest = 6; ExpectedHead = $script:head; Lane = 'Legacy'; TimeoutSeconds = 1; PollSeconds = 0 } + Merge-ReleaseFixtureCase @merge -WhatIf | Should -BeNullOrEmpty + @($script:calls | Where-Object Method -NE 'GET').Count | Should -Be 0 + } + } + + Describe 'Invoke-ReleaseFixture.ps1 RunPair' { + BeforeEach { + $script:summary = Join-Path -Path $TestDrive -ChildPath 'summary.md' + Set-Content -LiteralPath $script:summary -Value '' + $script:pair = { + param($Match) + $case = @{ number = 6; url = 'u'; candidate = 'c'; source = 's'; parent = 'p' } + $item = @{ case = $case; report = @{ run = 'r' }; release = @{ tag = 'v0.0.1' } } + $comparison = @{ match = $Match; rows = @(@{ check = 'x'; value = 'a'; reference = 'b'; match = $Match }) } + @{ legacy = $item; candidate = $item; comparison = $comparison } + } + $script:driver = Join-Path -Path $PSScriptRoot -ChildPath '..' -AdditionalChildPath '.github', 'scripts', 'Invoke-ReleaseFixture.ps1' + $script:dispatch = @{ + GITHUB_EVENT_NAME = 'workflow_dispatch' + GITHUB_REPOSITORY = 'PSModule/Release-GHRepository' + GITHUB_REF = 'refs/heads/main' + GITHUB_RUN_ID = '123' + GITHUB_RUN_ATTEMPT = '2' + GITHUB_STEP_SUMMARY = $script:summary + } + } + + It 'uses distinct case IDs per attempt, passes the resume inputs, and writes the summary' { + $result = & $script:pair $true + Mock Invoke-ReleaseFixturePair -MockWith { $result }.GetNewClosure() + $previous = @{} + try { + foreach ($name in $script:dispatch.Keys) { + $previous[$name] = [Environment]::GetEnvironmentVariable($name) + [Environment]::SetEnvironmentVariable($name, $script:dispatch[$name]) + } + & $script:driver -Mode RunPair -Candidate ('a' * 40) -LegacyPullRequest 6 -LegacyHead ('0' * 40) -Confirm:$false + } finally { + foreach ($name in $previous.Keys) { + [Environment]::SetEnvironmentVariable($name, $previous[$name]) + } + } + Should -Invoke Invoke-ReleaseFixturePair -Times 1 -Exactly -ParameterFilter { + $LegacyCaseId -ceq '123-3' -and $CandidateCaseId -ceq '123-4' -and $LegacyPullRequest -ceq '6' -and $LegacyHead -ceq ('0' * 40) + } + Get-Content -LiteralPath $script:summary -Raw | Should -Match 'Baseline-first pair comparison' + } + + It 'runs only the legacy lane for RunLegacy and points to run-pair' { + $evidence = @{ case = @{ number = 6; url = 'u'; source = 's' }; report = @{ tag = 'v0.0.1' } } + Mock Invoke-ReleaseFixtureLegacy -MockWith { $evidence }.GetNewClosure() + $previous = @{} + try { + foreach ($name in $script:dispatch.Keys) { + $previous[$name] = [Environment]::GetEnvironmentVariable($name) + [Environment]::SetEnvironmentVariable($name, $script:dispatch[$name]) + } + & $script:driver -Mode RunLegacy -LegacyPullRequest 6 -LegacyHead ('0' * 40) -Confirm:$false + } finally { + foreach ($name in $previous.Keys) { + [Environment]::SetEnvironmentVariable($name, $previous[$name]) + } + } + Should -Invoke Invoke-ReleaseFixtureLegacy -Times 1 -Exactly -ParameterFilter { + $CaseId -ceq '123-3' -and $LegacyPullRequest -ceq '6' -and $LegacyHead -ceq ('0' * 40) + } + Get-Content -LiteralPath $script:summary -Raw | Should -Match 'legacy_pr=6' + } + + It 'runs one scenario with the run and attempt as the case ID and writes the summary' { + $result = @{ + case = @{ caseId = '123-2'; scenario = 'one-step'; candidate = 'c' } + merged = @{ source = 'sq' } + pushReport = @{ tag = 'v0.0.1' } + } + Mock Invoke-ReleaseFixtureRun -MockWith { $result }.GetNewClosure() + $previous = @{} + try { + foreach ($name in $script:dispatch.Keys) { + $previous[$name] = [Environment]::GetEnvironmentVariable($name) + [Environment]::SetEnvironmentVariable($name, $script:dispatch[$name]) + } + & $script:driver -Mode Run -Scenario one-step -Candidate ('a' * 40) -Confirm:$false + } finally { + foreach ($name in $previous.Keys) { + [Environment]::SetEnvironmentVariable($name, $previous[$name]) + } + } + Should -Invoke Invoke-ReleaseFixtureRun -Times 1 -Exactly -ParameterFilter { + $CaseId -ceq '123-2' -and $Scenario -ceq 'one-step' -and $Candidate -ceq ('a' * 40) + } + Get-Content -LiteralPath $script:summary -Raw | Should -Match 'Tag: v0.0.1' + } + + It 'writes the full summary and then fails on a mismatch' { + $result = & $script:pair $false + Mock Invoke-ReleaseFixturePair -MockWith { $result }.GetNewClosure() + $previous = @{} + try { + foreach ($name in $script:dispatch.Keys) { + $previous[$name] = [Environment]::GetEnvironmentVariable($name) + [Environment]::SetEnvironmentVariable($name, $script:dispatch[$name]) + } + { & $script:driver -Mode RunPair -Candidate ('a' * 40) -Confirm:$false } | Should -Throw '*do not match*' + } finally { + foreach ($name in $previous.Keys) { + [Environment]::SetEnvironmentVariable($name, $previous[$name]) + } + } + Get-Content -LiteralPath $script:summary -Raw | Should -Match 'MISMATCH' + } + } + + Describe 'Invoke-ReleaseFixturePair' { + BeforeEach { + $script:resume = @{ + Candidate = ('a' * 40); LegacyCaseId = '5-1'; CandidateCaseId = '5-2'; LegacyPullRequest = 6 + LegacyHead = ('0' * 40); Confirm = $false + } + $script:order = @() + Mock Get-ReleaseFixtureOpenCase -ModuleName ReleaseFixture { + $script:order += "open $PullRequest $ExpectedHead $Lane" + @{ number = 6; url = 'u'; scenario = 'one-step'; candidate = '750abed0ecab02394554b610dc3aa191e75e3248' } + } + Mock Assert-ReleaseFixtureRepository -ModuleName ReleaseFixture {} + Mock Assert-ReleaseFixtureEmptyInventory -ModuleName ReleaseFixture {} + Mock Invoke-ReleaseFixtureRequest -ModuleName ReleaseFixture { @() } + Mock Start-ReleaseFixtureLegacyCase -ModuleName ReleaseFixture { + $script:order += "start-legacy $CaseId" + @{ number = 6; url = 'u'; head = 'b' * 40; label = 'release:patch' } + } + Mock Add-ReleaseFixtureLabel -ModuleName ReleaseFixture { $script:order += 'label' } + Mock Merge-ReleaseFixtureCase -ModuleName ReleaseFixture { + $script:order += "merge $Lane $PullRequest $ExpectedHead" + @{ number = $PullRequest; source = 's' * 40; lane = $Lane } + } + Mock Wait-ReleaseFixtureReport -ModuleName ReleaseFixture { + $script:order += 'wait-report' + @{ run = 'https://example.test/run'; tag = 'v0.0.1' } + } + Mock Get-ReleaseFixtureLegacyEvidence -ModuleName ReleaseFixture { + $script:order += "legacy-evidence $PullRequest" + @{ case = @{ number = 6; source = 's' * 40; url = 'u' }; report = @{ tag = 'v0.0.1'; run = 'r' } } + } + Mock Start-ReleaseFixturePairCandidate -ModuleName ReleaseFixture { + $script:order += "start-candidate $LegacyPullRequest $Candidate $CaseId" + @{ number = 9; url = 'u'; head = 'e' * 40; label = 'release:patch' } + } + Mock Get-ReleaseFixturePairEvidence -ModuleName ReleaseFixture { + $script:order += "pair $LegacyPullRequest $CandidatePullRequest" + @{ comparison = @{ match = $true } } + } + } + + It 'runs a new pair in order' { + $result = Invoke-ReleaseFixturePair -Candidate ('a' * 40) -LegacyCaseId '5-1' -CandidateCaseId '5-2' -Confirm:$false + $result.comparison.match | Should -BeTrue + $script:order | Should -Be @( + 'start-legacy 5-1', 'label', "merge Legacy 6 $('b' * 40)", 'wait-report', 'legacy-evidence 6' + "start-candidate 6 $('a' * 40) 5-2", 'label', 'wait-report', "merge Candidate 9 $('e' * 40)", 'pair 6 9' + ) + } + + It 'resumes the exact legacy pull request without opening another' { + $head = '0' * 40 + $lines = @() + $null = Invoke-ReleaseFixturePair -Candidate ('a' * 40) -LegacyCaseId '5-1' -CandidateCaseId '5-2' ` + -LegacyPullRequest 6 -LegacyHead $head -Progress { param($Line) $lines += $Line } -Confirm:$false + $script:order[0] | Should -BeExactly "open 6 $head Legacy" + $script:order | Should -Not -Contain 'start-legacy 5-1' + $script:order | Should -Contain "merge Legacy 6 $head" + Should -Invoke Start-ReleaseFixtureLegacyCase -ModuleName ReleaseFixture -Times 0 -Exactly + } + + It 'refuses a legacy head without its pull request' { + { Invoke-ReleaseFixturePair -Candidate ('a' * 40) -LegacyCaseId '5-1' -CandidateCaseId '5-2' -LegacyHead ('0' * 40) -Confirm:$false } | + Should -Throw '*needs the legacy pull request*' + } + + It 'continues from a verified merged legacy pull request without another merge' { + $null = Invoke-ReleaseFixturePair -Candidate ('a' * 40) -LegacyCaseId '5-1' -CandidateCaseId '5-2' -LegacyPullRequest 6 -Confirm:$false + $script:order | Should -Be @( + 'legacy-evidence 6', "start-candidate 6 $('a' * 40) 5-2", 'label', 'wait-report', "merge Candidate 9 $('e' * 40)", 'pair 6 9' + ) + Should -Invoke Merge-ReleaseFixtureCase -ModuleName ReleaseFixture -Times 1 -Exactly + Should -Invoke Start-ReleaseFixtureLegacyCase -ModuleName ReleaseFixture -Times 0 -Exactly + } + + It 'runs only the legacy lane without a candidate' { + $result = Invoke-ReleaseFixtureLegacy -CaseId '5-1' -Confirm:$false + $result.report.tag | Should -BeExactly 'v0.0.1' + $script:order | Should -Be @('start-legacy 5-1', 'label', "merge Legacy 6 $('b' * 40)", 'wait-report', 'legacy-evidence 6') + } + + It 'refuses a legacy resume that has only one of the pull request and the head' { + { Invoke-ReleaseFixtureLegacy -CaseId '5-1' -LegacyPullRequest 6 -Confirm:$false } | Should -Throw '*both*' + } + It 'refuses a resumed pull request with another scenario' { + Mock Get-ReleaseFixtureOpenCase -ModuleName ReleaseFixture { + @{ number = 6; url = 'u'; scenario = 'preview'; candidate = '750abed0ecab02394554b610dc3aa191e75e3248' } + } + { Invoke-ReleaseFixturePair @script:resume } | + Should -Throw '*one-step*' + Should -Invoke Merge-ReleaseFixtureCase -ModuleName ReleaseFixture -Times 0 -Exactly + } + + It 'refuses a resume when another fixture pull request is open' { + Mock Invoke-ReleaseFixtureRequest -ModuleName ReleaseFixture { + $repo = @{ id = 1477027955; full_name = 'PSModule/Release-GHRepository-Test' } + @(@{ + number = 8 + head = @{ ref = 'release-fixture/9-1'; repo = $repo } + base = @{ ref = 'main'; repo = $repo } + user = @{ id = 314722336; login = 'psmodule-s-shelly[bot]'; type = 'Bot' } + }) + } + { Invoke-ReleaseFixturePair @script:resume } | + Should -Throw '*also open*' + Should -Invoke Merge-ReleaseFixtureCase -ModuleName ReleaseFixture -Times 0 -Exactly + } + } +} + +BeforeDiscovery { + $script:runsBase = '/repos/PSModule/Release-GHRepository-Test/actions/workflows' +} + +Describe 'Anonymous check run reads' { + It 'refuses ' -ForEach @( + @{ Name = 'another path'; Method = 'GET'; Path = '/repos/PSModule/Release-GHRepository-Test/pulls/6' } + @{ Name = 'another repository'; Method = 'GET'; Path = "/repos/PSModule/Other/commits/$('a' * 40)/check-runs?per_page=100" } + @{ Name = 'a write'; Method = 'PUT'; Path = "/repos/PSModule/Release-GHRepository-Test/commits/$('a' * 40)/check-runs?per_page=100" } + @{ Name = 'a patch'; Method = 'PATCH'; Path = "$script:runsBase/Release-Test.yml/runs?event=pull_request&head_sha=$('a' * 40)" } + @{ Name = 'another workflow'; Method = 'GET'; Path = "$script:runsBase/Legacy-Release-Test.yml/runs?head_sha=$('a' * 40)" } + ) { + InModuleScope ReleaseFixture -Parameters @{ Method = $Method; Path = $Path } { + $call = { + Invoke-ReleaseFixtureRequest -Method $Method -Path $Path -Anonymous + } + $call | Should -Throw '*anonymous request may only read*' + } + } + + It 'stops after the per-process budget' { + InModuleScope ReleaseFixture { + $script:anonymousRequests = $anonymousLimit + $path = "/repos/PSModule/Release-GHRepository-Test/commits/$('a' * 40)/check-runs?per_page=100" + { Invoke-ReleaseFixtureRequest -Path $path -Anonymous } | Should -Throw '*budget*' + $script:anonymousRequests = 0 + } + } +} \ No newline at end of file diff --git a/tests/ReleaseFixturePair.Tests.ps1 b/tests/ReleaseFixturePair.Tests.ps1 index fbcfd82..f49ba24 100644 --- a/tests/ReleaseFixturePair.Tests.ps1 +++ b/tests/ReleaseFixturePair.Tests.ps1 @@ -2,6 +2,7 @@ BeforeAll { Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..' -AdditionalChildPath '.github', 'scripts', 'ReleaseFixture.psm1') + . (Join-Path -Path $PSScriptRoot -ChildPath 'Get-TestSeedTree.ps1') $script:baseline = '750abed0ecab02394554b610dc3aa191e75e3248' $script:candidate = 'a' * 40 @@ -131,6 +132,7 @@ Describe 'Baseline-first pair in one fixture repository' { '\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 /git/trees/[0-9a-f]{40}\?recursive=1\z' { return Get-TestSeedTree } '\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] } } }