diff --git a/.github/actions/update-wp-version/README.md b/.github/actions/update-wp-version/README.md new file mode 100644 index 0000000..150ab04 --- /dev/null +++ b/.github/actions/update-wp-version/README.md @@ -0,0 +1,118 @@ +# update-wp-version + +Sets the WordPress version a plugin is tested up to and, when asked, the minimum it requires: a +version given, or two minor versions behind. + +```yaml +- uses: actions/checkout@v6 + with: + ref: ${{ inputs.branch }} + persist-credentials: false + +- uses: stellarwp/plugin-toolbox/.github/actions/update-wp-version@v1 + id: wp + with: + # Empty sets the latest WordPress release. + tested-up-to: ${{ inputs.tested-up-to }} + # Empty leaves Requires at least; `auto` sets it two minors back; `6.9` sets exactly that. + min-version: ${{ inputs.min-version }} + +# Commit here, when steps.wp.outputs.changed is 'true': this action only writes files. +``` + +It commits nothing: the step that commits the release preparation carries the change. + +## What it writes + +| Header | `readme.txt` | Plugin file | +|---|---|---| +| `Tested up to:` | always | when the file carries the header | +| `Requires at least:` | when `min-version` is set | when `min-version` is set | + +An empty `tested-up-to` is the latest WordPress release: the first offer +`https://api.wordpress.org/core/version-check/1.7/` returns. A version passed in is used as it is. + +`min-version` takes a version, which is set as it is, or `auto`. `auto` is the tested version two +minors back, major and minor only: `6.8` and `6.8.1` both give `6.6`. WordPress runs each major from +x.0 to x.9 and then moves to the next (6.9 was followed by 7.0), so `auto` counts back across a +major the same way: `7.0` gives `6.8` and `7.1` gives `6.9`. `auto` never lowers a minimum: a file +at `6.9` stays at `6.9` when `auto` gives `6.8`, and the run reports it. A version given exactly is +set as it is, so passing `6.7` is how a plugin lowers its minimum on purpose. + +The plugin file is the single root-level `.php` file `.puprc` lists under `paths.versions`. Some +plugins keep `Tested up to:` there as well as in `readme.txt`, as LearnDash does in `sfwd_lms.php`, +so the action sets it in both. + +Only an existing header is rewritten. A file without the header is left as it is, and a missing +`readme.txt` is skipped. Only the first line carrying a header changes, so a version quoted further +down the file stays. `Tested up to` is never lowered: a file at `7.1.4` stays at `7.1.4` when +`tested-up-to` is `7.1`, and the run reports it. The whole value is +replaced, so `Tested up to: 6.8-RC1` becomes `Tested up to: 6.8`. When no file carries a header to set, the action writes a warning and passes. + +The log and the job summary say, for each header each file carries, whether it changed from one +version to another, was already at the version, or was left above it. The `changed` output is +`true` when any file was written. + +## What the repository needs + +Nothing to set `Tested up to:` in `readme.txt`. For the plugin file, a `.puprc` that lists it: + +```json +{ + "paths": { + "versions": [ + { "file": "the-events-calendar.php", "regex": "(Version: )(.+)" }, + { "file": "readme.txt", "regex": "(Stable tag: )(.+)" } + ] + } +} +``` + +The same file listed several times, once per regex, counts as one. A leading `./` is allowed: +`./the-events-calendar.php` is the same root file. + +## What it refuses + +Every check runs before any file is written, so a refused run changes nothing. + +- `tested-up-to` that is not two or three numeric parts: `banana`, `6`, `6.8.1.2`, `v6.8`. A + zero-padded part is refused too, such as `6.08` or `06.8`. +- An empty `tested-up-to` when the latest release cannot be looked up: the request fails, the + answer is not JSON, or its first offer holds no such version. +- `min-version` that is not empty, `auto`, or a version of the same shape as `tested-up-to`, or a + version above `tested-up-to`. +- `min-version: auto` with a tested version below `1.2`, which has no minimum two minors back. +- `working-directory` that is not a directory. +- With `min-version` set, a `.puprc` that is missing, is not JSON, has no `paths.versions`, or does + not list exactly one root-level PHP file that exists. + +With `min-version` empty the `.puprc` is optional. Without one, or with one that does not name +a single plugin file, only `readme.txt` is updated. + +## Inputs + +| Input | Required | Default | What it does | +|---|---|---|---| +| `tested-up-to` | no | the latest release | The WordPress version to set as `Tested up to`, e.g. `6.8` or `6.8.1`. Empty looks up the latest WordPress release | +| `min-version` | no | | The `Requires at least` version: empty leaves it, `auto` sets it two minor versions behind `tested-up-to` without lowering a higher one, a version such as `6.9` sets exactly that | +| `working-directory` | no | the workspace | Where the repository is checked out, relative to the workspace or absolute | + +## Outputs + +| Output | Example | What it is | +|---|---|---| +| `min-version` | `6.6` | The minimum version set. Empty when the `min-version` input is empty | +| `changed` | `true` | `true` when a file was written, `false` when every header was already at its version, was left above it, or no file carries one | + +## How it runs + +One [actions/github-script](https://github.com/actions/github-script) step runs +[`update-wp-version.js`](./update-wp-version.js). There is no dependency to install and nothing to +build. + +Inputs reach the script through `process.env`, never by being interpolated into it, so a version is +data and cannot become part of the program. The script runs no command: it reads and writes files, +and with an empty `tested-up-to` it sends one request to `api.wordpress.org`. + +`tests/actions/update-wp-version/update-wp-version.test.js` covers the rules above against real +temporary directories. Run `npm install` once, then `node --test`. diff --git a/.github/actions/update-wp-version/action.yml b/.github/actions/update-wp-version/action.yml new file mode 100644 index 0000000..c6a4bd4 --- /dev/null +++ b/.github/actions/update-wp-version/action.yml @@ -0,0 +1,64 @@ +# Sets the WordPress version a plugin is tested up to and, when asked, the minimum it requires: a +# version given, or two minor versions behind. It rewrites the headers in readme.txt and the plugin +# file only: it commits nothing, so the step that commits the release preparation carries the change. +# +# The logic lives in update-wp-version.js, run by actions/github-script, so there is no dependency +# to install and nothing to build. +name: Update the WordPress version +description: Sets the 'Tested up to' WordPress version and, optionally, the 'Requires at least' minimum + +inputs: + tested-up-to: + description: >- + The WordPress version to set as `Tested up to`, e.g. `6.8` or `6.8.1`: two or three numeric + parts, none zero-padded. Empty is the latest WordPress release, read from + api.wordpress.org; a failed lookup fails the step. Anything else fails before any file is + written. + required: false + default: '' + min-version: + description: >- + The `Requires at least` version. Empty leaves it. `auto` sets it two minor versions behind + `tested-up-to`, e.g. `6.8.1` gives `6.6` and `7.0` gives `6.8`, and never lowers a higher + minimum a file already has. A version such as `6.9` sets exactly that, lower or not, and may + not be above `tested-up-to`. Anything else fails before any file is + written. + required: false + default: '' + working-directory: + description: >- + Where the repository is checked out, relative to the workspace or absolute. Empty is the + workspace. A directory that is not there fails before any file is written. + required: false + default: '' + +outputs: + min-version: + description: 'The minimum version set, e.g. `6.6`. Empty when `min-version` is empty.' + value: ${{ steps.update.outputs.min-version }} + changed: + description: >- + `true` when a file was written, `false` when every header was already at its version, was + left above it, or no file carries one, so a later step can skip the commit. + value: ${{ steps.update.outputs.changed }} + +runs: + using: 'composite' + steps: + - name: Update the WordPress version + id: update + 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_TESTED_UP_TO: ${{ inputs.tested-up-to }} + INPUT_MIN_VERSION: ${{ inputs.min-version }} + INPUT_WORKING_DIRECTORY: ${{ inputs.working-directory }} + with: + script: | + const { runUpdateWpVersion } = require(`${process.env.ACTION_PATH}/update-wp-version.js`) + await runUpdateWpVersion({ core, env: process.env }) diff --git a/.github/actions/update-wp-version/update-wp-version.js b/.github/actions/update-wp-version/update-wp-version.js new file mode 100644 index 0000000..e4b0ec7 --- /dev/null +++ b/.github/actions/update-wp-version/update-wp-version.js @@ -0,0 +1,334 @@ +'use strict' + +/** + * Sets the WordPress version a plugin is tested up to and, when asked, the minimum it requires: + * a version given, or two minor versions behind the tested one. + * + * `Tested up to:` is set in readme.txt, and in the plugin file when it carries that header. + * `Requires at least:` is set in readme.txt and in the plugin file. The plugin file is the single + * root-level PHP file .puprc lists under `paths.versions`. + * + * Only an existing header is rewritten: a file without one is left as it is. `Tested up to` is + * never lowered: a file at 7.1.4 stays there when 7.1 is asked for. Neither is `Requires at least` + * when `min-version` is `auto`; a version given exactly is set as it is, lower or not. The action + * writes files and commits nothing. + * + * runUpdateWpVersion checks every input and the .puprc before it writes any file. + */ + +const fs = require('node:fs') +const path = require('node:path') + +const { readVersionFiles } = require('../../lib/puprc.js') +const { compareVersions } = require('../../lib/versions.js') +const { readWorkingDirectory, readCheckoutFile } = require('../../lib/workspace.js') + +/** What was not done, to close every error message. */ +const WHAT = 'No file was changed.' + +/** A WordPress version: two or three numeric parts, none zero-padded, so 6.010 is never read as 6.10. */ +const VERSION_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)(\.(0|[1-9]\d*))?$/ + +/** A PHP file at the root of the checkout. */ +const ROOT_PHP = /^[^/\\]+\.php$/ + +/** The WordPress.org endpoint whose first offer is the latest WordPress release. */ +const VERSION_CHECK_URL = 'https://api.wordpress.org/core/version-check/1.7/' + +/** The header that is never lowered. */ +const TESTED = 'Tested up to' + +/** The header `min-version` sets, never lowered when it is `auto`. */ +const REQUIRES = 'Requires at least' + +/** How many minor versions the minimum trails the tested version by. */ +const MINORS_BEHIND = 2 + +/** + * Looks up the latest WordPress release: the first offer of the WordPress.org version check. + * + * @param {Function} fetchImpl What `fetch` to use; a test passes a stand-in. + * + * @throws {Error} When the request fails, or the answer holds no version such as 6.8 or 6.8.1. + * + * @returns {Promise} The version. + */ +async function latestWordPress(fetchImpl) { + let body + try { + const response = await fetchImpl(VERSION_CHECK_URL) + if (!response.ok) { + throw new Error(`HTTP ${response.status}`) + } + body = await response.json() + } catch (error) { + throw new Error( + `Looking up the latest WordPress release failed (${error.message}). Pass tested-up-to and run this step again. ${WHAT}` + ) + } + + // The version is written into the plugin's files, so an answer of any other shape is refused. + const version = body?.offers?.[0]?.version + if (typeof version !== 'string' || !VERSION_PATTERN.test(version)) { + throw new Error( + `The latest WordPress release has no usable version in ${VERSION_CHECK_URL}. Pass tested-up-to and run this step again. ${WHAT}` + ) + } + + return version +} + +/** + * Reads the `tested-up-to` input. Empty means the latest WordPress release. + * + * @param {string} value The input value. + * @param {Function} fetchImpl What `fetch` to use for the latest release. + * + * @throws {Error} When it is not a version such as 6.8 or 6.8.1, or it is empty and the latest + * release cannot be looked up. + * + * @returns {Promise} The version. + */ +async function readTestedUpTo(value, fetchImpl) { + const version = String(value ?? '').trim() + + if (version === '') { + return latestWordPress(fetchImpl) + } + + if (!VERSION_PATTERN.test(version)) { + throw new Error( + `tested-up-to must look like 6.8 or 6.8.1, with no zero-padded part, got '${version}'. ${WHAT}` + ) + } + + return version +} + +/** + * The minimum version for a tested one: two minors behind, major and minor only. + * + * WordPress runs each major from x.0 to x.9 and then moves to the next (2.9, 3.0, ... 6.9, 7.0), + * so two minors behind 7.0 is 6.8 and two behind 7.1 is 6.9. + * + * @param {string} tested The tested version. + * + * @throws {Error} When the minimum would fall below 1.0. + * + * @returns {string} The minimum, e.g. 6.6 for 6.8.1. + */ +function minimumFor(tested) { + const [major, minor] = tested.split('.').map(Number) + const [minMajor, minMinor] = + minor >= MINORS_BEHIND ? [major, minor - MINORS_BEHIND] : [major - 1, minor - MINORS_BEHIND + 10] + + if (minMajor < 1) { + throw new Error( + `Cannot derive a minimum version two minors behind ${tested}; pass min-version as a version. ${WHAT}` + ) + } + + return `${minMajor}.${minMinor}` +} + +/** + * Reads the `min-version` input. + * + * @param {string} value The input value: empty, `auto`, or a version. + * @param {string} tested The tested version, which `auto` counts back from and a version may not exceed. + * + * @throws {Error} When it is none of those, is a version above the tested one, or `auto` derives none. + * + * @returns {{minimum: string, auto: boolean}} The minimum to set, empty to leave it, and whether + * `auto` derived it. + */ +function readMinVersion(value, tested) { + const min = String(value ?? '').trim() + + if (min === '') { + return { minimum: '', auto: false } + } + + if (min.toLowerCase() === 'auto') { + return { minimum: minimumFor(tested), auto: true } + } + + if (!VERSION_PATTERN.test(min)) { + throw new Error( + `min-version must be empty, auto, or a version like 6.9 or 6.9.1 with no zero-padded part, got '${min}'. ${WHAT}` + ) + } + + if (compareVersions(min, tested) > 0) { + throw new Error(`min-version ${min} is above the tested version ${tested}. ${WHAT}`) + } + + return { minimum: min, auto: false } +} + +/** + * Finds the plugin file: the single root-level PHP file .puprc lists under `paths.versions`. + * + * @param {string} cwd The checkout. + * @param {boolean} required Whether the file is needed. When it is not, an unusable .puprc is no error. + * + * @throws {Error} When the file is required and .puprc is unusable, lists no root PHP file or + * several, or lists one that is not a file. + * + * @returns {string|null} The file, relative to the checkout, or null when there is none to use. + */ +function readPluginFile(cwd, required) { + let files + try { + // A plugin file is listed once per regex, so the names are deduplicated. `./plugin.php` names + // the same root file as `plugin.php`. + files = [ + ...new Set( + readVersionFiles(readCheckoutFile(cwd, '.puprc'), WHAT) + .map((entry) => entry.file.replace(/^\.\//, '')) + .filter((file) => ROOT_PHP.test(file)) + ), + ] + } catch (error) { + if (required) { + throw error + } + + return null + } + + const isFile = files.length === 1 && fs.statSync(path.join(cwd, files[0]), { throwIfNoEntry: false })?.isFile() + + if (isFile) { + return files[0] + } + + if (!required) { + return null + } + + const got = files.length === 0 ? 'none' : files.map((file) => `'${file}'`).join(', ') + + throw new Error( + `.puprc must list exactly one root PHP file under paths.versions, got ${got}` + + `${files.length === 1 ? ', which is not a file' : ''}. The minimum version is set in that file. ${WHAT}` + ) +} + +/** + * Whether a header's current value is above the version to set, so setting it would lower it. + * + * Only the leading numeric parts count: `7.1.4` is above `7.1`, and `6.8-RC1` is not above `6.8`. + * A value with no numeric part, such as `trunk`, is never above. + * + * @param {string} current The value in the file. + * @param {string} version The version to set. + * + * @returns {boolean} True when the current value is the higher version. + */ +function isAbove(current, version) { + const numeric = current.match(/^\d+(\.\d+)*/)?.[0] + + return numeric !== undefined && compareVersions(numeric, version) > 0 +} + +/** + * Sets headers in a file of the checkout. Only the first line carrying each header changes, so a + * version quoted further down is left alone. A header the file does not carry is not added, and + * a header in `keep` is never lowered. + * + * @param {string} cwd The checkout. + * @param {string} file The file, relative to it. + * @param {Object} headers The version per header name. + * @param {Set} keep The header names never to lower. + * + * @returns {{lines: string[], changed: boolean}} What happened to each header the file carries, and + * whether the file was written. + */ +function setHeaders(cwd, file, headers, keep) { + const before = readCheckoutFile(cwd, file) + if (before === null) { + return { lines: [], changed: false } + } + + let after = before + const lines = [] + + for (const [name, version] of Object.entries(headers)) { + // The line shape WordPress reads a header from: comment characters, the name, a colon. The + // whole value up to the next space or `*/` is replaced, so `6.8-RC1` becomes `6.8`, and a + // comment closed right after the value stays closed. + const header = new RegExp(`^([ \\t/*#@]*${name}:[ \\t]*)((?:(?!\\*\\/)\\S)*)`, 'im') + const current = after.match(header)?.[2] + + if (current === undefined) { + continue + } + + if (current === version) { + lines.push(`${name} already at ${version}`) + } else if (keep.has(name) && isAbove(current, version)) { + lines.push(`${name} left at ${current}, which is above ${version}`) + } else { + after = after.replace(header, (match, lead) => `${lead}${version}`) + lines.push(`${name} changed from ${current} to ${version}`) + } + } + + if (after !== before) { + fs.writeFileSync(path.join(cwd, file), after) + } + + return { lines, changed: after !== before } +} + +/** + * Runs the action. + * + * @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, holding the inputs as `INPUT_*`. + * @param {string} options.cwd The workspace, the process's working directory by default. + * @param {Function} options.fetchImpl What `fetch` to use for the latest release; a test passes a stand-in. + * + * @throws {Error} When an input is refused, the latest release cannot be looked up, `auto` derives + * no minimum, or a minimum is asked for and .puprc does not name the plugin file. + * + * @returns {Promise} Resolves once the files, the outputs and the summary are written. + */ +async function runUpdateWpVersion({ core, env, cwd: workspace = process.cwd(), fetchImpl = globalThis.fetch }) { + const tested = await readTestedUpTo(env.INPUT_TESTED_UP_TO, fetchImpl) + const { minimum, auto } = readMinVersion(env.INPUT_MIN_VERSION, tested) + const cwd = readWorkingDirectory(env.INPUT_WORKING_DIRECTORY, { base: workspace, what: WHAT }) + const pluginFile = readPluginFile(cwd, minimum !== '') + + // Everything is checked by now; the writes start here. + const headers = { [TESTED]: tested, ...(minimum ? { [REQUIRES]: minimum } : {}) } + const keep = new Set(auto ? [TESTED, REQUIRES] : [TESTED]) + const results = ['readme.txt', pluginFile] + .filter((file) => file !== null) + .map((file) => ({ file, ...setHeaders(cwd, file, headers, keep) })) + const lines = results.flatMap(({ file, lines }) => lines.map((line) => `\`${file}\`: ${line}`)) + + if (lines.length === 0) { + core.warning('No file carries a header to set, so nothing was written.') + } + + core.setOutput('min-version', minimum) + core.setOutput('changed', String(results.some((result) => result.changed))) + core.info(`Tested up to ${tested}, minimum ${minimum || 'unchanged'}.`) + lines.forEach((line) => core.info(line.replaceAll('`', ''))) + await core.summary + .addRaw( + [ + '## Version Updates', + `* Tested Up To: \`${tested}\``, + `* Minimum Required Version: ${minimum ? `\`${minimum}\`` : 'Unchanged'}`, + ...lines.map((line) => `* ${line}`), + ].join('\n'), + true + ) + .write() +} + +module.exports = { runUpdateWpVersion } diff --git a/tests/actions/update-wp-version/update-wp-version.test.js b/tests/actions/update-wp-version/update-wp-version.test.js new file mode 100644 index 0000000..d4c1744 --- /dev/null +++ b/tests/actions/update-wp-version/update-wp-version.test.js @@ -0,0 +1,407 @@ +'use strict' + +const { describe, it, beforeEach, afterEach } = require('node:test') +const assert = require('node:assert') +const fs = require('node:fs') +const os = require('node:os') +const path = require('node:path') + +const { runUpdateWpVersion } = require('../../../.github/actions/update-wp-version/update-wp-version.js') +const { coreWithOutputs } = require('../../support/actions.js') + +const README = `=== Test Plugin === + +Contributors: someone +Stable tag: 1.2.3 +Requires at least: 6.0 +Tested up to: 6.4 +Requires PHP: 7.4 + +== Description == + +Tested up to: 6.2 was the previous target. +` + +const PLUGIN = ` { + throw new Error('No lookup was expected.') +} + +/** A fetch answering the WordPress version-check endpoint with the given body and status. */ +const versionCheck = (body, status = 200) => { + const calls = [] + const fetchImpl = async (url) => { + calls.push(url) + return new Response(typeof body === 'string' ? body : JSON.stringify(body), { status }) + } + return { fetchImpl, calls } +} + +/** A .puprc listing the given version files, the plugin file twice as real ones do. */ +const puprc = (files = ['test-plugin.php', 'test-plugin.php', 'readme.txt', 'src/Main.php']) => + JSON.stringify({ paths: { versions: files.map((file) => ({ file, regex: '(Version: )(.+)' })) } }) + +describe('update-wp-version', () => { + let dir + + const write = (name, body) => { + fs.mkdirSync(path.dirname(path.join(dir, name)), { recursive: true }) + fs.writeFileSync(path.join(dir, name), body) + } + + const read = (name) => fs.readFileSync(path.join(dir, name), 'utf8') + + /** Every file of the checkout, to assert a refusal wrote nothing. */ + const snapshot = () => + Object.fromEntries( + fs + .readdirSync(dir, { recursive: true, withFileTypes: true }) + .filter((entry) => entry.isFile()) + .map((entry) => path.join(entry.parentPath, entry.name)) + .sort() + .map((file) => [path.relative(dir, file), fs.readFileSync(file, 'utf8')]) + ) + + const run = async (t, tested, min, inputs = {}, fetchImpl = noFetch) => { + const { core, outputs, logged, summary } = await coreWithOutputs(t) + + await runUpdateWpVersion({ + core, + cwd: dir, + fetchImpl, + env: { INPUT_TESTED_UP_TO: tested, INPUT_MIN_VERSION: min, ...inputs }, + }) + + return { outputs: outputs(), logged: logged(), summary: summary() } + } + + /** Asserts the run is refused with the message, with no file changed and no output set. */ + const refuses = async (t, tested, min, message, fetchImpl = noFetch) => { + const before = snapshot() + const { core, outputs } = await coreWithOutputs(t) + + await assert.rejects( + runUpdateWpVersion({ + core, + cwd: dir, + fetchImpl, + env: { INPUT_TESTED_UP_TO: tested, INPUT_MIN_VERSION: min }, + }), + (error) => message.test(error.message) && error.message.endsWith('No file was changed.') + ) + assert.deepStrictEqual(snapshot(), before) + assert.deepStrictEqual(outputs(), {}) + } + + beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'toolbox-update-wp-version-')) + write('readme.txt', README) + write('test-plugin.php', PLUGIN) + write('.puprc', puprc()) + write('.github/workflows/tests-php.yml', WORKFLOW) + }) + + afterEach(() => { + fs.rmSync(dir, { recursive: true, force: true }) + }) + + it('sets the tested version and the minimum two minors behind it', async (t) => { + const { outputs, summary } = await run(t, '6.8.1', 'auto') + + assert.strictEqual(outputs['min-version'], '6.6') + assert.strictEqual(outputs.changed, 'true') + assert.match(read('readme.txt'), /^Tested up to: 6\.8\.1$/m) + assert.match(read('readme.txt'), /^Requires at least: 6\.6$/m) + assert.strictEqual(read('test-plugin.php'), PLUGIN.replace('least: 6.0', 'least: 6.6')) + assert.strictEqual(read('.github/workflows/tests-php.yml'), WORKFLOW) + assert.strictEqual( + summary, + '## Version Updates\n' + + '* Tested Up To: `6.8.1`\n' + + '* Minimum Required Version: `6.6`\n' + + '* `readme.txt`: Tested up to changed from 6.4 to 6.8.1\n' + + '* `readme.txt`: Requires at least changed from 6.0 to 6.6\n' + + '* `test-plugin.php`: Requires at least changed from 6.0 to 6.6\n' + ) + }) + + it('takes a version of two parts', async (t) => { + const { outputs } = await run(t, '6.8', 'auto') + + assert.strictEqual(outputs['min-version'], '6.6') + assert.match(read('readme.txt'), /^Tested up to: 6\.8$/m) + }) + + it('leaves the minimum alone unless asked, and needs no .puprc for it', async (t) => { + fs.rmSync(path.join(dir, '.puprc')) + const { outputs, summary } = await run(t, '7.0', '') + + assert.strictEqual(outputs['min-version'], '') + assert.strictEqual(read('readme.txt'), README.replace('up to: 6.4', 'up to: 7.0')) + assert.strictEqual(read('test-plugin.php'), PLUGIN) + assert.match(summary, /\* Minimum Required Version: Unchanged\n\* `readme.txt`: Tested up to changed from 6\.4 to 7\.0\n$/) + }) + + it('changes the header only, not a version quoted further down', async (t) => { + await run(t, '6.8', '') + + assert.match(read('readme.txt'), /^Tested up to: 6\.2 was the previous target\.$/m) + }) + + it('replaces the whole previous version, a pre-release suffix included', async (t) => { + write('readme.txt', README.replace('up to: 6.4', 'up to: 6.8-RC1')) + await run(t, '6.8', '') + + assert.match(read('readme.txt'), /^Tested up to: 6\.8$/m) + }) + + it('keeps a comment close that directly follows the value', async (t) => { + write('test-plugin.php', PLUGIN.replace(' * Requires at least: 6.0\n */', ' * Requires at least: 6.0*/')) + await run(t, '6.8', 'auto') + + assert.match(read('test-plugin.php'), /^ \* Requires at least: 6\.6\*\/$/m) + }) + + it('reports a header already at the version, and sets changed to false when nothing changed', async (t) => { + await run(t, '6.8', 'auto') + const { outputs, summary, logged } = await run(t, '6.8', 'auto') + + assert.strictEqual(outputs.changed, 'false') + assert.match(summary, /\* `readme.txt`: Tested up to already at 6\.8\n/) + assert.match(summary, /\* `test-plugin.php`: Requires at least already at 6\.6\n$/) + assert.match(logged, /readme\.txt: Tested up to already at 6\.8/) + }) + + it('never lowers Tested up to, and says so', async (t) => { + write('readme.txt', README.replace('up to: 6.4', 'up to: 7.1.4')) + write('test-plugin.php', PLUGIN_TESTED.replace('up to: 6.4', 'up to: 7.0')) + const { outputs, summary } = await run(t, '7.1', '') + + assert.strictEqual(outputs.changed, 'true') + assert.strictEqual(read('readme.txt'), README.replace('up to: 6.4', 'up to: 7.1.4')) + assert.match(summary, /\* `readme.txt`: Tested up to left at 7\.1\.4, which is above 7\.1\n/) + assert.match(summary, /\* `test-plugin.php`: Tested up to changed from 7\.0 to 7\.1\n$/) + + write('test-plugin.php', PLUGIN) + const again = await run(t, '7.1', '') + assert.strictEqual(again.outputs.changed, 'false') + }) + + it('never lowers Requires at least with auto, but sets a lower version given exactly', async (t) => { + write('test-plugin.php', PLUGIN.replace('least: 6.0', 'least: 6.9')) + const { outputs, summary } = await run(t, '7.0', 'auto') + + assert.strictEqual(outputs['min-version'], '6.8') + assert.strictEqual(read('test-plugin.php'), PLUGIN.replace('least: 6.0', 'least: 6.9')) + assert.match(summary, /\* `readme.txt`: Requires at least changed from 6\.0 to 6\.8\n/) + assert.match(summary, /\* `test-plugin.php`: Requires at least left at 6\.9, which is above 6\.8\n$/) + + await run(t, '7.0', '6.7') + assert.strictEqual(read('test-plugin.php'), PLUGIN.replace('least: 6.0', 'least: 6.7')) + }) + + it('updates a Tested up to header the plugin file carries, and adds none', async (t) => { + write('test-plugin.php', PLUGIN_TESTED) + const { summary } = await run(t, '6.8', '') + + assert.strictEqual(read('test-plugin.php'), PLUGIN_TESTED.replace('up to: 6.4', 'up to: 6.8')) + assert.match(summary, /\* `test-plugin.php`: Tested up to changed from 6\.4 to 6\.8\n$/) + + await run(t, '6.9', 'auto') + assert.strictEqual( + read('test-plugin.php'), + PLUGIN_TESTED.replace('up to: 6.4', 'up to: 6.9').replace('least: 6.0', 'least: 6.7') + ) + + write('test-plugin.php', PLUGIN) + await run(t, '6.9', '') + assert.strictEqual(read('test-plugin.php'), PLUGIN) + }) + + it('passes without a readme.txt, or with one that has no header, and warns when nothing was written', async (t) => { + fs.rmSync(path.join(dir, 'readme.txt')) + const { outputs, summary } = await run(t, '6.8', 'auto') + + assert.strictEqual(outputs['min-version'], '6.6') + assert.match(read('test-plugin.php'), /Requires at least: 6\.6/) + assert.ok(!summary.includes('readme.txt')) + + write('readme.txt', '== Changelog ==\n\n* Fix - Something.\n') + const { logged, outputs: noHeader } = await run(t, '6.8', '') + + assert.strictEqual(read('readme.txt'), '== Changelog ==\n\n* Fix - Something.\n') + assert.strictEqual(noHeader.changed, 'false') + assert.match(logged, /::warning::No file carries a header to set/) + }) + + it('works in the directory the repository is checked out in', async (t) => { + const workspace = dir + dir = path.join(workspace, 'source') + write('readme.txt', README) + dir = workspace + const { core } = await coreWithOutputs(t) + + await runUpdateWpVersion({ + core, + cwd: workspace, + env: { INPUT_TESTED_UP_TO: '6.8', INPUT_MIN_VERSION: '', INPUT_WORKING_DIRECTORY: 'source' }, + }) + + assert.match(read('source/readme.txt'), /^Tested up to: 6\.8$/m) + assert.strictEqual(read('readme.txt'), README) + }) + + it('refuses a version that is not two or three plain numeric parts', async (t) => { + const bad = [ + 'banana', + '6', + '6.8.1.2', + 'v6.8', + // Zero-padded parts: 6.010 is not 6.10. + '6.08', + '6.010', + '06.8', + // An input is data, so a shell payload is only a wrong version. + '6.8"; touch INJECTED; #', + '6.8$(touch INJECTED)', + '6.8`touch INJECTED`', + '6.8\nRequires at least: 1.0', + ] + + for (const version of bad) { + await refuses(t, version, 'auto', /must look like 6\.8 or 6\.8\.1/) + await refuses(t, version, '', /must look like 6\.8 or 6\.8\.1/) + } + }) + + it('sets the latest WordPress release when tested-up-to is empty', async (t) => { + const { fetchImpl, calls } = versionCheck({ offers: [{ version: '6.8.3' }, { version: '6.7.4' }] }) + await run(t, ' ', '', {}, fetchImpl) + + assert.deepStrictEqual(calls, ['https://api.wordpress.org/core/version-check/1.7/']) + assert.match(read('readme.txt'), /^Tested up to: 6\.8\.3$/m) + }) + + it('refuses when the latest WordPress release cannot be looked up', async (t) => { + const failed = /Looking up the latest WordPress release failed/ + const unusable = /The latest WordPress release has no usable version/ + + await refuses(t, '', '', failed, versionCheck({}, 500).fetchImpl) + await refuses(t, '', '', failed, versionCheck('').fetchImpl) + await refuses(t, '', '', failed, async () => { + throw new Error('getaddrinfo ENOTFOUND') + }) + await refuses(t, '', '', unusable, versionCheck({}).fetchImpl) + await refuses(t, '', '', unusable, versionCheck({ offers: [] }).fetchImpl) + await refuses(t, '', '', unusable, versionCheck({ offers: [{ version: '6.8; rm -rf' }] }).fetchImpl) + }) + + it('takes the minimum two minors back across a major version, as WordPress went from 6.9 to 7.0', async (t) => { + const expected = { '7.0': '6.8', '7.1': '6.9', '6.1.0': '5.9', '7.2.1': '7.0' } + + for (const [tested, minimum] of Object.entries(expected)) { + write('readme.txt', README.replace('least: 6.0', 'least: 1.0')) + const { outputs } = await run(t, tested, 'auto') + + assert.strictEqual(outputs['min-version'], minimum, tested) + assert.match(read('readme.txt'), new RegExp(`^Requires at least: ${minimum.replace('.', '\\.')}$`, 'm')) + } + }) + + it('refuses to derive a minimum below 1.0, and takes 1.0 from 1.2', async (t) => { + for (const tested of ['0.1', '0.2', '1.0', '1.1']) { + await refuses(t, tested, 'auto', new RegExp(`Cannot derive a minimum version two minors behind ${tested.replace('.', '\\.')}`)) + } + + write('readme.txt', README.replace('least: 6.0', 'least: 0.5')) + const { outputs } = await run(t, '1.2', 'auto') + assert.strictEqual(outputs['min-version'], '1.0') + }) + + it('sets a minimum given as a version exactly', async (t) => { + const { outputs } = await run(t, '7.0', ' 6.9 ') + + assert.strictEqual(outputs['min-version'], '6.9') + assert.match(read('readme.txt'), /^Requires at least: 6\.9$/m) + assert.strictEqual(read('test-plugin.php'), PLUGIN.replace('least: 6.0', 'least: 6.9')) + }) + + it('refuses a min-version that is not empty, auto or a version', async (t) => { + for (const min of ['yes', 'no', 'true', '6', 'v6.9', '6.09', '6.9-RC1']) { + await refuses(t, '6.8', min, /min-version must be empty, auto, or a version like 6\.9/) + } + }) + + it('refuses a min-version above the tested version', async (t) => { + await refuses(t, '6.8', '6.9', /min-version 6\.9 is above the tested version 6\.8/) + }) + + it('refuses a working-directory that is not there', async (t) => { + const { core } = await coreWithOutputs(t) + + await assert.rejects( + runUpdateWpVersion({ + core, + cwd: dir, + env: { INPUT_TESTED_UP_TO: '6.8', INPUT_MIN_VERSION: '', INPUT_WORKING_DIRECTORY: 'nowhere' }, + }), + /working-directory 'nowhere' is not a directory/ + ) + }) + + it('refuses to update the minimum unless .puprc lists exactly one root PHP file that exists', async (t) => { + const exactlyOne = /\.puprc must list exactly one root PHP file under paths\.versions/ + + write('other.php', PLUGIN) + write('.puprc', puprc(['test-plugin.php', 'other.php'])) + await refuses(t, '6.8', 'auto', /exactly one root PHP file under paths\.versions, got 'test-plugin\.php', 'other\.php'/) + + write('.puprc', puprc(['src/Main.php', 'readme.txt'])) + await refuses(t, '6.8', 'auto', exactlyOne) + + write('.puprc', puprc(['missing.php'])) + await refuses(t, '6.8', 'auto', /got 'missing\.php', which is not a file/) + + write('.puprc', '{nope') + await refuses(t, '6.8', 'auto', /\.puprc is not valid JSON/) + + fs.rmSync(path.join(dir, '.puprc')) + await refuses(t, '6.8', 'auto', /No \.puprc/) + }) + + it('takes a plugin file .puprc lists with a leading ./', async (t) => { + write('.puprc', puprc(['./test-plugin.php', './test-plugin.php', 'readme.txt'])) + await run(t, '6.8', 'auto') + + assert.strictEqual(read('test-plugin.php'), PLUGIN.replace('least: 6.0', 'least: 6.6')) + }) + + it('still sets the tested version in readme.txt when .puprc names no single plugin file', async (t) => { + write('other.php', PLUGIN_TESTED) + write('.puprc', puprc(['test-plugin.php', 'other.php'])) + await run(t, '6.8', '') + + assert.match(read('readme.txt'), /^Tested up to: 6\.8$/m) + assert.strictEqual(read('other.php'), PLUGIN_TESTED) + }) +})