Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 101 additions & 0 deletions .github/actions/wp-test-matrix/README.md
Original file line number Diff line number Diff line change
@@ -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.
42 changes: 42 additions & 0 deletions .github/actions/wp-test-matrix/action.yml
Original file line number Diff line number Diff line change
@@ -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 })
134 changes: 134 additions & 0 deletions .github/actions/wp-test-matrix/wp-test-matrix.js
Original file line number Diff line number Diff line change
@@ -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<object[]>} 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<void>} 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 }
34 changes: 34 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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 |

Expand Down Expand Up @@ -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`.
Expand Down
Loading