From 8b45c66dae51655617c04b6adfb1c1c45ebbb207 Mon Sep 17 00:00:00 2001 From: Sami Dokus Date: Fri, 4 Dec 2026 13:21:16 -0700 Subject: [PATCH] feat(actions): add wp-test-matrix for a WordPress version matrix [SOFT-4410] - Why: plugin test workflows pin one WordPress version, so a regression in a new WordPress release reaches support before CI. The six TEC repo PRs for SOFT-4410 to SOFT-4415 each wired the same lookup in by hand. - What: a github-script action that lists the newest X.Y releases from the WordPress.org version check, each at its latest patch, as a JSON array for strategy.matrix. count picks how many (default 3); fewer offered fails. Unit tests, a live job in test.yml, README entries. - Impact: any plugin feeds the output into its matrix and passes each version to setup-slic's wp-version; new WordPress releases rotate in without editing a workflow. --- .github/actions/wp-test-matrix/README.md | 101 +++++++++++++ .github/actions/wp-test-matrix/action.yml | 42 ++++++ .../actions/wp-test-matrix/wp-test-matrix.js | 134 ++++++++++++++++++ .github/workflows/test.yml | 34 +++++ README.md | 7 +- .../wp-test-matrix/wp-test-matrix.test.js | 134 ++++++++++++++++++ 6 files changed, 450 insertions(+), 2 deletions(-) create mode 100644 .github/actions/wp-test-matrix/README.md create mode 100644 .github/actions/wp-test-matrix/action.yml create mode 100644 .github/actions/wp-test-matrix/wp-test-matrix.js create mode 100644 tests/actions/wp-test-matrix/wp-test-matrix.test.js diff --git a/.github/actions/wp-test-matrix/README.md b/.github/actions/wp-test-matrix/README.md new file mode 100644 index 00000000..92cc91c6 --- /dev/null +++ b/.github/actions/wp-test-matrix/README.md @@ -0,0 +1,101 @@ +# wp-test-matrix + +Lists the newest WordPress X.Y releases, each at its latest patch, as a JSON array for a test +workflow's `strategy.matrix`. With the default `count` of 3 that is the latest release and the two +before it. When WordPress ships a new X.Y, it joins the matrix and the oldest one leaves, without +anyone editing a workflow. + +```yaml +jobs: + wp-versions: + runs-on: ubuntu-latest + permissions: {} + outputs: + versions: ${{ steps.matrix.outputs.versions }} + steps: + - id: matrix + uses: stellarwp/plugin-toolbox/.github/actions/wp-test-matrix@v1 + + test: + needs: wp-versions + runs-on: ubuntu-latest + # The version in the job name says which WordPress a failing job ran on. + name: ${{ matrix.suite }} (WP ${{ matrix.wp }}) + strategy: + # One WordPress version failing does not cancel the others. + fail-fast: false + matrix: + suite: [unit, wpunit] + wp: ${{ fromJSON(needs.wp-versions.outputs.versions) }} + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + + - uses: stellarwp/plugin-toolbox/.github/actions/setup-slic@v1 + with: + target: my-plugin + wp-version: ${{ matrix.wp }} + + - uses: stellarwp/plugin-toolbox/.github/actions/run-slic-suite@v1 + with: + suite: ${{ matrix.suite }} +``` + +Inside this repository, call it as `uses: $/.github/actions/wp-test-matrix`. + +The job needs no token, so `permissions: {}` keeps the repository's default token away from it. + +An artifact uploaded from a matrix job has to carry the version in its name, such as +`output ${{ matrix.suite }} wp-${{ matrix.wp }}`, or the jobs for one suite collide on the same name. + +## Inputs + +| Input | Required | Default | What it does | +|---|---|---|---| +| `count` | no | `3` | How many X.Y releases to list, newest first. Fewer releases offered than asked for fails the step | + +## Outputs + +| Output | Example | What it is | +|---|---|---| +| `versions` | `["7.1.5","7.0.9","6.9.12"]` | JSON array of full versions, newest first, for `fromJSON()` in `strategy.matrix` | + +## Testing fewer versions on some runs + +Each version runs every suite again, so three versions cost three times the runner minutes of one. +A workflow that wants the full matrix only on some runs passes a `count` expression. For example, +the latest release only, except on pull requests from a `release/` branch into `main`: + +```yaml +- id: matrix + uses: stellarwp/plugin-toolbox/.github/actions/wp-test-matrix@v1 + with: + count: ${{ startsWith(github.head_ref, 'release/') && github.base_ref == 'main' && 3 || 1 }} +``` + +## Where the versions come from + +The action asks [`https://api.wordpress.org/core/version-check/1.7/`](https://api.wordpress.org/core/version-check/1.7/), +the endpoint WordPress itself calls for updates. It offers the latest patch of every X.Y branch +that still gets security fixes. The action keeps the highest patch of each X.Y, so a duplicate or +an answer in another order changes nothing, and skips anything that is not a release, such as a +beta or an RC. + +The versions are full patch versions, such as `7.0.9` rather than `7.0`, so setup-slic's +`wp-version` installs an exact release and the job name says exactly what ran. + +The request is tried three times, with a 10-second timeout each. When every attempt fails, or +WordPress.org offers fewer releases than `count`, the step fails rather than run a smaller matrix. + +## How it runs + +The logic is in `wp-test-matrix.js`, run by [actions/github-script](https://github.com/actions/github-script), +so there is nothing to install and no bundle to build. + +The `count` input reaches the script through `process.env`, never by being interpolated into it. + +`tests/actions/wp-test-matrix/wp-test-matrix.test.js` covers the rules above against a stand-in for +the WordPress.org answer. Run `npm install` once, then `node --test`. The `wp-test-matrix` job in +[`test.yml`](../../workflows/test.yml) runs the action against the real endpoint and fans a matrix +out from its output. diff --git a/.github/actions/wp-test-matrix/action.yml b/.github/actions/wp-test-matrix/action.yml new file mode 100644 index 00000000..202f76a1 --- /dev/null +++ b/.github/actions/wp-test-matrix/action.yml @@ -0,0 +1,42 @@ +# Lists the newest WordPress X.Y releases, each at its latest patch, as a JSON array for a test +# workflow's strategy.matrix. A new WordPress release joins the matrix and the oldest one leaves it +# without anyone editing a workflow. +# +# The logic lives in wp-test-matrix.js, run by actions/github-script, so there is nothing to install +# and nothing to build. +name: WordPress test matrix +description: Lists the newest WordPress X.Y releases, at their latest patch, for a test matrix + +inputs: + count: + description: >- + How many X.Y releases to list, newest first: 3 is the latest release and the two before it. + Fewer releases offered by api.wordpress.org than asked for fails the step. + required: false + default: '3' + +outputs: + versions: + description: >- + JSON array of full versions, newest first, e.g. `["7.1.5","7.0.9","6.9.12"]`. Read it with + fromJSON() in strategy.matrix, and pass each one to setup-slic's wp-version. + value: ${{ steps.versions.outputs.versions }} + +runs: + using: 'composite' + steps: + - name: List the WordPress releases to test + id: versions + uses: actions/github-script@v9 + env: + # github-script's require() resolves against the workspace of the repository being built, + # not this action's directory, so the path has to be passed in. github.action_path is the + # documented expression for it. + ACTION_PATH: ${{ github.action_path }} + # Read from process.env rather than interpolated into the script, so an input is data and + # never part of the program. + INPUT_COUNT: ${{ inputs.count }} + with: + script: | + const { runWpTestMatrix } = require(`${process.env.ACTION_PATH}/wp-test-matrix.js`) + await runWpTestMatrix({ core, env: process.env }) diff --git a/.github/actions/wp-test-matrix/wp-test-matrix.js b/.github/actions/wp-test-matrix/wp-test-matrix.js new file mode 100644 index 00000000..c7fde293 --- /dev/null +++ b/.github/actions/wp-test-matrix/wp-test-matrix.js @@ -0,0 +1,134 @@ +'use strict' + +/** + * Lists the newest WordPress X.Y releases, each at its latest patch, for a test matrix. + * + * pickVersions is pure, so a test covers every rule without a network. runWpTestMatrix reads the + * input, asks WordPress.org and writes the `versions` output. + */ + +const { compareVersions } = require('../../lib/versions.js') + +/** The WordPress.org endpoint that offers the latest patch of every X.Y branch that still gets security fixes. */ +const VERSION_CHECK_URL = 'https://api.wordpress.org/core/version-check/1.7/' + +/** A WordPress release: two or three numeric parts. A beta or RC such as `7.2-RC1` is not one. */ +const RELEASE_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)(\.(0|[1-9]\d*))?$/ + +/** How long the request to api.wordpress.org may take, in milliseconds, before the step fails. */ +const LOOKUP_TIMEOUT = 10000 + +/** Attempts at the request, so one dropped connection does not fail every test workflow that runs. */ +const ATTEMPTS = 3 + +/** + * Reads the `count` input. + * + * @param {string} value The input value. + * + * @throws {Error} When it is not a whole number of at least 1. + * + * @returns {number} How many releases to list. + */ +function readCount(value) { + const trimmed = String(value ?? '').trim() + + if (!/^[1-9]\d*$/.test(trimmed)) { + throw new Error(`count must be a whole number of at least 1, such as 3, got '${trimmed}'.`) + } + + return Number(trimmed) +} + +/** + * Picks the newest X.Y releases from the offers of the version check. + * + * The version check offers each X.Y branch once, at its latest patch, but the latest release is + * offered twice (`upgrade` and `autoupdate`). Grouping by X.Y and keeping the highest patch holds + * whatever the order or the duplicates, so an answer listing 7.1.2 and 7.1.4 still gives 7.1.4. + * + * @param {object[]} offers The `offers` of the version check. + * @param {number} count How many releases to list. + * + * @returns {string[]} Full versions, newest first, e.g. `['7.1.5', '7.0.9', '6.9.12']`. Shorter than + * `count` when WordPress.org offers fewer. + */ +function pickVersions(offers, count) { + const latestPerBranch = new Map() + + for (const offer of Array.isArray(offers) ? offers : []) { + const version = offer?.version + if (typeof version !== 'string' || !RELEASE_PATTERN.test(version)) { + continue + } + + const branch = version.split('.').slice(0, 2).join('.') + const known = latestPerBranch.get(branch) + if (known === undefined || compareVersions(version, known) > 0) { + latestPerBranch.set(branch, version) + } + } + + return [...latestPerBranch.values()].sort((a, b) => compareVersions(b, a)).slice(0, count) +} + +/** + * Asks the WordPress.org version check for its offers, trying again after a failure. + * + * @param {Function} fetchImpl What `fetch` to use; a test passes a stand-in. + * + * @throws {Error} When every attempt fails. + * + * @returns {Promise} The offers, or an empty list when the answer has none. + */ +async function fetchOffers(fetchImpl) { + let lastError + + for (let attempt = 1; attempt <= ATTEMPTS; attempt++) { + try { + const response = await fetchImpl(VERSION_CHECK_URL, { signal: AbortSignal.timeout(LOOKUP_TIMEOUT) }) + if (!response.ok) { + throw new Error(`HTTP ${response.status}`) + } + const body = await response.json() + return Array.isArray(body?.offers) ? body.offers : [] + } catch (error) { + lastError = error + } + } + + throw new Error(`Looking up the WordPress releases at ${VERSION_CHECK_URL} failed (${lastError.message}).`) +} + +/** + * Reads the input, looks the releases up and writes the `versions` output. + * + * Fewer releases than asked for fails the step rather than shrinking the matrix, so a bad answer + * from WordPress.org cannot quietly test less than the caller asked for. + * + * @param {object} options + * @param {object} options.core The @actions/core toolkit, for the log, the output and the summary. + * @param {object} options.env The environment the action manifest put its inputs in. + * @param {Function} options.fetchImpl What `fetch` to use; a test passes a stand-in. + * + * @throws {Error} When `count` is refused, the lookup fails, or WordPress.org offers fewer releases. + * + * @returns {Promise} Resolves once the output and the summary are written. + */ +async function runWpTestMatrix({ core, env, fetchImpl = globalThis.fetch }) { + const count = readCount(env.INPUT_COUNT) + const versions = pickVersions(await fetchOffers(fetchImpl), count) + + if (versions.length < count) { + throw new Error( + `Asked for ${count} WordPress releases, but ${VERSION_CHECK_URL} offers ${versions.length}: ${JSON.stringify(versions)}.` + ) + } + + const json = JSON.stringify(versions) + core.setOutput('versions', json) + core.info(`WordPress test matrix: ${json}`) + await core.summary.addRaw(`## WordPress test matrix: \`${json}\``, true).write() +} + +module.exports = { runWpTestMatrix, pickVersions, readCount, VERSION_CHECK_URL } diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c0870c15..0ac4ca62 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -41,6 +41,40 @@ jobs: - name: Run the unit tests run: node --test + # The unit tests answer for WordPress.org; this runs the action against the real endpoint, so a + # change in its answer shows up here first, and fans a matrix out from the output the way a + # plugin's test workflow does. + wp-test-matrix: + runs-on: ubuntu-latest + permissions: {} + outputs: + versions: ${{ steps.matrix.outputs.versions }} + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + + - id: matrix + uses: ./.github/actions/wp-test-matrix + + wp-test-matrix-leg: + needs: wp-test-matrix + runs-on: ubuntu-latest + permissions: {} + name: wp-test-matrix (WP ${{ matrix.wp }}) + strategy: + matrix: + wp: ${{ fromJSON(needs.wp-test-matrix.outputs.versions) }} + steps: + - name: Check the version is a full WordPress release + env: + WP_VERSION: ${{ matrix.wp }} + run: | + if [[ ! "${WP_VERSION}" =~ ^[0-9]+\.[0-9]+(\.[0-9]+)?$ ]]; then + echo "::error::'${WP_VERSION}' is not a WordPress release." + exit 1 + fi + # The workflows and templates never run in this repository the way a plugin runs them, so a typo # in one would only show up in someone else's CI. actionlint also runs shellcheck on every run: # block it finds. diff --git a/README.md b/README.md index c578e292..4fe61e31 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,9 @@ This file is the README and the build plan. Until Phase 2 ships, anything under Use [setup-slic](.github/actions/setup-slic/) to provision the stack and [run-slic-suite](.github/actions/run-slic-suite/) to run Codeception tests. Playwright jobs can call -Slic directly after setup. Persistent runners should finish with +Slic directly after setup. To run the suites on the newest WordPress releases rather than one pinned +version, feed [wp-test-matrix](.github/actions/wp-test-matrix/) into the job's matrix and pass each +version to setup-slic's `wp-version`. Persistent runners should finish with [cleanup-slic](.github/actions/cleanup-slic/). The setup guide includes a complete workflow and examples for different checkout layouts. @@ -119,7 +121,7 @@ Three drawers in the toolbox. You can use any one without the others. | Layer | Lives in | What's in it | |---|---|---| -| Composite actions | `.github/actions/` | Small single-purpose steps with no opinions: `setup-slic`, `setup-bun`, `setup-node`, `prepare-matrix`, `check-php-changes`, `smart-checkout`, `process-changelog`, `generate-pot`, `push-translations`, `zip-name`, `release-zip`, `changed-files`, `skip-drafts`, `download-plugins` | +| Composite actions | `.github/actions/` | Small single-purpose steps with no opinions: `setup-slic`, `setup-bun`, `setup-node`, `prepare-matrix`, `check-php-changes`, `smart-checkout`, `process-changelog`, `generate-pot`, `push-translations`, `zip-name`, `release-zip`, `changed-files`, `skip-drafts`, `download-plugins`, `wp-test-matrix` | | Reusable workflows | `.github/workflows/` | Full jobs built from the actions (standards, analysis, tests, zip, release prep). Most repos will only touch this layer. | | File sync | `templates/` + `.github/sync.yml` | Files that must exist in the target repo, grouped by brand and repo type | @@ -174,6 +176,7 @@ Each phase ends with something people can actually use. - [x] Add `zip-name` and `release-zip`: the zip's name before the build, with a pre-release label (`dev`, `alpha`, `beta`, `rc`) and an optional build number, then `pup build`, `check`, `i18n` and `package` for that version. What `stellarwp/github-actions`' `zip.yml` does, as two actions so the bucket can be asked for the name first. The caller to copy, with the S3 check, the upload, the Slack notice and the artifact around them, is `templates/workflows/zip.yml`. - [x] Add `herald-publish`: the build uploaded to Herald and published as a version of a product, with a `ci` API key. A ZIP of another version is refused, and a rerun updates the version instead of creating it twice. `templates/workflows/release.yml` shows the step, commented out, between the build and `release-publish`. - [x] Port `push-translations` from TEC: a POT file to GlotPress, with the GlotPress project and the server folder as inputs. +- [x] Port `wp-test-matrix` from TEC: the newest WordPress X.Y releases, at their latest patch, as a JSON array for a test matrix. `count` sets how many. - [ ] Turn every hard-coded repo name, slug, or branch pattern into an input. - [ ] Self-checks: actionlint everything, unit test anything with real logic. - [ ] Tag `v1.0.0`. diff --git a/tests/actions/wp-test-matrix/wp-test-matrix.test.js b/tests/actions/wp-test-matrix/wp-test-matrix.test.js new file mode 100644 index 00000000..3ab10b51 --- /dev/null +++ b/tests/actions/wp-test-matrix/wp-test-matrix.test.js @@ -0,0 +1,134 @@ +'use strict' + +const { describe, it } = require('node:test') +const assert = require('node:assert') + +const { + runWpTestMatrix, + pickVersions, + readCount, + VERSION_CHECK_URL, +} = require('../../../.github/actions/wp-test-matrix/wp-test-matrix.js') +const { coreWithOutputs } = require('../../support/actions.js') + +/** The offers as api.wordpress.org gave them, cut to the newest branches: the latest release twice. */ +const OFFERS = [ + { response: 'upgrade', version: '7.1.5' }, + { response: 'autoupdate', version: '7.1.5' }, + { response: 'autoupdate', version: '7.0.9' }, + { response: 'autoupdate', version: '6.9.12' }, + { response: 'autoupdate', version: '6.8.13' }, +] + +/** A fetch answering each request with the next of the given responses, recording the URLs. */ +function answers(...responses) { + const calls = [] + const fetchImpl = async (url) => { + calls.push(url) + const next = responses[Math.min(calls.length, responses.length) - 1] + if (next instanceof Error) { + throw next + } + return new Response(typeof next === 'string' ? next : JSON.stringify(next), { status: next?.status ?? 200 }) + } + return { fetchImpl, calls } +} + +describe('wp-test-matrix', () => { + describe('readCount', () => { + it('reads a whole number', () => { + assert.equal(readCount(' 3 '), 3) + assert.equal(readCount('12'), 12) + }) + + it('refuses zero, a negative, a fraction, a word and empty', () => { + for (const value of ['0', '-1', '2.5', 'three', '', '03']) { + assert.throws(() => readCount(value), /count must be a whole number of at least 1/, value) + } + }) + }) + + describe('pickVersions', () => { + it('lists the newest X.Y releases at their latest patch, newest first', () => { + assert.deepEqual(pickVersions(OFFERS, 3), ['7.1.5', '7.0.9', '6.9.12']) + }) + + it('counts the latest release once although it is offered twice', () => { + assert.deepEqual(pickVersions(OFFERS, 2), ['7.1.5', '7.0.9']) + }) + + it('keeps the highest patch of a branch whatever the order', () => { + const offers = [{ version: '7.1.2' }, { version: '6.9.10' }, { version: '7.1.10' }, { version: '7.0' }] + + assert.deepEqual(pickVersions(offers, 3), ['7.1.10', '7.0', '6.9.10']) + }) + + it('orders 7.10 above 7.9, which a string sort does not', () => { + assert.deepEqual(pickVersions([{ version: '7.9.1' }, { version: '7.10' }], 2), ['7.10', '7.9.1']) + }) + + it('skips a beta, an RC and anything that is not a version', () => { + const offers = [{ version: '7.2-RC1' }, { version: '7.2-beta3' }, { version: null }, {}, null, ...OFFERS] + + assert.deepEqual(pickVersions(offers, 1), ['7.1.5']) + }) + + it('lists fewer when fewer are offered', () => { + assert.deepEqual(pickVersions(OFFERS.slice(0, 3), 3), ['7.1.5', '7.0.9']) + assert.deepEqual(pickVersions(undefined, 3), []) + }) + }) + + describe('runWpTestMatrix', () => { + async function run(t, env, fetchImpl) { + const { core, outputs, summary } = await coreWithOutputs(t) + await runWpTestMatrix({ core, env, fetchImpl }) + return { outputs: outputs(), summary: summary() } + } + + it('writes the versions as a JSON array for fromJSON, and the summary', async (t) => { + const { fetchImpl, calls } = answers({ offers: OFFERS }) + + const { outputs, summary } = await run(t, { INPUT_COUNT: '3' }, fetchImpl) + + assert.deepEqual(calls, [VERSION_CHECK_URL]) + assert.equal(outputs.versions, '["7.1.5","7.0.9","6.9.12"]') + assert.match(summary, /WordPress test matrix: `\["7\.1\.5","7\.0\.9","6\.9\.12"\]`/) + }) + + it('refuses a bad count before any lookup', async (t) => { + const { fetchImpl, calls } = answers({ offers: OFFERS }) + + await assert.rejects(run(t, { INPUT_COUNT: '0' }, fetchImpl), /count must be/) + assert.equal(calls.length, 0) + }) + + it('fails rather than test fewer releases than asked for', async (t) => { + const { fetchImpl } = answers({ offers: OFFERS.slice(0, 2) }) + + await assert.rejects(run(t, { INPUT_COUNT: '3' }, fetchImpl), /Asked for 3 WordPress releases, but .* offers 1: \["7\.1\.5"\]/) + }) + + it('fails on an answer without offers', async (t) => { + const { fetchImpl } = answers({ error: 'nope' }) + + await assert.rejects(run(t, { INPUT_COUNT: '1' }, fetchImpl), /offers 0/) + }) + + it('tries again after a failed request', async (t) => { + const { fetchImpl, calls } = answers({ status: 503 }, new Error('socket hang up'), { offers: OFFERS }) + + const { outputs } = await run(t, { INPUT_COUNT: '1' }, fetchImpl) + + assert.equal(calls.length, 3) + assert.equal(outputs.versions, '["7.1.5"]') + }) + + it('fails once every attempt has failed, naming the last error', async (t) => { + const { fetchImpl, calls } = answers(new Error('socket hang up'), 'not json', { status: 500 }) + + await assert.rejects(run(t, { INPUT_COUNT: '1' }, fetchImpl), /Looking up the WordPress releases .* failed \(HTTP 500\)/) + assert.equal(calls.length, 3) + }) + }) +})