From 9f192bd343039fdad5080e2588ac1492ff5e11c3 Mon Sep 17 00:00:00 2001 From: Jeffrey <9938813+Raphire@users.noreply.github.com> Date: Tue, 27 Oct 2026 22:04:03 +0100 Subject: [PATCH] feat: add release preparation workflow and build script for versioned assets (#855) --- .github/workflows/release.yml | 111 ++++++++++++++++++++++++ Scripts/Build-Release.ps1 | 74 ++++++++++++++++ Scripts/Get.ps1 | 3 + Tests/Build-Release.Tests.ps1 | 112 ++++++++++++++++++++++++ Tests/Get-ArchiveHash.Tests.ps1 | 11 +++ Tests/ReleaseWorkflow.Tests.ps1 | 149 ++++++++++++++++++++++++++++++++ 6 files changed, 460 insertions(+) create mode 100644 .github/workflows/release.yml create mode 100644 Scripts/Build-Release.ps1 create mode 100644 Tests/Build-Release.Tests.ps1 create mode 100644 Tests/ReleaseWorkflow.Tests.ps1 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..4a84c5e --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,111 @@ +name: Prepare release assets + +on: + workflow_dispatch: + inputs: + tag: + description: 'New release version and tag (YYYY.MM.DD or YYYY.MM.DD-rN)' + required: true + type: string + +permissions: + contents: read + +concurrency: + group: prepare-release + cancel-in-progress: false + +jobs: + package: + if: github.ref == 'refs/heads/master' + runs-on: windows-latest + timeout-minutes: 20 + permissions: + contents: write + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + RELEASE_TAG: ${{ inputs.tag }} + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + with: + ref: master + persist-credentials: false + + - name: Update source version + shell: powershell + run: | + $ErrorActionPreference = 'Stop' + if ($env:RELEASE_TAG -notmatch '^\d{4}\.\d{2}\.\d{2}(?:-r[1-9]\d*)?$') { throw 'Expected a YYYY.MM.DD tag with an optional -rN revision suffix (positive integer).' } + $null = [datetime]::ParseExact($env:RELEASE_TAG.Substring(0, 10), 'yyyy.MM.dd', [cultureinfo]::InvariantCulture) + gh auth setup-git + if ($LASTEXITCODE -ne 0) { throw 'Unable to configure Git authentication.' } + $existingTag = git ls-remote --tags origin "refs/tags/$env:RELEASE_TAG" + if ($LASTEXITCODE -ne 0) { throw 'Unable to check release tags.' } + if ($existingTag) { throw 'This tag already exists. Use a new release version.' } + $scriptPath = Join-Path $pwd 'Win11Debloat.ps1' + $text = [IO.File]::ReadAllText($scriptPath) + $pattern = '(?m)^\$script:Version = "[^"\r\n]+"\r?$' + if ([regex]::Matches($text, $pattern).Count -ne 1) { throw 'Expected exactly one script version assignment.' } + $text = [regex]::Replace($text, $pattern, ('$script:Version = "' + $env:RELEASE_TAG + '"')) + [IO.File]::WriteAllText($scriptPath, $text, [Text.UTF8Encoding]::new($true)) + + - name: Test the release source + shell: powershell + run: | + $global:LASTEXITCODE = 0 + ./Scripts/Run-Tests.ps1 -Bootstrap + if ($LASTEXITCODE -ne 0) { throw 'Release tests failed.' } + + - name: Commit version and create release tag + shell: powershell + run: | + $ErrorActionPreference = 'Stop' + git config user.name 'github-actions[bot]' + if ($LASTEXITCODE -ne 0) { throw 'Unable to configure commit author.' } + git config user.email '41898282+github-actions[bot]@users.noreply.github.com' + if ($LASTEXITCODE -ne 0) { throw 'Unable to configure commit email.' } + git diff --quiet -- Win11Debloat.ps1 + if ($LASTEXITCODE -eq 1) { + git add -- Win11Debloat.ps1 + if ($LASTEXITCODE -ne 0) { throw 'Unable to stage version update.' } + git commit -m "chore: release $env:RELEASE_TAG" + if ($LASTEXITCODE -ne 0) { throw 'Unable to commit version update.' } + } elseif ($LASTEXITCODE -ne 0) { throw 'Unable to check version changes.' } + git tag $env:RELEASE_TAG + if ($LASTEXITCODE -ne 0) { throw 'Unable to create release tag.' } + git push --atomic origin HEAD:refs/heads/master "refs/tags/$env:RELEASE_TAG" + if ($LASTEXITCODE -ne 0) { throw 'Unable to push version commit and tag. Check branch/tag permissions.' } + + - name: Download committed release source + shell: powershell + run: | + $sourceCommit = git rev-parse HEAD + if ($LASTEXITCODE -ne 0) { throw 'Unable to resolve release commit.' } + curl.exe --fail --location --retry 3 --header "Authorization: Bearer $env:GH_TOKEN" --output source.zip "https://api.github.com/repos/$env:GH_REPO/zipball/$sourceCommit" + if ($LASTEXITCODE -ne 0) { throw 'Unable to download release source.' } + Expand-Archive -LiteralPath source.zip -DestinationPath release-source + + - name: Build release assets + shell: powershell + run: | + $source = @(Get-ChildItem release-source -Directory)[0].FullName + & (Join-Path $source 'Scripts/Build-Release.ps1') -SourcePath $source -Version $env:RELEASE_TAG -OutputDirectory release-assets + + - name: Create draft release + shell: powershell + run: | + gh release create $env:RELEASE_TAG --verify-tag --draft --title "Release $env:RELEASE_TAG" --generate-notes + if ($LASTEXITCODE -ne 0) { throw 'Unable to create draft release.' } + + - name: Upload assets to draft release + shell: powershell + run: | + $ErrorActionPreference = 'Stop' + $releaseJson = gh release view $env:RELEASE_TAG --json isDraft + if ($LASTEXITCODE -ne 0) { throw 'Unable to read release.' } + $release = $releaseJson | ConvertFrom-Json + if (-not $release.isDraft) { throw 'Release was published before preparation finished.' } + gh release upload $env:RELEASE_TAG release-assets/Win11Debloat.zip release-assets/SHA256SUMS release-assets/Get.ps1 + if ($LASTEXITCODE -ne 0) { throw 'Upload failed. Finish the draft manually, or remove the unpublished draft and its tag before retrying.' } + "Prepared $env:RELEASE_TAG. Review its three assets, then publish the draft release." | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Append -Encoding ascii diff --git a/Scripts/Build-Release.ps1 b/Scripts/Build-Release.ps1 new file mode 100644 index 0000000..e6c3cb0 --- /dev/null +++ b/Scripts/Build-Release.ps1 @@ -0,0 +1,74 @@ +<# + .SYNOPSIS + Builds versioned runtime release assets. +#> +[CmdletBinding()] +param( + [Parameter(Mandatory)] + [ValidatePattern('^\d{4}\.\d{2}\.\d{2}(?:-r[1-9]\d*)?$')] + [string]$Version, + [Parameter(Mandatory)] + [string]$OutputDirectory, + [string]$SourcePath = (Split-Path -Parent $PSScriptRoot) +) + +$ErrorActionPreference = 'Stop' +$null = [datetime]::ParseExact($Version.Substring(0, 10), 'yyyy.MM.dd', [cultureinfo]::InvariantCulture) +$outputPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputDirectory) +New-Item -ItemType Directory -Path $outputPath -Force | Out-Null +foreach ($name in 'Win11Debloat.zip', 'SHA256SUMS', 'Get.ps1') { + if (Test-Path -LiteralPath (Join-Path $outputPath $name)) { + throw "Output already exists: $name. Use a fresh output directory." + } +} + +$workPath = Join-Path $outputPath ('staging-' + [guid]::NewGuid().ToString('N')) +$packageName = "Win11Debloat-$Version" +$packagePath = Join-Path $workPath $packageName +$archivePath = Join-Path $outputPath 'Win11Debloat.zip' +$excludedPaths = @( + '.git', '.github', '.gitignore', 'Tests', 'Logs', 'Backups', + 'Scripts/Build-Release.ps1', 'Scripts/Run-Tests.ps1', + 'LastUsedSettings.json', 'Config/LastUsedSettings.json' +) + +# Prune excluded directories before descending, including output staged inside the source tree. +function Copy-ReleaseDirectory([string]$Path, [string]$RelativePath = '') { + foreach ($item in Get-ChildItem -LiteralPath $Path -Force) { + $relativeItemPath = ($RelativePath + '/' + $item.Name).TrimStart('/') + if ($relativeItemPath -in $excludedPaths -or $item.FullName -in @($outputPath, $workPath)) { continue } + $destination = Join-Path $packagePath $relativeItemPath + if ($item.PSIsContainer) { + New-Item -ItemType Directory -Path $destination -Force | Out-Null + Copy-ReleaseDirectory $item.FullName $relativeItemPath + } + else { + Copy-Item -LiteralPath $item.FullName -Destination $destination + } + } +} + +try { + New-Item -ItemType Directory -Path $packagePath -Force | Out-Null + Copy-ReleaseDirectory $SourcePath + $scriptPath = Join-Path $packagePath 'Win11Debloat.ps1' + $text = [IO.File]::ReadAllText($scriptPath) + $versionPattern = '(?m)^\$script:Version = "[^"\r\n]+"\r?$' + if ([regex]::Matches($text, $versionPattern).Count -ne 1) { + throw 'Expected exactly one script version assignment.' + } + $text = [regex]::Replace($text, $versionPattern, ('$script:Version = "' + $Version + '"')) + [IO.File]::WriteAllText($scriptPath, $text, [Text.UTF8Encoding]::new($true)) + + Compress-Archive -LiteralPath $packagePath -DestinationPath $archivePath + $hash = (Get-FileHash -LiteralPath $archivePath -Algorithm SHA256).Hash.ToLowerInvariant() + [IO.File]::WriteAllText((Join-Path $outputPath 'SHA256SUMS'), "$hash Win11Debloat.zip`n", [Text.UTF8Encoding]::new($false)) + Copy-Item -LiteralPath (Join-Path $packagePath 'Scripts/Get.ps1') -Destination (Join-Path $outputPath 'Get.ps1') +} +finally { + # Only remove this invocation's generated staging directory inside the output directory. + $resolvedWorkPath = [IO.Path]::GetFullPath($workPath) + if ($resolvedWorkPath.StartsWith($outputPath.TrimEnd('\') + '\', [StringComparison]::OrdinalIgnoreCase) -and (Test-Path -LiteralPath $resolvedWorkPath)) { + Remove-Item -LiteralPath $resolvedWorkPath -Recurse -Force + } +} diff --git a/Scripts/Get.ps1 b/Scripts/Get.ps1 index 72a8dd3..72684ca 100644 --- a/Scripts/Get.ps1 +++ b/Scripts/Get.ps1 @@ -167,6 +167,9 @@ try { } $sourceUri = $archiveAsset.browser_download_url } + else { + Write-Warning 'This release does not publish both Win11Debloat.zip and SHA256SUMS. Downloading the source archive without SHA-256 verification.' + } } Invoke-RestMethod $sourceUri -OutFile $tempArchivePath } diff --git a/Tests/Build-Release.Tests.ps1 b/Tests/Build-Release.Tests.ps1 new file mode 100644 index 0000000..da8fc97 --- /dev/null +++ b/Tests/Build-Release.Tests.ps1 @@ -0,0 +1,112 @@ +BeforeAll { + $repositoryRoot = Split-Path -Parent $PSScriptRoot + $buildScript = Join-Path $repositoryRoot 'Scripts/Build-Release.ps1' + $releasePath = Join-Path $TestDrive 'release' + $version = '2026.10.22-r2' + $originalScript = [IO.File]::ReadAllBytes((Join-Path $repositoryRoot 'Win11Debloat.ps1')) + Push-Location $TestDrive + try { & $buildScript -SourcePath $repositoryRoot -Version $version -OutputDirectory 'release' } + finally { Pop-Location } + $unpackedPath = Join-Path $TestDrive 'unpacked' + Expand-Archive -LiteralPath (Join-Path $releasePath 'Win11Debloat.zip') -DestinationPath $unpackedPath + $packagePath = Join-Path $unpackedPath "Win11Debloat-$version" +} + +Describe 'Release packaging' { + It 'stamps only the packaged version and preserves runtime resources' { + [IO.File]::ReadAllText((Join-Path $packagePath 'Win11Debloat.ps1')) | Should -Match '\$script:Version = "2026\.10\.22-r2"' + [Convert]::ToBase64String([IO.File]::ReadAllBytes((Join-Path $repositoryRoot 'Win11Debloat.ps1'))) | + Should -BeExactly ([Convert]::ToBase64String($originalScript)) + foreach ($directory in 'Assets', 'Config', 'Regfiles', 'Schemas') { + foreach ($file in Get-ChildItem -LiteralPath (Join-Path $repositoryRoot $directory) -File -Recurse) { + $relativePath = $file.FullName.Substring($repositoryRoot.Length + 1) + if ($relativePath -eq 'Config\LastUsedSettings.json') { continue } + $packagedFile = Join-Path $packagePath $relativePath + Test-Path -LiteralPath $packagedFile | Should -BeTrue -Because $relativePath + (Get-FileHash -LiteralPath $packagedFile).Hash | Should -Be (Get-FileHash -LiteralPath $file.FullName).Hash + } + } + } + + It 'excludes development files and existing user data' { + foreach ($path in 'Tests', '.github', '.git', '.gitignore', 'Logs', 'Backups', 'Scripts/Run-Tests.ps1', 'Scripts/Build-Release.ps1', 'LastUsedSettings.json', 'Config/LastUsedSettings.json') { + Test-Path -LiteralPath (Join-Path $packagePath $path) | Should -BeFalse + } + } + + It 'hashes the final ZIP and publishes the matching launcher' { + $hash = (Get-FileHash -LiteralPath (Join-Path $releasePath 'Win11Debloat.zip')).Hash.ToLowerInvariant() + [IO.File]::ReadAllText((Join-Path $releasePath 'SHA256SUMS')) | Should -BeExactly "$hash Win11Debloat.zip`n" + (Get-FileHash -LiteralPath (Join-Path $releasePath 'Get.ps1')).Hash | + Should -Be (Get-FileHash -LiteralPath (Join-Path $packagePath 'Scripts/Get.ps1')).Hash + } + + It 'includes new files automatically and prunes exclusions and nested output' { + $source = Join-Path $TestDrive 'source-fixture' + foreach ($directory in 'NewRuntime', 'Scripts', 'Tests', '.git', '.github', 'Logs', 'Backups', 'Config') { + New-Item -ItemType Directory -Path (Join-Path $source $directory) -Force | Out-Null + } + Copy-Item -LiteralPath (Join-Path $repositoryRoot 'Win11Debloat.ps1') -Destination $source + Copy-Item -LiteralPath (Join-Path $repositoryRoot 'Scripts/Get.ps1') -Destination (Join-Path $source 'Scripts/Get.ps1') + foreach ($path in 'extra.txt', 'NewRuntime/data.txt', 'Scripts/NewHelper.ps1', 'Tests/test.txt', '.git/config', '.github/workflow.yml', '.gitignore', 'Logs/log.txt', 'Backups/backup.json', 'Scripts/Build-Release.ps1', 'Scripts/Run-Tests.ps1', 'LastUsedSettings.json', 'Config/LastUsedSettings.json') { + Set-Content -LiteralPath (Join-Path $source $path) -Value 'fixture' + } + $output = Join-Path $source 'output' + & $buildScript -SourcePath $source -Version $version -OutputDirectory $output + $extracted = Join-Path $TestDrive 'fixture-extracted' + Expand-Archive -LiteralPath (Join-Path $output 'Win11Debloat.zip') -DestinationPath $extracted + $root = Join-Path $extracted "Win11Debloat-$version" + foreach ($path in 'extra.txt', 'NewRuntime/data.txt', 'Scripts/NewHelper.ps1', 'Scripts/Get.ps1') { + Test-Path -LiteralPath (Join-Path $root $path) | Should -BeTrue + } + foreach ($path in 'Tests', '.git', '.github', '.gitignore', 'Logs', 'Backups', 'Scripts/Build-Release.ps1', 'Scripts/Run-Tests.ps1', 'LastUsedSettings.json', 'Config/LastUsedSettings.json', 'output') { + Test-Path -LiteralPath (Join-Path $root $path) | Should -BeFalse + } + } + + It 'rejects invalid version input and refuses to overwrite output' { + { & $buildScript -Version '../2026' -OutputDirectory (Join-Path $TestDrive 'invalid') } | Should -Throw + { & $buildScript -Version '2026.02.30' -OutputDirectory (Join-Path $TestDrive 'invalid-date') } | Should -Throw + foreach ($invalidVersion in '2026.02.30-r2', '2026.10.22-r0', '2026.10.22-r', '2026.10.22-r2-extra') { + { & $buildScript -Version $invalidVersion -OutputDirectory (Join-Path $TestDrive 'invalid-revision') } | Should -Throw + } + { & $buildScript -Version $version -OutputDirectory $releasePath } | Should -Throw '*Output already exists*' + } +} + +Describe 'Packaged archive through the launcher' { + It 'verifies and really extracts the release to the expected launch path' { + $originalTemp = $env:TEMP + $launcherTemp = Join-Path $TestDrive 'launcher' + New-Item -ItemType Directory -Path $launcherTemp | Out-Null + $env:TEMP = $launcherTemp + $archiveBytes = [IO.File]::ReadAllBytes((Join-Path $releasePath 'Win11Debloat.zip')) + $sumsText = [IO.File]::ReadAllText((Join-Path $releasePath 'SHA256SUMS')) + Mock Clear-Host {} + Mock Read-Host { throw 'Unexpected launcher prompt.' } + Mock Start-Process { throw 'Reached launch with real extraction.' } + Mock Invoke-RestMethod { + if ([string]$Uri -match 'releases/latest$') { + return [pscustomobject]@{ + assets = @( + [pscustomobject]@{ name = 'Win11Debloat.zip'; browser_download_url = 'https://example.invalid/Win11Debloat.zip' } + [pscustomobject]@{ name = 'SHA256SUMS'; browser_download_url = 'https://example.invalid/SHA256SUMS' } + ) + } + } + if ([string]$Uri -match 'SHA256SUMS$') { [IO.File]::WriteAllText($OutFile, $sumsText) } + else { [IO.File]::WriteAllBytes($OutFile, $archiveBytes) } + } + try { + # Stop at the launcher's catch, before its final cleanup; no child process is created. + $ErrorActionPreference = 'Stop' + { & (Join-Path $releasePath 'Get.ps1') -CLI } | Should -Throw '*Reached launch with real extraction*' + $mainScript = Join-Path $launcherTemp 'Win11Debloat/Win11Debloat.ps1' + Test-Path -LiteralPath $mainScript | Should -BeTrue + [IO.File]::ReadAllText($mainScript) | Should -Match '\$script:Version = "2026\.10\.22-r2"' + Test-Path -LiteralPath (Join-Path $launcherTemp 'Win11Debloat/Schemas/MainWindow.xaml') | Should -BeTrue + Should -Invoke Start-Process -Times 1 -Exactly -ParameterFilter { $ArgumentList -like '*Win11Debloat.ps1*' } + } + finally { $env:TEMP = $originalTemp } + } +} diff --git a/Tests/Get-ArchiveHash.Tests.ps1 b/Tests/Get-ArchiveHash.Tests.ps1 index 8560c43..d578f9f 100644 --- a/Tests/Get-ArchiveHash.Tests.ps1 +++ b/Tests/Get-ArchiveHash.Tests.ps1 @@ -174,4 +174,15 @@ Describe 'Launcher archive verification flow' { Should -Invoke Invoke-RestMethod -Times 0 -Exactly -ParameterFilter { $Uri -eq $checksumsUrl -or $Uri -eq $archiveUrl } Should -Invoke Expand-Archive -Times 1 -Exactly } + + It 'downloads the generated source archive when the release has no archive asset' { + $state.Release.assets = @($state.Release.assets | Where-Object { $_.name -ne 'Win11Debloat.zip' }) + $ErrorActionPreference = 'Continue' + + { & $getScriptPath *> $null } | Should -Throw '*reached extraction*' + + Should -Invoke Invoke-RestMethod -Times 1 -Exactly -ParameterFilter { $Uri -eq $zipballUrl } + Should -Invoke Invoke-RestMethod -Times 0 -Exactly -ParameterFilter { $Uri -eq $checksumsUrl -or $Uri -eq $archiveUrl } + Should -Invoke Expand-Archive -Times 1 -Exactly + } } diff --git a/Tests/ReleaseWorkflow.Tests.ps1 b/Tests/ReleaseWorkflow.Tests.ps1 new file mode 100644 index 0000000..cb947f0 --- /dev/null +++ b/Tests/ReleaseWorkflow.Tests.ps1 @@ -0,0 +1,149 @@ +BeforeAll { + $repositoryRoot = Split-Path -Parent $PSScriptRoot + $gitExecutable = (Get-Command git -CommandType Application | Select-Object -First 1).Source + $workflow = Get-Content -LiteralPath (Join-Path $repositoryRoot '.github/workflows/release.yml') -Raw + $workflowBlocks = @([regex]::Matches($workflow, '(?m)^ run: \|\r?\n(?(?: [^\r\n]*(?:\r?\n|$))+)') | ForEach-Object { + [scriptblock]::Create(($_.Groups['body'].Value -replace '(?m)^ ', '')) + }) +} + +Describe 'Release workflow version commit' { + BeforeEach { + $locationPushed = $false + $originalTag = $env:RELEASE_TAG + $originalSummary = $env:GITHUB_STEP_SUMMARY + $originalToken = $env:GH_TOKEN + $testRoot = Join-Path $TestDrive ([guid]::NewGuid().ToString('N')) + $checkoutPath = Join-Path $testRoot 'checkout' + $remotePath = Join-Path $testRoot 'origin.git' + New-Item -ItemType Directory -Path (Join-Path $checkoutPath 'Scripts') -Force | Out-Null + git init --bare --quiet $remotePath + git init --quiet --initial-branch master $checkoutPath + git -C $checkoutPath config user.name 'Release test' + git -C $checkoutPath config user.email 'release-test@example.invalid' + git -C $checkoutPath config commit.gpgsign false + git -C $checkoutPath config tag.gpgsign false + git -C $checkoutPath config core.autocrlf false + [IO.File]::WriteAllText((Join-Path $checkoutPath 'Win11Debloat.ps1'), '$script:Version = "2026.08.24"') + foreach ($name in 'Build-Release.ps1', 'Get.ps1') { + Copy-Item -LiteralPath (Join-Path $repositoryRoot "Scripts/$name") -Destination (Join-Path $checkoutPath "Scripts/$name") + } + [IO.File]::WriteAllText((Join-Path $checkoutPath 'Scripts/Run-Tests.ps1'), @' +param([switch]$Bootstrap) +$text = [IO.File]::ReadAllText((Join-Path $PSScriptRoot '../Win11Debloat.ps1')) +if ($text -notmatch [regex]::Escape($env:RELEASE_TAG)) { throw 'Tests did not see the updated version.' } +'@) + git -C $checkoutPath add . + git -C $checkoutPath commit --quiet -m initial + git -C $checkoutPath remote add origin $remotePath + git -C $checkoutPath push --quiet origin master + if ($LASTEXITCODE -ne 0) { throw 'Unable to prepare isolated Git fixture.' } + $initialCommit = git -C $checkoutPath rev-parse HEAD + $env:RELEASE_TAG = '2026.10.23' + $env:GITHUB_STEP_SUMMARY = Join-Path $testRoot 'summary.txt' + $env:GH_TOKEN = 'release-workflow-test-token' + $script:uploadedFiles = @() + $script:gitAuthenticationConfigured = $false + + function git { + if ($args[0] -eq 'ls-remote' -and -not $script:gitAuthenticationConfigured) { + throw 'Git authentication must be configured before querying remote tags.' + } + & $gitExecutable @args + $global:LASTEXITCODE = $LASTEXITCODE + } + + # Real local Git commits/pushes; all GitHub operations stay inside this fixture. + function gh { + $global:LASTEXITCODE = 0 + if ($args[0] -eq 'auth' -and $args[1] -eq 'setup-git') { + $script:gitAuthenticationConfigured = $true + return + } + if ($args[1] -eq 'create') { return } + if ($args[1] -eq 'view') { return '{"isDraft":true}' } + if ($args[1] -eq 'upload') { + $script:uploadedFiles = @($args | Select-Object -Skip 3) + foreach ($file in $script:uploadedFiles) { + if (-not (Test-Path -LiteralPath $file)) { throw "Missing upload: $file" } + } + return + } + throw 'Unexpected GitHub CLI operation.' + } + function curl.exe { + $headerIndex = [array]::IndexOf($args, '--header') + if ($headerIndex -lt 0 -or $args[$headerIndex + 1] -cne "Authorization: Bearer $env:GH_TOKEN") { + throw 'The source download must authenticate with GH_TOKEN.' + } + $outputIndex = [array]::IndexOf($args, '--output') + 1 + $commit = ($args[-1] -split '/')[-1] + git archive --format=zip --prefix=tagged-source/ -o $args[$outputIndex] $commit + if ($LASTEXITCODE -ne 0) { throw 'Unable to prepare mock source download.' } + } + Push-Location $checkoutPath + $locationPushed = $true + } + + AfterEach { + if ($locationPushed) { Pop-Location } + $env:RELEASE_TAG = $originalTag + $env:GITHUB_STEP_SUMMARY = $originalSummary + $env:GH_TOKEN = $originalToken + } + + It 'commits and packages release version from the same tagged commit' -ForEach @( + @{ ReleaseVersion = '2026.10.23' } + @{ ReleaseVersion = '2026.10.23-r2' } + @{ ReleaseVersion = '2026.10.23-r10' } + ) { + $env:RELEASE_TAG = $ReleaseVersion + foreach ($block in $workflowBlocks) { & $block } + $releaseCommit = git rev-parse HEAD + $releaseCommit | Should -Not -Be $initialCommit + (git --git-dir $remotePath rev-parse refs/heads/master) | Should -Be $releaseCommit + (git --git-dir $remotePath rev-parse "refs/tags/$env:RELEASE_TAG") | Should -Be $releaseCommit + $versionPattern = '\$script:Version = "' + [regex]::Escape($ReleaseVersion) + '"' + (git show HEAD:Win11Debloat.ps1) | Should -Match $versionPattern + $script:uploadedFiles | Should -HaveCount 3 + $summaryBytes = [IO.File]::ReadAllBytes($env:GITHUB_STEP_SUMMARY) + $summaryBytes[0] | Should -Be ([byte][char]'P') + $summaryBytes | Should -Not -Contain 0 + $unpacked = Join-Path $testRoot 'unpacked' + Expand-Archive -LiteralPath release-assets/Win11Debloat.zip -DestinationPath $unpacked + [IO.File]::ReadAllText((Join-Path $unpacked "Win11Debloat-$ReleaseVersion/Win11Debloat.ps1")) | + Should -Match $versionPattern + } + + It 'rejects invalid release version before changing the source' -ForEach @( + @{ InvalidVersion = '2026.02.30-r2' } + @{ InvalidVersion = '2026.10.23-r0' } + @{ InvalidVersion = '2026.10.23-r' } + @{ InvalidVersion = '2026.10.23-r2-extra' } + ) { + $env:RELEASE_TAG = $InvalidVersion + { & $workflowBlocks[0] } | Should -Throw + [IO.File]::ReadAllText((Join-Path $checkoutPath 'Win11Debloat.ps1')) | Should -Match '2026\.08\.24' + } + + It 'does not commit or push a release when tests fail' { + [IO.File]::WriteAllText((Join-Path $checkoutPath 'Scripts/Run-Tests.ps1'), 'exit 1') + { foreach ($block in $workflowBlocks) { & $block } } | Should -Throw '*Release tests failed*' + (git --git-dir $remotePath rev-parse refs/heads/master) | Should -Be $initialCommit + (git ls-remote --tags origin "refs/tags/$env:RELEASE_TAG") | Should -BeNullOrEmpty + } + + It 'clears a stale native exit code before running successful tests' { + & $workflowBlocks[0] + $global:LASTEXITCODE = 7 + { & $workflowBlocks[1] } | Should -Not -Throw + $LASTEXITCODE | Should -Be 0 + } + + It 'rejects an existing tag before modifying the source version' { + git tag $env:RELEASE_TAG + git push --quiet origin "refs/tags/$env:RELEASE_TAG" + { & $workflowBlocks[0] } | Should -Throw '*tag already exists*' + [IO.File]::ReadAllText((Join-Path $checkoutPath 'Win11Debloat.ps1')) | Should -Match '2026\.08\.24' + } +}