diff --git a/.gitattributes b/.gitattributes index e75b066c..a499574a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -29,3 +29,12 @@ packages/cultmesh-ts/native/**/*.so.* binary # ends in `\r`) while CI, checking out on Linux, stays green. packages/cultmesh-ts/native/SHA256SUMS text eol=lf packages/cultmesh-ts/native/MANIFEST.txt text eol=lf + +# CultMath source keeps CRLF in the working tree on every checkout. The release +# gate compares the CultMath.dll it builds with the one org.gamecult.cultmath +# tracks, byte for byte, and the bytes follow the checkout's line endings: the +# pdb's document checksums feed the DLL's pdb id, timestamp and MVID. The +# tracked DLL was built from CRLF source, so CRLF here keeps it valid, and an +# LF-configured or Linux clone builds the same bytes as a Windows one. The index +# stays LF; only the checkout changes. +packages/cultmath/src/** text eol=crlf diff --git a/.github/workflows/publish-packages.yml b/.github/workflows/publish-packages.yml index 1ed1f176..ea38c052 100644 --- a/.github/workflows/publish-packages.yml +++ b/.github/workflows/publish-packages.yml @@ -55,17 +55,12 @@ jobs: node-version: 24.x registry-url: https://registry.npmjs.org - # The suite pins the release checker's rules and the declared tag prefixes - # (docs/semver-policy.md). It runs before any check or publish step, on a - # checkout that holds every tag. + # The release-checks suite, which Publish runs, needs .NET for the API gate. - name: Set up .NET uses: actions/setup-dotnet@v4 with: dotnet-version: 10.0.x - - name: Test the release checks - run: node --test scripts/check-changelog-semver.test.mjs - - name: Install workspace dependencies run: npm ci @@ -92,12 +87,11 @@ jobs: working-directory: packages/cultcache-ts run: npm test - # Scoped packages default to restricted even on public npm, and this is - # MIT like the rest of the repo, so say public explicitly. + # Runs the release-checks suite, then npm publish --access public, in one + # process that publishes only if the suite passed (docs/semver-policy.md). - name: Publish if: startsWith(github.ref, 'refs/tags/cultcache-ts-v') - working-directory: packages/cultcache-ts - run: npm publish --access public + run: node scripts/release-after-suite.mjs npm-publish packages/cultcache-ts env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} @@ -155,11 +149,6 @@ jobs: with: dotnet-version: 10.0.x - # See the same step in the npm job: the suite comes before any check or publish step. - - name: Test the release checks - if: steps.selected.outputs.run == 'true' - run: node --test scripts/check-changelog-semver.test.mjs - - name: Verify the tag matches the manifest version if: steps.selected.outputs.run == 'true' && startsWith(github.ref, 'refs/tags/') run: | @@ -184,14 +173,16 @@ jobs: - name: Install and test if: steps.selected.outputs.run == 'true' run: | - python -m pip install -e packages/cultcache-py -e packages/cultnet-py -e packages/cultmesh-py + python -m pip install --upgrade build -e packages/cultcache-py -e packages/cultnet-py -e packages/cultmesh-py python -m unittest discover -s packages/${{ matrix.package }}/tests + # Runs the release-checks suite, then builds the sdist and wheel, in one + # process that builds only if the suite passed (docs/semver-policy.md). + # Publish uploads only what this step built, so it has nothing to upload + # unless the suite passed. - name: Build sdist and wheel if: steps.selected.outputs.run == 'true' - run: | - python -m pip install --upgrade build - python -m build packages/${{ matrix.package }} + run: node scripts/release-after-suite.mjs python-build packages/${{ matrix.package }} - name: Publish if: steps.selected.outputs.run == 'true' && startsWith(github.ref, 'refs/tags/') diff --git a/docs/semver-policy.md b/docs/semver-policy.md index b40fb3e3..4b7a2028 100644 --- a/docs/semver-policy.md +++ b/docs/semver-policy.md @@ -111,7 +111,7 @@ swap under "Changed" rather than "Breaking". ## Pre-1.0 packages -A package at `0.y.z` (currently `org.gamecult.cultmath`, at `0.2.x`) uses the +A package at `0.y.z` (currently `org.gamecult.cultmath`, at `0.3.x`) uses the standard pre-1.0 convention: `MAJOR` stays `0` during initial development, so `MINOR` carries what `MAJOR` means once the package reaches `1.0.0`. Concretely: @@ -182,8 +182,8 @@ or a missing declaration refuses), and: workflow tag trigger must be a declared prefix, and each such package's prefix must be a workflow trigger or, for the Caching Unity package the workflow does not build, the prefix of tags that hold its own manifest at the tag's own - version, so a typo or a copied prefix fails the suite. The workflow and the - three Unity release scripts run the suite before any check or publish step. + version, so a typo or a copied prefix fails the suite. Nothing releases + without the suite passing; see below for how each release path runs it. Releases run from a full clone with every tag (`fetch-depth: 0` in CI), the recorded `partial-tags-first-release`. Tags that cannot be read (a `--cwd` that is not a git repository, or a tag @@ -280,6 +280,36 @@ It is wired into: `org.gamecult.cultmath`; - `scripts/verify-caching-unity-release.ps1`, for `org.gamecult.caching.unity`. +Each of those runs the check's own tests before it releases. The Unity release +scripts run them before they call the check, and the tests pin that order. In +`publish-packages.yml` the release step runs `scripts/release-after-suite.mjs`, +which runs the tests and then the release action from one process, and releases +only if the tests passed: `npm publish` for `cultcache-ts`, and for the Python +packages the sdist and wheel build, whose output is all the PyPI upload step +uploads. The gate is that call, not a step condition, so no `if:` can release +what the tests did not pass. The tests compare each job's release steps with +their expected text exactly, less the steps' `if:` lines, and refuse +`continue-on-error`, `shell` and `defaults` anywhere in the workflow. Removing +the call is still possible, but only as a visible edit to those steps and to the +tests. + +`org.gamecult.cultlib` compiles CultMath from source and ships beside +`org.gamecult.cultmath`, so its build refuses unless it declares exactly the +CultMath package's version and every `CultMath.dll` it built equals the one +that package tracks, byte for byte. Any CultMath source change therefore means: +release `org.gamecult.cultmath`, declare its new version in +`org.gamecult.cultlib`, then release `org.gamecult.cultlib`. The bytes also +depend on the checkout and the toolchain. `.gitattributes` pins CultMath +source to CRLF on every checkout, because the tracked DLL was built from CRLF +source and line endings reach the DLL through the pdb's document checksums; a +clone checked out before that rule may still hold LF files (`git ls-files +--eol packages/cultmath/src` shows `w/lf`) until they are checked out again. +The build needs a git checkout, and refuses up front without `.git`: the repo +root maps to `/_/` through git, so an archive or source zip would write its +own path into the DLL. No `global.json` pins the .NET SDK, so the same refusal +at unchanged source and CRLF checkout means this SDK or host differs from the +one that built the tracked DLL. + ### Coverage gaps `publish-packages.yml` only triggers on `cultcache-ts-v*`, `cultcache-py-v*`, diff --git a/scripts/build-unity-package.ps1 b/scripts/build-unity-package.ps1 index 2f277c30..621a8034 100644 --- a/scripts/build-unity-package.ps1 +++ b/scripts/build-unity-package.ps1 @@ -9,13 +9,32 @@ param( $ErrorActionPreference = "Stop" $repoRoot = Split-Path -Parent $PSScriptRoot -$projectPath = Join-Path $repoRoot "src\GameCult.Mesh\GameCult.Mesh.csproj" -$webSocketProjectPath = Join-Path $repoRoot "src\GameCult.Networking.WebSockets\GameCult.Networking.WebSockets.csproj" -$quicProjectPath = Join-Path $repoRoot "src\GameCult.Mesh.Quic.Native\GameCult.Mesh.Quic.Native.csproj" +# The CultMath byte gate below needs a git checkout: ContinuousIntegrationBuild maps the repo root to /_/ +# through the SDK's git source root, so in a tree that is not the top of a git checkout (git archive, a +# source zip, an empty .git) the DLL names the absolute obj path and its bytes change with the directory. +# Git itself answers, so a worktree, where .git is a file, passes. +$gitErrorAction = $ErrorActionPreference +$ErrorActionPreference = "Continue" +$gitTop = & git -C $repoRoot rev-parse --show-toplevel 2>$null +$gitExit = $LASTEXITCODE +$ErrorActionPreference = $gitErrorAction +$isGitTop = $gitExit -eq 0 -and $gitTop -and + ([System.IO.Path]::GetFullPath("$gitTop").TrimEnd('\', '/') -eq [System.IO.Path]::GetFullPath($repoRoot).TrimEnd('\', '/')) +if (-not $isGitTop) { + throw "$repoRoot is not the top of a git checkout (git rev-parse --show-toplevel: '$gitTop', exit $gitExit), so CultMath.dll would carry this directory's path and fail the CultMath byte gate. Build from a git clone or worktree, not an archive or source zip." +} $templateRoot = Join-Path $repoRoot "unity\org.gamecult.cultlib" -$publishRoot = Join-Path $repoRoot "artifacts\unity-publish" -$webSocketPublishRoot = Join-Path $repoRoot "artifacts\unity-websocket-publish" -$quicPublishRoot = Join-Path $repoRoot "artifacts\unity-quic-publish" +# Every managed publish the package is assembled from, in the order $publishedByName fills (last wins). +# This list is the one owner of publish-root identity: the clean step, the publish loop, the assembly +# lookup, the CultMath byte gate and the semver check's --api-refs all read it. +$managedPublishes = @( + @{ Project = "src\GameCult.Mesh\GameCult.Mesh.csproj"; Root = "artifacts\unity-publish"; Extra = @(); Label = "CultLib" }, + @{ Project = "src\GameCult.Mesh.Quic.Native\GameCult.Mesh.Quic.Native.csproj"; Root = "artifacts\unity-quic-publish"; Extra = @(); Label = "CultLib native QUIC managed" }, + @{ Project = "src\GameCult.Networking.WebSockets\GameCult.Networking.WebSockets.csproj"; Root = "artifacts\unity-websocket-publish"; Extra = @("-f", "netstandard2.1"); Label = "CultLib WebSocket" } +) +foreach ($publish in $managedPublishes) { + $publish.Root = Join-Path $repoRoot $publish.Root +} $quicNativeRoot = Join-Path $repoRoot "artifacts\unity-quic-native" $outputRoot = if ([System.IO.Path]::IsPathRooted($OutputDirectory)) { $OutputDirectory @@ -24,28 +43,23 @@ $outputRoot = if ([System.IO.Path]::IsPathRooted($OutputDirectory)) { } $pluginRoot = Join-Path $outputRoot "Runtime\Plugins" -if (Test-Path -LiteralPath $publishRoot) { - Remove-Item -LiteralPath $publishRoot -Recurse -Force -} -if (Test-Path -LiteralPath $quicPublishRoot) { - Remove-Item -LiteralPath $quicPublishRoot -Recurse -Force -} -if (Test-Path -LiteralPath $webSocketPublishRoot) { - Remove-Item -LiteralPath $webSocketPublishRoot -Recurse -Force -} -if (Test-Path -LiteralPath $outputRoot) { - Remove-Item -LiteralPath $outputRoot -Recurse -Force +foreach ($root in @($managedPublishes | ForEach-Object { $_.Root }) + $outputRoot) { + if (Test-Path -LiteralPath $root) { + Remove-Item -LiteralPath $root -Recurse -Force + } } $unityPackageVersion = (Get-Content -LiteralPath (Join-Path $templateRoot "package.json") -Raw | ConvertFrom-Json).version -# Release gate: cultlib's Unity package resolves CultMath through the org.gamecult.cultmath -# dependency, so a cultlib release must not run ahead of the CultMath package it names. -# (1) The declared dependency version must not exceed the CultMath package's own version. -# (2) The CultMath.dll that package tracks must define every type CultMathResolver formats. -# The names come from the resolver source (its Shape entries); scripts\check-cultmath-types.cs -# looks them up in the assembly's type-definition table, which Windows PowerShell cannot load -# the assembly to do. It checks type names, not signatures. +# Release gate: cultlib compiles CultMath from source and ships beside org.gamecult.cultmath, which owns +# CultMath.dll and is resolved through the package.json dependency. Two gates bind the two: +# (1) The declared dependency version must equal the CultMath package's own version. Checked here, +# before anything is built. +# (2) Every CultMath.dll the publishes below produce must equal, byte for byte, the one that package +# tracks. Checked once they exist. The builds are deterministic for one toolchain and checkout, so a +# mismatch means the CultMath source changed since that package was released, its checkout's line +# endings differ from the CRLF that .gitattributes pins, or this SDK, compiler or host builds +# different bytes from the one that built the tracked DLL (no global.json pins the SDK). $cultMathPackageRoot = Join-Path $repoRoot "packages\cultmath\unity\org.gamecult.cultmath" $cultMathDeclared = (Get-Content -LiteralPath (Join-Path $templateRoot "package.json") -Raw | ConvertFrom-Json).dependencies.'org.gamecult.cultmath' $cultMathAvailable = (Get-Content -LiteralPath (Join-Path $cultMathPackageRoot "package.json") -Raw | ConvertFrom-Json).version @@ -57,60 +71,50 @@ foreach ($declared in @(@("org.gamecult.cultlib's org.gamecult.cultmath dependen throw "$($declared[0]) is '$($declared[1])'. The release gate compares exact release versions (major.minor.patch); prerelease and range versions are not supported." } } -if ([version]$cultMathDeclared -gt [version]$cultMathAvailable) { - throw "Release order: org.gamecult.cultlib depends on org.gamecult.cultmath $cultMathDeclared, but the CultMath package is at $cultMathAvailable. Release CultMath first." -} -$resolverSource = Get-Content -LiteralPath (Join-Path $repoRoot "src\GameCult.Caching.MessagePack\CultMathResolver.cs") -Raw -$resolverTypes = @([regex]::Matches($resolverSource, '\bShape<(?!T>)(\w+)>\(') | ForEach-Object { $_.Groups[1].Value } | Sort-Object -Unique) -if ($resolverTypes.Count -eq 0) { - throw "Found no CultMath types in CultMathResolver.cs; the release gate cannot check the CultMath package." -} -$missingTypes = & dotnet run (Join-Path $PSScriptRoot "check-cultmath-types.cs") -- (Join-Path $cultMathPackageRoot "Runtime\Plugins\CultMath.dll") @resolverTypes -if ($LASTEXITCODE -eq 1) { - throw "The CultMath.dll in org.gamecult.cultmath $cultMathAvailable lacks types CultMathResolver formats: $missingTypes. Release CultMath first." -} -if ($LASTEXITCODE -ne 0) { - throw "scripts\check-cultmath-types.cs failed with exit code $LASTEXITCODE." +if ([version]$cultMathDeclared -ne [version]$cultMathAvailable) { + throw "Release order: org.gamecult.cultlib declares org.gamecult.cultmath $cultMathDeclared but the CultMath package is at $cultMathAvailable; cultlib compiles against that package's source, so they must be equal. Release CultMath first, then declare its version." } # The tracked DLLs and pdbs are committed beside their source, so none may name a commit or a worktree: # Source Link writes the commit SHA into the pdb, the informational version carries it too, and each DLL # carries its pdb's content id. ContinuousIntegrationBuild maps the local source path to /_/. # dotnet publish has no --no-incremental, so clear the configuration's intermediates instead: a stale obj -# directory must not decide what the byte check compares. -Get-ChildItem -LiteralPath (Join-Path $repoRoot "obj\src") -Directory -ErrorAction SilentlyContinue | - ForEach-Object { Join-Path $_.FullName $Configuration } | +# directory must not decide what the byte check compares. Directory.Build.props puts every project's +# intermediates under obj\, CultMath's at obj\packages\cultmath\src\CultMath, so clear the +# configuration directory beside every restored project's project.assets.json, not only those under obj\src. +@(Get-ChildItem -LiteralPath (Join-Path $repoRoot "obj") -Recurse -File -Filter "project.assets.json" -ErrorAction SilentlyContinue) | + ForEach-Object { Join-Path $_.DirectoryName $Configuration } | Where-Object { Test-Path -LiteralPath $_ } | ForEach-Object { Remove-Item -LiteralPath $_ -Recurse -Force } $deterministicArguments = @("--disable-build-servers", "-p:UseSharedCompilation=false", "-p:ContinuousIntegrationBuild=true", "-p:EnableSourceLink=false", "-p:IncludeSourceRevisionInInformationalVersion=false", "-m:1") -$publishArguments = @("publish", $projectPath, "-c", $Configuration, "-o", $publishRoot, "-p:CultLibPackageVersion=$unityPackageVersion") + $deterministicArguments -if ($NoRestore) { $publishArguments += "--no-restore" } -if (-not [string]::IsNullOrWhiteSpace($NuGetConfig)) { - $publishArguments += "-p:RestoreConfigFile=$([IO.Path]::GetFullPath($NuGetConfig))" +foreach ($publish in $managedPublishes) { + $publishArguments = @("publish", (Join-Path $repoRoot $publish.Project), "-c", $Configuration) + $publish.Extra + + @("-o", $publish.Root, "-p:CultLibPackageVersion=$unityPackageVersion") + $deterministicArguments + if ($NoRestore) { $publishArguments += "--no-restore" } + if (-not [string]::IsNullOrWhiteSpace($NuGetConfig)) { + $publishArguments += "-p:RestoreConfigFile=$([IO.Path]::GetFullPath($NuGetConfig))" + } + & dotnet @publishArguments + if ($LASTEXITCODE -ne 0) { + throw "$($publish.Label) publish failed with exit code $LASTEXITCODE" + } } -& dotnet @publishArguments -if ($LASTEXITCODE -ne 0) { - throw "CultLib publish failed with exit code $LASTEXITCODE" +# Gate (2): the CultMath bytes cultlib was built against are the bytes org.gamecult.cultmath ships. +$cultMathTrackedHash = (Get-FileHash -LiteralPath (Join-Path $cultMathPackageRoot "Runtime\Plugins\CultMath.dll") -Algorithm SHA256).Hash +$cultMathComparedRoots = @() +foreach ($publish in $managedPublishes) { + $builtCultMath = Join-Path $publish.Root "CultMath.dll" + if (-not (Test-Path -LiteralPath $builtCultMath)) { continue } + if ((Get-FileHash -LiteralPath $builtCultMath -Algorithm SHA256).Hash -ne $cultMathTrackedHash) { + throw "Release order: the CultMath.dll built into $($publish.Root) differs from the one org.gamecult.cultmath $cultMathAvailable tracks. Either CultMath source changed since that release, its checkout has other line endings, or this toolchain builds different bytes from the one that built the tracked DLL. Check first: git log cultmath-unity-v$cultMathAvailable.. -- packages/cultmath/src for a source change; git ls-files --eol packages/cultmath/src, where every file must read w/crlf (.gitattributes pins it; a clone checked out before that rule needs the files checked out again); then dotnet --version and the host against the build that produced the tracked DLL. A source change means release CultMath first, then declare its version; a toolchain difference means build with the toolchain that produced the tracked DLL." + } + $cultMathComparedRoots += $publish.Root } -$webSocketPublishArguments = @("publish", $webSocketProjectPath, "-c", $Configuration, "-f", "netstandard2.1", "-o", $webSocketPublishRoot, "-p:CultLibPackageVersion=$unityPackageVersion") + $deterministicArguments -if ($NoRestore) { $webSocketPublishArguments += "--no-restore" } -if (-not [string]::IsNullOrWhiteSpace($NuGetConfig)) { - $webSocketPublishArguments += "-p:RestoreConfigFile=$([IO.Path]::GetFullPath($NuGetConfig))" -} -& dotnet @webSocketPublishArguments -if ($LASTEXITCODE -ne 0) { - throw "CultLib WebSocket publish failed with exit code $LASTEXITCODE" -} -$quicPublishArguments = @("publish", $quicProjectPath, "-c", $Configuration, "-o", $quicPublishRoot, "-p:CultLibPackageVersion=$unityPackageVersion") + $deterministicArguments -if ($NoRestore) { $quicPublishArguments += "--no-restore" } -if (-not [string]::IsNullOrWhiteSpace($NuGetConfig)) { - $quicPublishArguments += "-p:RestoreConfigFile=$([IO.Path]::GetFullPath($NuGetConfig))" -} -& dotnet @quicPublishArguments -if ($LASTEXITCODE -ne 0) { - throw "CultLib native QUIC managed publish failed with exit code $LASTEXITCODE" +if ($cultMathComparedRoots.Count -eq 0) { + throw "No managed publish produced CultMath.dll, so the CultMath byte gate measured nothing." } +Write-Host "CultMath byte gate: CultMath.dll in $($cultMathComparedRoots -join ', ') equals org.gamecult.cultmath $cultMathAvailable's tracked DLL." & (Join-Path $PSScriptRoot "build-quic-native.ps1") ` -Configuration $Configuration ` -OutputDirectory $quicNativeRoot @@ -157,14 +161,10 @@ if (($referencedAssemblies -join "|") -ne ($declaredAssemblies -join "|")) { throw "GameCult.CultLib.asmdef precompiledReferences differ from the shipped plus external assembly lists." } $publishedByName = @{} -foreach ($assembly in Get-ChildItem -LiteralPath $publishRoot -Filter "*.dll") { - $publishedByName[$assembly.Name] = $assembly -} -foreach ($assembly in Get-ChildItem -LiteralPath $quicPublishRoot -Filter "*.dll") { - $publishedByName[$assembly.Name] = $assembly -} -foreach ($assembly in Get-ChildItem -LiteralPath $webSocketPublishRoot -Filter "*.dll") { - $publishedByName[$assembly.Name] = $assembly +foreach ($publish in $managedPublishes) { + foreach ($assembly in Get-ChildItem -LiteralPath $publish.Root -Filter "*.dll") { + $publishedByName[$assembly.Name] = $assembly + } } foreach ($assemblyName in $expectedAssemblies) { if (-not $publishedByName.ContainsKey($assemblyName)) { @@ -182,8 +182,8 @@ $measuredArguments = @() foreach ($assemblyName in $expectedAssemblies) { $measuredArguments += @("--api-built", $publishedByName[$assemblyName].FullName) } -foreach ($refRoot in @($publishRoot, $quicPublishRoot, $webSocketPublishRoot)) { - $measuredArguments += @("--api-refs", $refRoot) +foreach ($publish in $managedPublishes) { + $measuredArguments += @("--api-refs", $publish.Root) } # The suite pins the checker's rules and the declared tag prefixes, so it runs first. & node --test (Join-Path $repoRoot "scripts\check-changelog-semver.test.mjs") diff --git a/scripts/check-changelog-semver.test.mjs b/scripts/check-changelog-semver.test.mjs index 62a78068..237c870f 100644 --- a/scripts/check-changelog-semver.test.mjs +++ b/scripts/check-changelog-semver.test.mjs @@ -741,33 +741,72 @@ test("workflow: the Caching Unity prefix is its own tag family, not another pack assert.match(prefixPinProblems(releasePackages, workflowText(), [], readAtTag).join("\n"), /are the tags fetched\?/); }); -// The suite is what pins the declared prefixes and the checker's rules, so the places that release -// run it first: every job of publish-packages.yml, on a checkout that holds every tag, with .NET set -// up for the API gate, before any step that checks or publishes; and each Unity release script, -// before it calls the checker. +// The suite is what pins the declared prefixes and the checker's rules, so nothing releases without it. +// publish-packages.yml releases only through scripts/release-after-suite.mjs, which runs the suite and then +// the release action from one process, so no if: on any step can release what the suite did not pass. This +// pin reads no condition. It compares each job's release steps whole, less their own if: line, with the +// text below, so a release step that does anything else is a mismatch, and it refuses any step or job that +// may fail without failing the job, or that runs through another shell. Each Unity release script runs the +// suite itself, before it calls the checker. const SUITE = /node\s+--test[^\n]*check-changelog-semver\.test\.mjs/; const CHECKER = /check-changelog-semver\.mjs/; const code = (text) => text.split("\n").filter((line) => !line.trim().startsWith("#")).join("\n"); -function workflowSuiteProblems(workflow) { - const [, jobs] = workflow.split(/^jobs:\r?\n/m); +const RELEASE_STEPS = { + "cultcache-ts": [ + ["- name: Publish", " run: node scripts/release-after-suite.mjs npm-publish packages/cultcache-ts", " env:", " NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}"], + ], + // Publish uploads only the dist the guarded step built, so it has nothing to upload unless the suite passed. + python: [ + ["- name: Build sdist and wheel", " run: node scripts/release-after-suite.mjs python-build packages/${{ matrix.package }}"], + ["- name: Publish", " uses: pypa/gh-action-pypi-publish@release/v1", " with:", " packages-dir: packages/${{ matrix.package }}/dist"], + ], +}; + +// A job's steps, each as its lines relative to its "- name:" line, without comments, blank lines or the +// step's own one-line if:. A line indented less than the step stays whole, so it cannot match. +function jobSteps(job) { + const steps = []; + for (const line of job.split(/\r?\n/)) { + if (line.trim() === "" || line.trim().startsWith("#")) continue; + const name = line.match(/^( *)- name:/); + if (name) steps.push({ indent: name[1], lines: [] }); + const step = steps.at(-1); + if (step === undefined) continue; + const relative = line.startsWith(step.indent) ? line.slice(step.indent.length) : line; + if (!/^ if: .*$/.test(relative)) step.lines.push(relative); + } + return steps; +} + +function workflowReleaseProblems(workflow) { + const [, jobs = ""] = workflow.split(/^jobs:\r?\n/m); const starts = [...jobs.matchAll(/^ ([\w-]+):\r?\n/gm)]; const problems = []; - if (starts.length === 0) problems.push("the workflow has no jobs"); + for (const id of Object.keys(RELEASE_STEPS)) { + if (!starts.some((start) => start[1] === id)) problems.push(`the workflow has no job ${id}`); + } starts.forEach((start, index) => { - const job = code(jobs.slice(start.index, starts[index + 1]?.index ?? jobs.length)); - const at = (pattern) => job.search(pattern); - const suite = at(SUITE); const label = `job ${start[1]}`; - if (suite < 0) return problems.push(`${label} does not run the suite`); - if (/continue-on-error/.test(job)) problems.push(`${label} lets a step fail without failing the job`); - if (at(/fetch-depth:\s*0\b/) < 0 || at(/fetch-depth:\s*0\b/) > suite) problems.push(`${label} runs the suite before checking out with fetch-depth: 0`); - if (at(/actions\/setup-dotnet@/) < 0 || at(/actions\/setup-dotnet@/) > suite) problems.push(`${label} runs the suite before setting up .NET`); - for (const [what, pattern] of [["the checker", CHECKER], ["a publish step", /^\s+- name: Publish\b/m]]) { - if (at(pattern) < 0) problems.push(`${label} has no ${what}`); - else if (at(pattern) < suite) problems.push(`${label} reaches ${what} before the suite`); + if (!Object.hasOwn(RELEASE_STEPS, start[1])) return problems.push(`${label} is not a job this pin knows; give it its release steps in RELEASE_STEPS`); + const steps = jobSteps(jobs.slice(start.index, starts[index + 1]?.index ?? jobs.length)); + let from = 0; + for (const want of RELEASE_STEPS[start[1]]) { + const named = steps.filter((step) => step.lines[0] === want[0]); + const at = steps.findIndex((step, i) => i >= from && step.lines[0] === want[0]); + if (named.length !== 1 || at < 0) { + problems.push(`${label} needs exactly one step "${want[0]}", after the release step before it`); + continue; + } + if (steps[at].lines.join("\n") !== want.join("\n")) { + problems.push(`${label} step "${want[0]}" is not exactly the release call:\n${steps[at].lines.join("\n")}`); + } + from = at + 1; } }); + if (/continue-on-error|\bshell\b|\bdefaults\b/.test(code(workflow))) { + problems.push("the workflow says continue-on-error, shell or defaults: no step may fail without failing its job, or run through another shell"); + } return problems; } @@ -777,23 +816,59 @@ function scriptSuiteProblems(script) { return body.search(CHECKER) < body.search(SUITE) ? ["calls the checker before the suite"] : []; } -test("workflow: every job runs the suite first, with every tag fetched; removing or moving the step fails this test", () => { +test("workflow: each job releases only through release-after-suite.mjs, and no step may fail without failing its job", () => { const workflow = workflowText(); - assert.deepEqual(workflowSuiteProblems(workflow), []); - const suiteLines = /^\s+run: node --test scripts\/check-changelog-semver\.test\.mjs\r?\n/gm; - assert.equal(workflow.match(suiteLines).length, 2); - // the step removed from either job, or from both - let removed = 0; - assert.deepEqual(workflowSuiteProblems(workflow.replace(suiteLines, (line) => (removed++ === 0 ? " run: true\n" : line))).length, 1); - assert.equal(workflowSuiteProblems(workflow.replace(suiteLines, " run: true\n")).length, 2); - // the step moved after the checker, a shallow checkout, no .NET, and a step allowed to fail - const moved = workflow - .replace(suiteLines, " run: true\n") - .replace(/(\s+- name: Verify semver policy\b)/, "\n - name: Late\n run: node --test scripts/check-changelog-semver.test.mjs$1"); - assert.notDeepEqual(workflowSuiteProblems(moved), []); - assert.notDeepEqual(workflowSuiteProblems(workflow.replace(/fetch-depth: 0/g, "fetch-depth: 1")), []); - assert.notDeepEqual(workflowSuiteProblems(workflow.replace(/actions\/setup-dotnet@/g, "actions/setup-other@")), []); - assert.notDeepEqual(workflowSuiteProblems(workflow.replace(suiteLines, (line) => `${line} continue-on-error: true\n`)), []); + assert.deepEqual(workflowReleaseProblems(workflow), []); + const npmRun = "run: node scripts/release-after-suite.mjs npm-publish packages/cultcache-ts"; + const pythonRun = "run: node scripts/release-after-suite.mjs python-build packages/${{ matrix.package }}"; + const exact = /is not exactly the release call/; + for (const run of [npmRun, pythonRun]) { + assert.equal(workflow.split(run).length, 2, run); + const edit = (replacement) => workflowReleaseProblems(workflow.replace(run, replacement)).join("\n"); + // anything else on the line, on a continuation line, or in a block; another call; another shell + assert.match(edit(`${run} || true`), exact, run); + assert.match(edit(`${run}\n || true`), exact, run); + assert.match(edit("run: |\n node --test scripts/check-changelog-semver.test.mjs\n true"), exact, run); + assert.match(edit(run.replace("release-after-suite.mjs", "check-changelog-semver.mjs")), exact, run); + assert.match(edit(`${run}\n shell: bash`), /another shell/, run); + assert.match(edit(`${run}\n continue-on-error: true`), /no step may fail/, run); + } + // the guard runs the suite itself, so the release steps' conditions are free + assert.deepEqual(workflowReleaseProblems(workflow.replace(/if: startsWith\(github\.ref, 'refs\/tags\/cultcache-ts-v'\)(\r?\n\s+run: node)/, "if: always()$1")), []); + // a job allowed to fail, a release step removed, renamed or doubled, a Publish that uploads another dist, an unknown job + assert.match(workflowReleaseProblems(workflow.replace(/( runs-on: ubuntu-latest\r?\n)/, "$1 continue-on-error: true\n")).join("\n"), /no step may fail/); + assert.match(workflowReleaseProblems(workflow.replace("- name: Build sdist and wheel", "- name: Build")).join("\n"), /needs exactly one step "- name: Build sdist and wheel"/); + assert.match(workflowReleaseProblems(workflow.replace("- name: Build and test", "- name: Publish\n run: npm publish\n\n - name: Build and test")).join("\n"), /needs exactly one step "- name: Publish"/); + assert.match(workflowReleaseProblems(workflow.replace("packages-dir: packages/${{ matrix.package }}/dist", "packages-dir: dist")).join("\n"), exact); + assert.match(workflowReleaseProblems(`${workflow}\n other:\n runs-on: ubuntu-latest\n`).join("\n"), /job other is not a job this pin knows/); +}); + +test("release-after-suite runs the suite first, and the release action only when the suite passed", async () => { + const { releaseAfterSuite, suite } = await import("./release-after-suite.mjs"); + const calls = []; + const runner = (suiteStatus, actionStatus = 0) => (command, args, cwd) => { + calls.push([command, args, cwd]); + return command === process.execPath ? suiteStatus : actionStatus; + }; + const suiteCall = [process.execPath, ["--test", suite], undefined]; + assert.equal(releaseAfterSuite(["npm-publish", "packages/cultcache-ts"], runner(0)), 0); + assert.deepEqual(calls, [suiteCall, ["npm", ["publish", "--access", "public"], "packages/cultcache-ts"]]); + calls.length = 0; + assert.equal(releaseAfterSuite(["python-build", "packages/cultnet-py"], runner(0, 3)), 3); + assert.deepEqual(calls, [suiteCall, ["python", ["-m", "build", "packages/cultnet-py"], undefined]]); + for (const action of ["npm-publish", "python-build"]) { + calls.length = 0; + assert.equal(releaseAfterSuite([action, "packages/x"], runner(1)), 1); + assert.deepEqual(calls, [suiteCall], action); + } + for (const argv of [[], ["npm-publish"], ["constructor", "x"], ["npm-publish", "x", "y"]]) { + calls.length = 0; + assert.equal(releaseAfterSuite(argv, runner(0)), 2, argv.join(" ")); + assert.deepEqual(calls, []); + } + // run as a script, a usage error exits 2 before the suite runs + const script = fileURLToPath(new URL("./release-after-suite.mjs", import.meta.url)); + assert.throws(() => execFileSync(process.execPath, [script], { stdio: "pipe" }), (error) => error.status === 2); }); test("the Unity release scripts run the suite before the checker; removing it fails this test", () => { diff --git a/scripts/check-cultmath-types.cs b/scripts/check-cultmath-types.cs deleted file mode 100644 index dab33397..00000000 --- a/scripts/check-cultmath-types.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Release gate helper for build-unity-package.ps1: reads an assembly's type-definition table and -// reports which of the named CultMath types it does not define as a public top-level type. -// Usage: dotnet run scripts/check-cultmath-types.cs -- ... -// Exit 0 when every type is defined, 1 when any is missing, 2 on bad usage. -using System.Reflection; -using System.Reflection.Metadata; -using System.Reflection.PortableExecutable; - -if (args.Length < 2) -{ - Console.Error.WriteLine("usage: check-cultmath-types ..."); - return 2; -} - -using var stream = File.OpenRead(args[0]); -using var pe = new PEReader(stream); -var metadata = pe.GetMetadataReader(); -var defined = new HashSet(); -foreach (var handle in metadata.TypeDefinitions) -{ - var type = metadata.GetTypeDefinition(handle); - if (!type.GetDeclaringType().IsNil) continue; - if ((type.Attributes & TypeAttributes.VisibilityMask) != TypeAttributes.Public) continue; - if (metadata.GetString(type.Namespace) == "CultMath") defined.Add(metadata.GetString(type.Name)); -} - -var missing = args.Skip(1).Where(name => !defined.Contains(name)).ToArray(); -if (missing.Length == 0) return 0; -Console.WriteLine(string.Join(", ", missing)); -return 1; diff --git a/scripts/release-after-suite.mjs b/scripts/release-after-suite.mjs new file mode 100644 index 00000000..1bf06a3b --- /dev/null +++ b/scripts/release-after-suite.mjs @@ -0,0 +1,36 @@ +// How publish-packages.yml releases a package: the release-checks suite runs first, and the release +// action runs only if the suite passed, both from this one process. No workflow condition can then +// release what the suite did not pass. docs/semver-policy.md, "The suite gates every release". +// +// node scripts/release-after-suite.mjs npm-publish npm publish --access public in +// node scripts/release-after-suite.mjs python-build python -m build , for the PyPI step +import { spawnSync } from "node:child_process"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +export const suite = fileURLToPath(new URL("./check-changelog-semver.test.mjs", import.meta.url)); + +// Scoped npm packages default to restricted, and CultLib is MIT, so the publish says public. +export const actions = { + "npm-publish": (dir) => ["npm", ["publish", "--access", "public"], dir], + "python-build": (dir) => ["python", ["-m", "build", dir], undefined], +}; + +const spawn = (command, args, cwd) => spawnSync(command, args, { cwd, stdio: "inherit" }).status ?? 1; + +// Returns the exit code. `run(command, args, cwd)` returns a command's exit code; tests pass their own. +export function releaseAfterSuite(argv, run = spawn) { + const [action, dir, ...rest] = argv; + if (!Object.hasOwn(actions, action ?? "") || !dir || rest.length > 0) { + console.error(`usage: node scripts/release-after-suite.mjs <${Object.keys(actions).join("|")}> `); + return 2; + } + if (run(process.execPath, ["--test", suite], undefined) !== 0) { + console.error("The release check suite failed (scripts/check-changelog-semver.test.mjs); not releasing."); + return 1; + } + return run(...actions[action](dir)); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + process.exitCode = releaseAfterSuite(process.argv.slice(2)); +}