diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a7be283..47b4b30 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,7 +3,7 @@ # Every job calls Tests/test-local.ps1 for one stage, so `./Tests/test-local.ps1` locally runs the same checks. # The build job (Sampler/ModuleBuilder) produces output///; the Pester jobs test that built # module under both Windows PowerShell 5.1 and PowerShell 7, because the module must work on both. -# Publishing to the PowerShell Gallery is manual for now (see AGENTS.md). No module name is hard-coded here. +# Publishing to the PowerShell Gallery is done by release.yml (see AGENTS.md). No module name is hard-coded here. # # Security note: never interpolate ${{ github.* }} / ${{ matrix.* }} values directly into a # run: script. Pass them through env: instead. diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..4533f7b --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,171 @@ +# Release: publishes the module to the PowerShell Gallery and creates the GitHub Release. +# +# Real release: push a tag v (for example v0.5.0) that points at a commit on master. +# Dry run: "Run workflow" (workflow_dispatch) on any branch. It checks, builds, tests and packages, and then +# stops: nothing is published and no release is created. +# +# What a release does, in order: +# 1. check tag = ModuleVersion in the manifest, CHANGELOG.md has a dated section for the version, the version +# is not on the Gallery yet, and the tagged commit is on master (Build/Get-ReleaseInfo.ps1) +# 2. build build and run every stage of Tests/test-local.ps1 (the same checks as CI, both PowerShell editions) +# 3. package pack the build into a .nupkg, push it to a temporary folder repository and import the saved +# package on both editions (Build/Test-ReleasePackage.ps1) +# 4. publish Publish-PSResource -NupkgPath of that exact .nupkg, after checking its SHA256. Runs in the +# "psgallery" environment, which holds the PSGALLERY_API_KEY secret and should require the owner's +# approval. +# 5. release GitHub Release for the tag, with the CHANGELOG section as its notes +# +# A Gallery version can never be replaced, so everything that can fail is checked before step 4. +# No module name is hard-coded here. +# +# Security note: never interpolate ${{ github.* }} values directly into a run: script. Use env: or the +# default GITHUB_* environment variables instead. + +name: Release + +on: + push: + tags: + - 'v*' + workflow_dispatch: + +permissions: + contents: read + +# Dry runs and tag runs queue separately: a group keeps only one waiting run, so a dry run in the same group +# could cancel a waiting release. +concurrency: + group: release-${{ github.event_name }} + cancel-in-progress: false + +jobs: + build: + name: Check, build and test + runs-on: windows-latest + defaults: + run: + shell: pwsh + + steps: + - name: Checkout Repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + fetch-depth: 0 + + - name: Check the release + run: | + $Params = @{ NotesPath = 'release-notes.md' } + if ($env:GITHUB_EVENT_NAME -eq 'push') { + $Params.Tag = $env:GITHUB_REF_NAME + git merge-base --is-ancestor HEAD origin/master + if ($LASTEXITCODE -ne 0) { throw "Tag $env:GITHUB_REF_NAME does not point at a commit on master." } + } else { + $Params.AllowUnreleased = $true + } + $Info = ./Build/Get-ReleaseInfo.ps1 @Params + $Info | Select-Object ModuleName, Version, Tag, DryRun, NotesSource | Format-List + + - name: Build and test + run: ./Tests/test-local.ps1 + + - name: Package and check the package + run: | + $Release = Join-Path 'output' 'release' + $Package = ./Build/Test-ReleasePackage.ps1 -PackagePath $Release + Move-Item -Path 'release-notes.md' -Destination $Release + $Package | Select-Object ModuleName, Version, Functions, PackageName, PackageSha256 | + ConvertTo-Json | Set-Content -Path (Join-Path $Release 'release.json') + + $Mode = if ($env:GITHUB_EVENT_NAME -eq 'push') { 'Release' } else { 'Dry run (nothing is published)' } + @( + "## $($Package.ModuleName) $($Package.Version)" + '' + "- Mode: $Mode" + "- Commit: $env:GITHUB_SHA" + "- Functions: $($Package.Functions)" + "- Package: $($Package.PackageName), SHA256 $($Package.PackageSha256)" + '' + '### Release notes' + '' + (Get-Content -Path (Join-Path $Release 'release-notes.md') -Raw) + ) | Add-Content -Path $env:GITHUB_STEP_SUMMARY + + - name: Upload Release Artifact + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: release + path: output/release/ + if-no-files-found: error + retention-days: 30 + + publish: + name: Publish to the PowerShell Gallery + if: github.event_name == 'push' + needs: build + runs-on: windows-latest + environment: + name: psgallery + url: https://www.powershellgallery.com/packages/${{ github.event.repository.name }} + defaults: + run: + shell: pwsh + + steps: + # No checkout: this job only handles the files the build job tested. + - name: Download Release Artifact + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: release + path: release + + - name: Publish + env: + PSGALLERY_API_KEY: ${{ secrets.PSGALLERY_API_KEY }} + run: | + if (-not $env:PSGALLERY_API_KEY) { throw 'The PSGALLERY_API_KEY secret is not set in the psgallery environment.' } + $Release = Get-Content -Path 'release/release.json' -Raw | ConvertFrom-Json + if ("v$($Release.Version)" -ne $env:GITHUB_REF_NAME) { + throw "The built version $($Release.Version) does not match tag $env:GITHUB_REF_NAME." + } + # Publish the .nupkg the build job checked, and only if it is byte-for-byte that file + $Package = Join-Path 'release' $Release.PackageName + $Hash = (Get-FileHash -Path $Package -Algorithm SHA256).Hash + if ($Hash -ne $Release.PackageSha256) { + throw "The package hash $Hash does not match the checked package $($Release.PackageSha256)." + } + Publish-PSResource -NupkgPath $Package -Repository PSGallery -ApiKey $env:PSGALLERY_API_KEY + Write-Host "Published $($Release.ModuleName) $($Release.Version) ($($Release.PackageName), SHA256 $Hash)" + + - name: Wait until the Gallery lists the version + run: | + $Release = Get-Content -Path 'release/release.json' -Raw | ConvertFrom-Json + foreach ($Attempt in 1..20) { + $Found = Find-PSResource -Name $Release.ModuleName -Version $Release.Version -Repository PSGallery ` + -ErrorAction SilentlyContinue + if ($Found) { Write-Host "The Gallery lists $($Found.Name) $($Found.Version)"; exit 0 } + Start-Sleep -Seconds 30 + } + # The publish itself succeeded; the Gallery can take longer to validate and index a package. + Write-Warning 'The Gallery does not list the version yet. Check the package page before announcing it.' + + github-release: + name: Create the GitHub Release + if: github.event_name == 'push' + needs: publish + runs-on: ubuntu-latest + permissions: + contents: write + + steps: + - name: Download Release Artifact + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: release + path: release + + - name: Create Release + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + run: gh release create "$GITHUB_REF_NAME" --verify-tag --title "$GITHUB_REF_NAME" --notes-file release/release-notes.md diff --git a/AGENTS.md b/AGENTS.md index 964bbeb..b3c2717 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -62,9 +62,28 @@ Tooling: PowerShell 7 for the build; Pester 5.7.1+, PSScriptAnalyzer, platyPS 0. | PSScriptAnalyzer | Zero analyzer errors in `source/` | | Docs drift | `Build/Update-Help.ps1` leaves no diff | -`.github/workflows/pr-validation.yml` warns when a PR doesn't update `CHANGELOG.md`. Publishing to the PowerShell -Gallery is manual and needs the owner's explicit go: build, then -`Publish-Module -Path output// -NuGetApiKey ` (publish the built folder, not `source/`). +`.github/workflows/pr-validation.yml` warns when a PR doesn't update `CHANGELOG.md`. + +### Releasing + +`.github/workflows/release.yml` publishes to the PowerShell Gallery. A Gallery version can never be replaced, and +every step below needs the owner's explicit go. + +1. Release PR: set `ModuleVersion` in `source/.psd1` (three parts), rename the CHANGELOG's + `## [Unreleased]` notes to `## [] - ` (leave an empty `[Unreleased]` above it) and update + the compare links at the bottom. Merge it. +2. Dry run: run the **Release** workflow by hand (`gh workflow run release.yml`). It checks, builds, tests and + packages, and publishes nothing. Locally: `./Build/Get-ReleaseInfo.ps1`, then `./Tests/test-local.ps1`, then + `./Build/Test-ReleasePackage.ps1`. +3. Tag the merged commit on `master` as `v` and push the tag. The workflow fails before building unless + the tag equals `ModuleVersion`, the CHANGELOG has the dated section, the version is not on the Gallery and the + commit is on `master`. +4. The `publish` job waits for the owner's approval in the `psgallery` environment, which holds the + `PSGALLERY_API_KEY` secret. Agents never see or handle that key. The job publishes the `.nupkg` the package + check tested, after comparing its SHA256. After the publish, the workflow creates the GitHub Release from the + CHANGELOG section. + +If the publish succeeded and a later job failed, re-run only the failed job; never re-run the publish. ## Architecture @@ -142,8 +161,8 @@ Enforced by `.PSScriptAnalyzerSettings.psd1` and `.editorconfig`: | --- | --- | --- | | PowerShell 7.6, Core only | PowerShell 3.0+, runs on 5.1 and 7 | MSPs run it from RMM agents on Windows PowerShell 5.1 | | Sampler `test` task, Pester 6 | `Tests/test-local.ps1`, Pester 5.7 | Must run the suite under Windows PowerShell 5.1 | -| `Tests/Unit/{Module,Public,Private}`, one file per function | Four suite files under `Tests/` | Not split yet | +| `Tests/Unit/{Module,Public,Private}`, one file per function | Four module suite files (plus `Release.Tests.ps1`) under `Tests/` | Not split yet | | `docs/` (help, examples, media) | `Docs/` (platyPS), `Examples/`, `Media/` at the root | `docs/` = `Docs/` on Windows | -| Changelog release task | Release notes by hand | The task cannot parse this CHANGELOG's 4-part versions | +| Changelog release task | `Build/Get-ReleaseInfo.ps1` reads the notes | The task cannot parse this CHANGELOG's 4-part versions | | PlatyPS 1.x → `docs/help` | platyPS 0.14 via `Build/Update-Help.ps1` (+ MAML) | `Get-Help` on 5.1 uses the MAML | -| Tag-driven publish workflow | Manual `Publish-Module` | Owner publishes by hand | +| Sampler `publish` task | `release.yml` with `Publish-PSResource` | Publishes the exact `.nupkg` the package check installed and imported | diff --git a/Build/Get-ReleaseInfo.ps1 b/Build/Get-ReleaseInfo.ps1 new file mode 100644 index 0000000..1777a2e --- /dev/null +++ b/Build/Get-ReleaseInfo.ps1 @@ -0,0 +1,155 @@ +<# +.SYNOPSIS + Checks that the repository is ready to release a version and returns the version and its release notes. + +.DESCRIPTION + Used by .github/workflows/release.yml before anything is built. It fails (throws) unless: + - the tag is v.. and equals the ModuleVersion in the source manifest + - CHANGELOG.md has a dated section for that version: ## [0.5.0] - 2026-01-31 + - the section has text + - that version is not already on the PowerShell Gallery (a published version can never be replaced) + + Without -Tag it is a dry run for the version in the manifest. A dry run only warns when the version is + already on the Gallery, and with -AllowUnreleased it takes the notes from the [Unreleased] section when the + version has no section yet. + + The Gallery check fails when the Gallery cannot be reached: no answer is not treated as "not published". + +.PARAMETER Tag + The git tag being released, for example v0.5.0. Leave empty for a dry run. + +.PARAMETER AllowUnreleased + Dry run only: use the [Unreleased] section when CHANGELOG.md has no section for the version. + +.PARAMETER SkipGalleryCheck + Do not ask the PowerShell Gallery whether the version already exists. + +.PARAMETER NotesPath + Write the release notes (the CHANGELOG section without its heading) to this file. + +.PARAMETER ManifestPath + The source manifest. Defaults to the only .psd1 in source/. + +.PARAMETER ChangelogPath + Defaults to CHANGELOG.md in the repository root. + +.EXAMPLE + ./Build/Get-ReleaseInfo.ps1 -Tag v0.5.0 -NotesPath output/release-notes.md + +.EXAMPLE + ./Build/Get-ReleaseInfo.ps1 -AllowUnreleased -SkipGalleryCheck +#> +[CmdletBinding()] +param( + [string]$Tag, + + [switch]$AllowUnreleased, + + [switch]$SkipGalleryCheck, + + [string]$NotesPath, + + [string]$ManifestPath, + + [string]$ChangelogPath +) + +$ErrorActionPreference = 'Stop' +$RepoRoot = Split-Path -Parent $PSScriptRoot + +if (-not $ManifestPath) { + $Found = @(Get-ChildItem -Path (Join-Path $RepoRoot 'source') -Filter '*.psd1' -File) + if ($Found.Count -ne 1) { throw "Expected one module manifest in source/, found $($Found.Count)." } + $ManifestPath = $Found[0].FullName +} +if (-not $ChangelogPath) { $ChangelogPath = Join-Path $RepoRoot 'CHANGELOG.md' } + +$ModuleName = [IO.Path]::GetFileNameWithoutExtension($ManifestPath) +$Version = [string](Import-PowerShellDataFile -Path $ManifestPath).ModuleVersion +if ($Version -notmatch '^\d+\.\d+\.\d+$') { + throw "ModuleVersion '$Version' in the manifest must have three parts (major.minor.patch)." +} + +if ($Tag) { + if ($AllowUnreleased) { throw '-AllowUnreleased is for dry runs only; do not combine it with -Tag.' } + if ($Tag -notmatch '^v\d+\.\d+\.\d+$') { throw "Tag '$Tag' must look like v1.2.3." } + if ($Tag -ne "v$Version") { + throw "Tag '$Tag' does not match ModuleVersion '$Version' in the manifest. Fix the manifest or the tag." + } +} + +# Split the changelog into sections by their '## [name]' headings +$Lines = @(Get-Content -Path $ChangelogPath) +$Sections = [ordered]@{} +$Current = $null +foreach ($Line in $Lines) { + if ($Line -match '^## \[(?[^\]]+)\](?.*)$') { + $Current = $Matches.Name + $Sections[$Current] = @{ + Heading = $Line + Rest = $Matches.Rest + Body = New-Object System.Collections.Generic.List[string] + } + } elseif ($Line -match '^\[[^\]]+\]:\s') { + $Current = $null # link definitions at the end of the file + } elseif ($Current) { + $Sections[$Current].Body.Add($Line) + } +} + +$NotesSource = $Version +if ($Sections.Contains($Version)) { + if ($Sections[$Version].Rest -notmatch '^ - \d{4}-\d{2}-\d{2}\s*$') { + throw "CHANGELOG heading '$($Sections[$Version].Heading)' needs a date: ## [$Version] - yyyy-MM-dd" + } +} elseif (-not $Tag -and $AllowUnreleased -and $Sections.Contains('Unreleased')) { + $NotesSource = 'Unreleased' +} else { + throw "CHANGELOG.md has no '## [$Version] - yyyy-MM-dd' section. Move the [Unreleased] notes under it first." +} + +$Notes = ($Sections[$NotesSource].Body -join "`n").Trim() +if (-not $Notes) { throw "CHANGELOG section [$NotesSource] is empty." } + +$AlreadyPublished = $null +if (-not $SkipGalleryCheck) { + # Ask the Gallery for this exact package version: 200 = it exists (unlisted versions too), 404 = it does not. + # Any other answer, or none, fails the check instead of counting as "not published". + [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 3072 + $Uri = "https://www.powershellgallery.com/api/v2/Packages(Id='$ModuleName',Version='$Version')" + try { + Invoke-WebRequest -Uri $Uri -UseBasicParsing | Out-Null + $AlreadyPublished = $true + } catch { + $Status = 0 + if ($_.Exception.Response) { $Status = [int]$_.Exception.Response.StatusCode } + if ($Status -ne 404) { + throw ("Could not check the PowerShell Gallery for $ModuleName $Version (HTTP $Status): " + + $_.Exception.Message) + } + $AlreadyPublished = $false + } + if ($AlreadyPublished) { + $Message = "$ModuleName $Version is already on the PowerShell Gallery. A version cannot be replaced; " + + 'raise ModuleVersion for the next release.' + if ($Tag) { throw $Message } + Write-Warning $Message + } +} + +if ($NotesPath) { + $NotesFolder = Split-Path -Parent $NotesPath + if ($NotesFolder -and -not (Test-Path $NotesFolder)) { New-Item -ItemType Directory -Path $NotesFolder | Out-Null } + [IO.File]::WriteAllText($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($NotesPath), + $Notes + "`n", (New-Object System.Text.UTF8Encoding($false))) +} + +[pscustomobject]@{ + ModuleName = $ModuleName + Version = $Version + Tag = "v$Version" + DryRun = -not $Tag + NotesSource = $NotesSource + AlreadyPublished = $AlreadyPublished + Notes = $Notes +} diff --git a/Build/Test-ReleasePackage.ps1 b/Build/Test-ReleasePackage.ps1 new file mode 100644 index 0000000..e2b391a --- /dev/null +++ b/Build/Test-ReleasePackage.ps1 @@ -0,0 +1,128 @@ +<# +.SYNOPSIS + Builds the package the PowerShell Gallery will receive and checks that it installs. + +.DESCRIPTION + Used by .github/workflows/release.yml after the build and the tests, and safe to run locally. It: + 1. packs the built module (output///) into a .nupkg in a temporary folder repository + 2. pushes that .nupkg to a second temporary repository with Publish-PSResource -NupkgPath, the same call + the workflow uses for the real publish + 3. saves the package from the second repository, as Install-Module would + 4. imports the saved copy in PowerShell 7 and in Windows PowerShell 5.1 and checks the version, the number + of exported functions and that the import shows no warnings + + With -PackagePath the checked .nupkg is copied there, so the workflow can publish that exact file. + Nothing leaves the machine. Needs PowerShell 7 with Microsoft.PowerShell.PSResourceGet 1.1.0 or newer. + +.PARAMETER Version + The version that must have been built. Defaults to the newest build under output/. + +.PARAMETER PackagePath + Folder to copy the checked .nupkg to. Created when missing. + +.EXAMPLE + ./Tests/test-local.ps1 -Stage Build; ./Build/Test-ReleasePackage.ps1 +#> +[CmdletBinding()] +param( + [string]$Version, + + [string]$PackagePath +) + +$ErrorActionPreference = 'Stop' +$RepoRoot = Split-Path -Parent $PSScriptRoot + +if (-not (Get-Command Publish-PSResource -ErrorAction SilentlyContinue).Parameters.ContainsKey('NupkgPath')) { + throw 'Publish-PSResource -NupkgPath is not available. Update Microsoft.PowerShell.PSResourceGet to 1.1.0 or newer.' +} + +$SourceManifest = @(Get-ChildItem -Path (Join-Path $RepoRoot 'source') -Filter '*.psd1' -File) +if ($SourceManifest.Count -ne 1) { throw "Expected one module manifest in source/, found $($SourceManifest.Count)." } +$ModuleName = $SourceManifest[0].BaseName + +$Built = Get-ChildItem -Path (Join-Path $RepoRoot "output/$ModuleName") -Filter "$ModuleName.psd1" -Recurse -File ` + -ErrorAction SilentlyContinue | Sort-Object { [version]$_.Directory.Name } -Descending +if ($Version) { $Built = $Built | Where-Object { $_.Directory.Name -eq $Version } } +$Built = $Built | Select-Object -First 1 +if (-not $Built) { + throw "No built module found under output/$ModuleName. Run ./Tests/test-local.ps1 -Stage Build first." +} + +$Manifest = Import-PowerShellDataFile -Path $Built.FullName +$Version = [string]$Manifest.ModuleVersion +$FunctionCount = @($Manifest.FunctionsToExport).Count +if ($Built.Directory.Name -ne $Version) { + throw "Built folder '$($Built.Directory.Name)' does not match ModuleVersion '$Version' in its manifest." +} + +$Work = Join-Path ([IO.Path]::GetTempPath()) ('release-check-' + [guid]::NewGuid().ToString('N')) +$PackFeed = Join-Path $Work 'pack' +$PushFeed = Join-Path $Work 'push' +$Saved = Join-Path $Work 'saved' +New-Item -ItemType Directory -Path $PackFeed, $PushFeed, $Saved | Out-Null +$Suffix = [guid]::NewGuid().ToString('N').Substring(0, 8) +$PackRepository = "ReleasePack$Suffix" +$PushRepository = "ReleasePush$Suffix" + +Register-PSResourceRepository -Name $PackRepository -Uri $PackFeed -Trusted +Register-PSResourceRepository -Name $PushRepository -Uri $PushFeed -Trusted +try { + Publish-PSResource -Path $Built.Directory.FullName -Repository $PackRepository + $Package = Get-ChildItem -Path $PackFeed -Filter '*.nupkg' -File | Select-Object -First 1 + if (-not $Package) { throw 'Publish-PSResource produced no .nupkg in the temporary repository.' } + if ($Package.Name -ne "$ModuleName.$Version.nupkg") { throw "Unexpected package name '$($Package.Name)'." } + $PackageHash = (Get-FileHash -Path $Package.FullName -Algorithm SHA256).Hash + + Publish-PSResource -NupkgPath $Package.FullName -Repository $PushRepository + Save-PSResource -Name $ModuleName -Version $Version -Repository $PushRepository -Path $Saved -TrustRepository + $SavedManifest = Join-Path $Saved "$ModuleName/$Version/$ModuleName.psd1" + if (-not (Test-Path $SavedManifest)) { throw "The saved package has no manifest at $SavedManifest." } + + # Runs in a fresh process of each edition; prints one line that is compared below + $Check = @' +$ErrorActionPreference = 'Stop' +$Warnings = @() +$Module = Import-Module '{0}' -PassThru -WarningVariable Warnings -WarningAction SilentlyContinue +'RESULT version={{0}} functions={{1}} aliases={{2}} warnings={{3}}' -f $Module.Version, $Module.ExportedFunctions.Count, + $Module.ExportedAliases.Count, $Warnings.Count +'@ -f $SavedManifest.Replace("'", "''") + $Expected = "RESULT version=$Version functions=$FunctionCount aliases=0 warnings=0" + + $Shells = @((Get-Process -Id $PID).Path) + $Desktop = Get-Command powershell.exe -ErrorAction SilentlyContinue + if ($Desktop) { + $Shells += $Desktop.Source + } else { + Write-Warning 'powershell.exe not found; Windows PowerShell 5.1 not checked.' + } + foreach ($Shell in $Shells) { + $Output = @(& $Shell -NoProfile -NonInteractive -Command $Check 2>&1 | ForEach-Object { "$_" }) + $Result = $Output | Where-Object { $_ -like 'RESULT *' } | Select-Object -Last 1 + if ($LASTEXITCODE -ne 0 -or $Result -ne $Expected) { + throw "Package check failed in $Shell.`nExpected: $Expected`nGot: $($Output -join "`n")" + } + Write-Host "$([IO.Path]::GetFileNameWithoutExtension($Shell)): $Result" + } + + $CopiedPackage = $null + if ($PackagePath) { + if (-not (Test-Path $PackagePath)) { New-Item -ItemType Directory -Path $PackagePath | Out-Null } + $CopiedPackage = (Copy-Item -Path $Package.FullName -Destination $PackagePath -PassThru).FullName + if ((Get-FileHash -Path $CopiedPackage -Algorithm SHA256).Hash -ne $PackageHash) { + throw "The copy of the package at $CopiedPackage does not match the checked package." + } + } + + [pscustomobject]@{ + ModuleName = $ModuleName + Version = $Version + Functions = $FunctionCount + PackageName = $Package.Name + PackageSha256 = $PackageHash + PackageFile = $CopiedPackage + } +} finally { + Unregister-PSResourceRepository -Name $PackRepository, $PushRepository -ErrorAction SilentlyContinue + Remove-Item -Path $Work -Recurse -Force -ErrorAction SilentlyContinue +} diff --git a/CHANGELOG.md b/CHANGELOG.md index 208923a..3f92d82 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -92,6 +92,10 @@ Details are in the sections below. - CI moved from AppVeyor to GitHub Actions (`.github/workflows/ci.yml`): Pester on PowerShell 7 and Windows PowerShell 5.1, PSScriptAnalyzer, `Test-ModuleManifest` and a docs-drift check. `Tests/test-local.ps1` runs the same stages locally. `Tests/appveyor.pester.ps1` removed. +- Releases are published by a workflow (`.github/workflows/release.yml`): pushing a tag `v` checks the + tag against the manifest and this changelog, builds, runs every test stage, checks the package installs on + both editions, publishes to the PowerShell Gallery after the owner approves, and creates the GitHub Release. + A manual run is a dry run that publishes nothing. - Repository layout follows the GitHub-Template (Sampler): the module source moved from `ConnectWiseControlAPI/` to `source/` (`Extensions/Remote Workforce` is now `Extensions/RemoteWorkforce`) and `./build.ps1` builds the published module into `output///`. Module-level setup moved from the `.psm1` to diff --git a/Tests/Release.Tests.ps1 b/Tests/Release.Tests.ps1 new file mode 100644 index 0000000..f358691 --- /dev/null +++ b/Tests/Release.Tests.ps1 @@ -0,0 +1,188 @@ +# Tests for Build/Get-ReleaseInfo.ps1, the check that runs before the release workflow builds or publishes anything. +# They use a temporary manifest and changelog and never contact the PowerShell Gallery. + +BeforeAll { + $Script:ReleaseInfo = Join-Path (Split-Path -Parent $PSScriptRoot) 'Build/Get-ReleaseInfo.ps1' + $Script:TestManifest = Join-Path $TestDrive 'Sample.psd1' + $Script:TestChangelog = Join-Path $TestDrive 'CHANGELOG.md' + + function Set-TestRelease { + param([string]$Version = '1.2.3', [string[]]$Changelog) + Set-Content -Path $Script:TestManifest -Value "@{ ModuleVersion = '$Version' }" + Set-Content -Path $Script:TestChangelog -Value $Changelog + } + + function Get-TestReleaseInfo { + param([hashtable]$With = @{}, [switch]$GalleryCheck) + $Paths = @{ ManifestPath = $Script:TestManifest; ChangelogPath = $Script:TestChangelog } + & $Script:ReleaseInfo @Paths -SkipGalleryCheck:(-not $GalleryCheck) @With + } + + # A failed web request as Invoke-WebRequest reports it on both editions: an exception with Response.StatusCode + function New-TestWebError { + param([int]$StatusCode) + $Exception = New-Object System.Exception "HTTP $StatusCode" + if ($StatusCode) { + $Response = [pscustomobject]@{ StatusCode = $StatusCode } + $Exception | Add-Member -NotePropertyName Response -NotePropertyValue $Response + } + $Exception + } + + $Script:ReleasedChangelog = @( + '# Changelog' + '' + '## [Unreleased]' + '' + '## [1.2.3] - 2026-01-31' + '' + '### Added' + '' + '- New thing' + '' + '## [1.2.2] - 2025-12-01' + '' + '- Old thing' + '' + '[Unreleased]: https://example.com/compare/v1.2.3...HEAD' + '[1.2.3]: https://example.com/compare/v1.2.2...v1.2.3' + ) + $Script:UnreleasedChangelog = @( + '# Changelog' + '' + '## [Unreleased]' + '' + '- Coming soon' + '' + '## [1.2.2] - 2025-12-01' + '' + '- Old thing' + ) +} + +Describe 'Build/Get-ReleaseInfo.ps1' { + Context 'a tagged release' { + BeforeEach { Set-TestRelease -Changelog $Script:ReleasedChangelog } + + It 'returns the version and only that version''s notes' { + $Info = Get-TestReleaseInfo -With @{ Tag = 'v1.2.3' } + $Info.ModuleName | Should -Be 'Sample' + $Info.Version | Should -Be '1.2.3' + $Info.Tag | Should -Be 'v1.2.3' + $Info.DryRun | Should -BeFalse + $Info.Notes | Should -Match '^### Added' + $Info.Notes | Should -Match 'New thing$' + $Info.Notes | Should -Not -Match 'Old thing|example\.com' + } + + It 'writes the notes to -NotesPath' { + $NotesPath = Join-Path $TestDrive 'notes/release-notes.md' + Get-TestReleaseInfo -With @{ Tag = 'v1.2.3'; NotesPath = $NotesPath } | Out-Null + (Get-Content -Path $NotesPath -Raw).Trim() | Should -Match '^### Added[\s\S]*New thing$' + } + + It 'fails when the tag does not match the manifest version' { + { Get-TestReleaseInfo -With @{ Tag = 'v1.2.4' } } | Should -Throw '*does not match ModuleVersion*' + } + + It 'fails for a tag that is not v..: ' -ForEach @( + @{ Tag = '1.2.3' }, @{ Tag = 'v1.2' }, @{ Tag = 'v1.2.3-beta' }, @{ Tag = 'v1.2.3.0' } + ) { + { Get-TestReleaseInfo -With @{ Tag = $Tag } } | Should -Throw '*must look like v1.2.3*' + } + + It 'refuses -AllowUnreleased together with -Tag' { + { Get-TestReleaseInfo -With @{ Tag = 'v1.2.3'; AllowUnreleased = $true } } | Should -Throw '*dry runs only*' + } + } + + Context 'a changelog that is not ready' { + It 'fails when the version has no section' { + Set-TestRelease -Changelog $Script:UnreleasedChangelog + { Get-TestReleaseInfo -With @{ Tag = 'v1.2.3' } } | Should -Throw '*has no*section*' + } + + It 'fails when the heading has no date' { + Set-TestRelease -Changelog ($Script:ReleasedChangelog -replace '^## \[1\.2\.3\].*$', '## [1.2.3]') + { Get-TestReleaseInfo -With @{ Tag = 'v1.2.3' } } | Should -Throw '*needs a date*' + } + + It 'fails when the section is empty' { + Set-TestRelease -Changelog '## [1.2.3] - 2026-01-31', '', '## [1.2.2] - 2025-12-01', '', '- Old thing' + { Get-TestReleaseInfo -With @{ Tag = 'v1.2.3' } } | Should -Throw '*is empty*' + } + + It 'fails when the manifest version does not have three parts' { + Set-TestRelease -Version '1.2.3.0' -Changelog $Script:ReleasedChangelog + { Get-TestReleaseInfo } | Should -Throw '*three parts*' + } + } + + Context 'a dry run (no tag)' { + It 'uses the version section when it exists' { + Set-TestRelease -Changelog $Script:ReleasedChangelog + $Info = Get-TestReleaseInfo + $Info.DryRun | Should -BeTrue + $Info.NotesSource | Should -Be '1.2.3' + } + + It 'falls back to [Unreleased] only with -AllowUnreleased' { + Set-TestRelease -Changelog $Script:UnreleasedChangelog + { Get-TestReleaseInfo } | Should -Throw '*has no*section*' + $Info = Get-TestReleaseInfo -With @{ AllowUnreleased = $true } + $Info.NotesSource | Should -Be 'Unreleased' + $Info.Notes | Should -Be '- Coming soon' + } + } + + Context 'the PowerShell Gallery check' { + BeforeEach { Set-TestRelease -Changelog $Script:ReleasedChangelog } + + It 'asks for the exact package version and passes when the Gallery answers 404' { + Mock Invoke-WebRequest { throw (New-TestWebError -StatusCode 404) } + $Info = Get-TestReleaseInfo -GalleryCheck -With @{ Tag = 'v1.2.3' } + $Info.AlreadyPublished | Should -BeFalse + Should -Invoke Invoke-WebRequest -Times 1 -Exactly -ParameterFilter { + "$Uri" -like "*Packages(Id='Sample',Version='1.2.3')" + } + } + + It 'fails a tagged release when the version is already published' { + Mock Invoke-WebRequest { [pscustomobject]@{ StatusCode = 200 } } + { Get-TestReleaseInfo -GalleryCheck -With @{ Tag = 'v1.2.3' } } | + Should -Throw '*already on the PowerShell Gallery*' + } + + It 'only warns in a dry run when the version is already published' { + Mock Invoke-WebRequest { [pscustomobject]@{ StatusCode = 200 } } + $Output = @(Get-TestReleaseInfo -GalleryCheck 3>&1) + $Warnings = @($Output | Where-Object { $_ -is [System.Management.Automation.WarningRecord] }) + $Info = $Output | Where-Object { $_ -isnot [System.Management.Automation.WarningRecord] } + "$Warnings" | Should -Match 'already on the PowerShell Gallery' + $Info.AlreadyPublished | Should -BeTrue + } + + It 'fails when the Gallery cannot be reached or answers with an error: ' -ForEach @( + @{ StatusCode = 0 }, @{ StatusCode = 503 } + ) { + Mock Invoke-WebRequest { throw (New-TestWebError -StatusCode $StatusCode) } + $Expected = '*Could not check the PowerShell Gallery*' + { Get-TestReleaseInfo -GalleryCheck -With @{ Tag = 'v1.2.3' } } | Should -Throw $Expected + { Get-TestReleaseInfo -GalleryCheck } | Should -Throw $Expected + } + + It 'does not contact the Gallery with -SkipGalleryCheck' { + Mock Invoke-WebRequest { throw 'must not be called' } + Get-TestReleaseInfo -With @{ Tag = 'v1.2.3' } | Out-Null + Should -Invoke Invoke-WebRequest -Times 0 -Exactly + } + } + + Context 'this repository' { + It 'is releasable as a dry run' { + $Info = & $Script:ReleaseInfo -AllowUnreleased -SkipGalleryCheck + $Info.Version | Should -Match '^\d+\.\d+\.\d+$' + $Info.Notes | Should -Not -BeNullOrEmpty + } + } +}