diff --git a/.github/workflows/Legacy-Baseline.yml b/.github/workflows/Legacy-Baseline.yml new file mode 100644 index 0000000..12eeefd --- /dev/null +++ b/.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/.github/workflows/Legacy-Release-Test.yml b/.github/workflows/Legacy-Release-Test.yml new file mode 100644 index 0000000..0e57b13 --- /dev/null +++ b/.github/workflows/Legacy-Release-Test.yml @@ -0,0 +1,172 @@ +name: Legacy release integration + +on: + pull_request: + branches: [main] + types: [closed] + +permissions: {} + +concurrency: + group: Release-GHRepository-Test-Legacy + queue: max + +jobs: + Select: + name: Verify the merged legacy case + if: >- + ${{ github.repository == 'PSModule/Release-GHRepository-Test-Legacy' + && 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 + 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 an empty inventory + needs: [Select, CI] + if: ${{ needs.CI.outputs.testedSha == needs.Select.outputs.source }} + runs-on: ubuntu-24.04 + permissions: + contents: read + outputs: + before: ${{ steps.gate.outputs.before }} + 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 the release and tag inventory + 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 inventory 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' }} + 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_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/README.md b/README.md index f2ad675..2d07d2a 100644 --- a/README.md +++ b/README.md @@ -22,12 +22,54 @@ Use **Verify the fixture result** or its PR report as the verdict. The overall r Start with `staged` to publish a stable release at fixture `main`. Run `missing-decision` and `configured-default` only when `main` points to a published stable release. After a maintenance merge or a case that did not publish, use another explicit patch case to establish a new baseline. Keep test tags and releases as evidence. Use a new case instead of rerunning a push that already published. +## Legacy baseline + +This layer follows fixture PR #3 and comes before the producer layers and the live comparison. [`Legacy-Baseline.yml`](.github/workflows/Legacy-Baseline.yml) verifies the published v2.0.3 (`750abed0ecab02394554b610dc3aa191e75e3248`) on pull requests with no write token and no release write. It never publishes. + +| Job | Evidence | +| --- | --- | +| `Simulated` | Runs the unchanged `src/main.ps1` from the pinned checkout. A synthetic merged-PR event drives it. `gh` and `git` are doubles that answer the two read calls and record every other call as a write. Tests: [`tests-baseline`](tests-baseline). The real GitHub module supplies `LogGroup`. | +| `WhatIf` | Runs the real composite with `WhatIf: true` and a `contents: read` token. It compares the release and tag inventory before and after. | + +The `Simulated` job covers these scenarios with the legacy inputs (`AutoPatching`, `AutoCleanup` and both alias tags off, `PatchLabels: release:patch`): explicit patch, first stable tag `v0.0.1` and a bump of the latest tag, preview with no writes, the `NoRelease` skip, an unnamespaced `major` label that overrides the patch label, and unmerged or non-main PRs. It also shows what the default inputs do: auto-patching, `release:skip` ignored, alias tags moved with `git tag -f`, and a configuration file that overrides the inputs. + +Known v2.0.3 behavior that the candidate changes on purpose: + +- With `AutoPatching` off (the lane setting) and no deciding label, the "Skipping release creation" branch does not skip. It only leaves its `LogGroup` block, and the script attempts the unchanged version (`v0.0.0` on an empty inventory, or the latest tag again, which `gh` rejects). This is command evidence from the doubles. The released defaults (`AutoPatching` on) patch without a label. The candidate requires a decision. +- `release:skip` is unknown to v2.0.3. With auto-patching on, it still releases. +- The source of a release is the tip of `main` when `gh release create` runs. The doubles cannot show it. Only a hosted write run in the isolated legacy repository can. + +The legacy lane below provides the hosted write evidence: one stable tag at the exact squash commit. The staged plan and the push CI gate exist only in the candidate. No legacy equivalent exists for those cases, so the baseline does not cover them. The doubles prove the logic only. They do not prove GitHub permissions, tag targets or the git push. + +Run the baseline locally with the pinned checkout: + +```powershell +git clone https://github.com/PSModule/Release-GHRepository.git "$env:TEMP/legacy-action" +git -C "$env:TEMP/legacy-action" checkout 750abed0ecab02394554b610dc3aa191e75e3248 +Install-PSResource -Name GitHub, PSSemVer, powershell-yaml -TrustRepository +$env:LEGACY_ACTION_PATH = "$env:TEMP/legacy-action" +Invoke-Pester -Path .\tests-baseline +``` + ## Maintain the suite [`tests/FixtureContract.json`](tests/FixtureContract.json) lists the supported cases and their labels. Shelly opens a same-repository PR from `release-fixture/-` to `main`. It adds `tests/cases/-.json` with `scenario` and `candidate`. On a push, the suite selects a case only from the Shelly PR merged at that commit. Other PRs and pushes run the fixture tests but do not run the action. [`Release-Test.yml`](.github/workflows/Release-Test.yml) checks out the public producer at the exact candidate SHA and runs the local action. Only the Publish job can write fixture tags and releases. Only the Verify job can add reports to the fixture PR. The fixture does not mint or use Shelly's token. Never add app credentials or real release data to this repository. +## Legacy lane + +[`Legacy-Release-Test.yml`](.github/workflows/Legacy-Release-Test.yml) tests the published v2.0.3 composite (`PSModule/Release-GHRepository@750abed0ecab02394554b610dc3aa191e75e3248`) on a real merged pull request. It runs only in the separate repository `PSModule/Release-GHRepository-Test-Legacy`. This repository does not publish through it. The legacy repository is not provisioned yet. + +Requirements for the legacy repository: + +- Create it as a separate repository with exactly the same `main` as this repository at provisioning time. Pin its numeric ID after creation. +- Keep its release and tag inventory empty before the case. The workflow stops if a release or tag exists, or if `main` is not the squash commit. +- Use normal review. Do not merge any other PR while the case runs. `gh release create` tags the current tip of `main`, so a concurrent merge breaks the case. +- Shelly opens `release-fixture/-` with `release:patch` as the only label. v2.0.3 also reads `major`, `breaking`, `minor`, `feature` and `NoRelease`, so any other label fails the case. `Select` also fails if `.github/auto-release.yml` exists at the squash, because v2.0.3 lets that file override the workflow inputs. The PR adds only `tests/cases/-.json` with `{"scenario":"one-step","candidate":"750abed0ecab02394554b610dc3aa191e75e3248"}`. A verified single-parent squash must contain the same file. + +Read-only jobs select the case, test the exact squash commit, and gate on current `main` and the empty inventory. Only `Publish` has `contents: write`. It uses only `GITHUB_TOKEN`, with `AutoPatching`, `AutoCleanup`, and the alias tags turned off. v2.0.3 runs `git push origin --tags`, which fails without credentials, so only `Publish` persists the job token at checkout. `Verify` expects one new stable `v..` release and tag at the squash commit. It reports a schema 2 `release-fixture-result` comment on the PR. + Run the case selection and inventory tests without GitHub credentials: ```powershell diff --git a/tests-baseline/LegacyAction.psm1 b/tests-baseline/LegacyAction.psm1 new file mode 100644 index 0000000..0a1183d --- /dev/null +++ b/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/tests-baseline/LegacyBaseline.Tests.ps1 b/tests-baseline/LegacyBaseline.Tests.ps1 new file mode 100644 index 0000000..1f53761 --- /dev/null +++ b/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/tests/Invoke-LegacyFixture.ps1 b/tests/Invoke-LegacyFixture.ps1 new file mode 100644 index 0000000..946b132 --- /dev/null +++ b/tests/Invoke-LegacyFixture.ps1 @@ -0,0 +1,146 @@ +#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-Legacy' -or $env:GITHUB_EVENT_NAME -cne 'pull_request') { + throw 'This suite runs only for pull requests in PSModule/Release-GHRepository-Test-Legacy.' +} +$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.' } + + $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 (Get-CaseFile -Id $caseId -Ref $squash) + + # 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 + Assert-LegacyPublicationReady -MainSha (Get-MainSha) -Source $env:FIXTURE_SOURCE -Inventory $inventory + if ($env:GITHUB_OUTPUT) { + Add-Content -LiteralPath $env:GITHUB_OUTPUT -Value "before=$(Get-ReleaseInventoryFingerprint -Inventory $inventory)" + } + 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 = Get-LegacyObservedTag -Source $report.source -After $after + 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/tests/LegacyCase.Tests.ps1 b/tests/LegacyCase.Tests.ps1 new file mode 100644 index 0000000..be53277 --- /dev/null +++ b/tests/LegacyCase.Tests.ps1 @@ -0,0 +1,165 @@ +BeforeAll { + Import-Module (Join-Path $PSScriptRoot 'LegacyCase.psm1') -Force + + $script:repository = 'PSModule/Release-GHRepository-Test-Legacy' + $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 = 77 + EventPayload = @{ + action = 'closed' + pull_request = @{ + number = 3 + merged = $true + user = @{ id = 314722336; login = 'psmodule-s-shelly[bot]' } + base = @{ ref = 'main'; repo = @{ id = 77; full_name = $repository } } + head = @{ ref = 'release-fixture/123-1'; sha = 'b' * 40; repo = @{ id = 77; 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 the candidate repository' { + $arguments.Repository = 'PSModule/Release-GHRepository-Test' + { 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 publication gate and verdict' { + It 'requires main at the squash and an empty inventory' { + $empty = @{ tags = @(); releases = @() } + { Assert-LegacyPublicationReady -MainSha $squash -Source $squash -Inventory $empty } | Should -Not -Throw + { Assert-LegacyPublicationReady -MainSha ('d' * 40) -Source $squash -Inventory $empty } | Should -Throw '*moved*' + { Assert-LegacyPublicationReady -MainSha $squash -Source $squash -Inventory @{ + tags = @(@{ name = 'v0.0.1'; sha = $squash }); releases = @() + } } | Should -Throw '*no release or tag*' + } + + Context 'observed tag' { + BeforeEach { + $script:after = @{ + tags = @(@{ name = 'v0.0.1'; sha = $squash }) + releases = @(@{ tag = 'v0.0.1'; id = 9; draft = $false; prerelease = $false }) + } + } + + It 'returns the one stable tag at the squash' { + Get-LegacyObservedTag -Source $squash -After $after | Should -BeExactly 'v0.0.1' + } + + It 'rejects ' -ForEach @( + @{ Name = 'a tag at another commit'; Change = { $after.tags[0].sha = 'd' * 40 } } + @{ Name = 'an alias tag'; Change = { $after.tags += @{ name = 'v0'; sha = $squash } } } + @{ Name = 'a prerelease'; Change = { $after.releases[0].prerelease = $true } } + @{ Name = 'a draft'; Change = { $after.releases[0].draft = $true } } + @{ Name = 'no release'; Change = { $after.releases = @() } } + @{ Name = 'a release for another tag'; Change = { $after.releases[0].tag = 'v0.0.2' } } + ) { + & $Change + { Get-LegacyObservedTag -Source $squash -After $after } | 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 'guards on the exact legacy repository, merged Shelly case, and main' { + foreach ($guard in "github.repository == 'PSModule/Release-GHRepository-Test-Legacy'", + "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/tests/LegacyCase.psm1 b/tests/LegacyCase.psm1 new file mode 100644 index 0000000..c3e51bf --- /dev/null +++ b/tests/LegacyCase.psm1 @@ -0,0 +1,150 @@ +$script:LegacyRepository = 'PSModule/Release-GHRepository-Test-Legacy' +$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:LegacyRepository) { + throw "Only [$script:LegacyRepository] 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 the same legacy 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 Assert-LegacyPublicationReady { + <# + .SYNOPSIS + Verifies that main is still the squash commit and that no release or tag exists yet. + #> + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [string] $MainSha, + + [Parameter(Mandatory)] + [string] $Source, + + [Parameter(Mandatory)] + [System.Collections.IDictionary] $Inventory + ) + + if ($MainSha -cne $Source) { throw "Main moved from [$Source] to [$MainSha]. Do not publish." } + if (@($Inventory.tags).Count -ne 0 -or @($Inventory.releases).Count -ne 0) { + throw 'The legacy repository must have no release or tag before publication.' + } +} + +function Get-LegacyObservedTag { + <# + .SYNOPSIS + Returns the one stable tag that publication added, after checking the whole inventory. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [string] $Source, + + [Parameter(Mandatory)] + [System.Collections.IDictionary] $After + ) + + $tags = @($After.tags) + $releases = @($After.releases) + if ($tags.Count -ne 1 -or $releases.Count -ne 1) { + throw "Expected exactly one new tag and one new release, found [$($tags.Count)] and [$($releases.Count)]." + } + $name = [string] $tags[0].name + if ($name -cnotmatch '\Av[0-9]+\.[0-9]+\.[0-9]+\z' -or $tags[0].sha -cne $Source) { + throw "Expected one stable tag at the squash commit [$Source], found [$name]." + } + if ($releases[0].tag -cne $name -or $releases[0].id -le 0 -or + $releases[0].draft -ne $false -or $releases[0].prerelease -ne $false) { + throw "Expected one stable release for [$name]." + } + $name +} + +Export-ModuleMember -Function Get-LegacyFixtureCase, Assert-LegacyPublicationReady, Get-LegacyObservedTag