From d49c960006465f5998fa544ceedbff93f89f7d1c Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Mon, 30 Nov 2026 17:10:15 -0300 Subject: [PATCH 01/45] Add herald-publish: the build uploaded to Herald and published as a version A paid release reaches Herald by hand today: a person uploads the ZIP in the dashboard, fills in the release date and the changelog, creates the version and publishes it. herald-publish does the same from the deploy workflow, with a Herald API key of scope ci. It uploads the ZIP, creates the version when the product does not have it yet, then points the version at the ZIP and sets the status, the changelog and the release date in one update. Herald reads the plugin header of what it stores, and a ZIP whose header holds another version is refused before any version is touched. A rerun for the same version updates it instead of creating it twice, and reuses a ZIP Herald already holds. Every input is checked before the first call, and each failure says what Herald holds at that point. The release template shows the step, commented out, between the build and release-publish. SOFT-5788 --- .github/actions/herald-publish/README.md | 146 ++++++ .github/actions/herald-publish/action.yml | 92 ++++ .../actions/herald-publish/herald-publish.js | 495 ++++++++++++++++++ README.md | 1 + templates/workflows/release.yml | 11 + .../herald-publish/herald-publish.test.js | 385 ++++++++++++++ 6 files changed, 1130 insertions(+) create mode 100644 .github/actions/herald-publish/README.md create mode 100644 .github/actions/herald-publish/action.yml create mode 100644 .github/actions/herald-publish/herald-publish.js create mode 100644 tests/actions/herald-publish/herald-publish.test.js diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md new file mode 100644 index 00000000..64400f35 --- /dev/null +++ b/.github/actions/herald-publish/README.md @@ -0,0 +1,146 @@ +# herald-publish + +Publishes a plugin ZIP to [Herald](https://github.com/stellarwp/herald), the service customers +download paid plugins from. It uploads the ZIP, creates the version when the product does not have +it yet, then points the version at the ZIP and sets its status, release date and changelog. + +It is what a person does by hand in the Herald dashboard for a paid release: New Version, Upload +new, the release date and the changelog, Create, then Publish. In a deploy it runs after the build +and before [release-publish](../release-publish/README.md), so a failed upload leaves no GitHub +release behind: + +```yaml +- uses: stellarwp/plugin-toolbox/.github/actions/release-merge@v1 + id: merge + with: + branch: ${{ inputs.branch }} + version: ${{ inputs.version }} + +- uses: actions/checkout@v6 + with: + ref: ${{ steps.merge.outputs.base-sha }} + +# Build the plugin here, from the merged commit. + +- uses: stellarwp/plugin-toolbox/.github/actions/herald-publish@v1 + with: + herald-url: ${{ vars.HERALD_URL }} + product: my-plugin + version: ${{ inputs.version }} + zip: build/my-plugin.zip + api-key: ${{ secrets.HERALD_API_KEY }} + +- uses: stellarwp/plugin-toolbox/.github/actions/release-publish@v1 + with: + version: ${{ inputs.version }} + target: ${{ steps.merge.outputs.base-sha }} + files: | + build/my-plugin.zip +``` + +`product` is the slug of the product in Herald, which is not always the repository's name. The +product has to exist: the action creates versions, never products. + +## What it does + +1. Checks every input before any call: the address, the slug, the version, the status, the ZIP and + the changelog file. +2. Uploads the ZIP (`POST /api/v1/zips/upload`). Herald stores it, computes its SHA-256 and reads the + plugin header inside. +3. Compares the version Herald read from the ZIP with `version`, and stops when they differ. A ZIP of + another version, or of another plugin on another version, is not published under this one. +4. Reads the version of the product (`GET /api/v1/products/{product}/versions/{version}`) and + creates it when it is missing (`POST /api/v1/products/{product}/versions`). A new version is a + draft. +5. Updates the version in one call (`PATCH` on the same address): the ZIP, the status, and the + changelog and the release date when they were given. Herald writes them together, so a refused + update never leaves the version published with the old ZIP. + +The run log and the job summary show the ZIP id and its SHA-256. + +## Inputs + +| Input | Required | Default | What it is | +|---|---|---|---| +| `herald-url` | yes | | The address of the Herald instance. HTTPS only. | +| `product` | yes | | The slug of the product in Herald. | +| `version` | yes | | The version being released: three or four numeric parts. | +| `zip` | yes | | The build to upload, a `.zip` path relative to the checkout. | +| `status` | no | `published` | `draft`, `review` or `published`. Only a published version is served to customers. | +| `changelog-file` | no | | A file with the entries of this version, one per line, each starting with `* `. Empty keeps the changelog Herald has. | +| `release-date` | no | | `YYYY-MM-DD`. Empty gives a new version today's date in UTC and leaves an existing version's date alone. | +| `api-key` | yes | | A Herald API key of scope `ci`, from a secret. | + +The changelog file holds entries only, with no version and no date: + +```text +* Fix - Resolved an error when the fee is disabled for the gateway. +* New - Added a setting for the maximum fee. +``` + +Herald shows the field as it is, and a header in it breaks the page the changelog appears on. The +action refuses a file with a line that is not an entry. + +## Outputs + +| Output | What it is | +|---|---| +| `zip-id` | The id of the ZIP record in Herald. | +| `sha256` | The SHA-256 Herald computed for the ZIP. Empty when Herald already held the same bytes. | +| `status` | The status the version was left in. | +| `created` | `true` when the version was created, `false` when it existed and was updated. | + +## Running it again + +A run can be repeated after a late failure, for the same version: + +- **The version exists.** It is updated to point at the ZIP of this run. No second version is + created. +- **The build came out identical.** Herald refuses bytes it already stores and names the record in + the refusal. The action takes that id and goes on. It cannot read that ZIP's plugin header with a + `ci` key, so the version check of step 3 is skipped for a reused ZIP. +- **Another run created the version in between.** The create is refused as a duplicate, and the + action goes on to the update. + +When a step fails, the error says what Herald holds at that point: nothing, the ZIP with no version +pointing at it, or a new version left as a draft. + +## The key, and who can publish + +The key is a Herald API key of scope `ci`. That scope can upload ZIPs and create, read and update +versions, and nothing else: it cannot delete a version or touch products, brands or other keys. +Herald's `docs/github-actions.md` says how to create one. + +With `status: published`, the version is live in Herald when the step ends, with no second click +there. So whoever can start the deploy can publish. On GitHub, starting a workflow by hand +[needs write access to the repository](https://docs.github.com/en/actions/how-tos/manage-workflow-runs/manually-run-a-workflow): +keep that access to the people who release and to the app that dispatches for the release +dashboard, where the review and the QA approval come before the deploy. + +How much more to add is each repository's choice: + +- Keep the key as a secret of an environment whose branch policy accepts only release branches, so + no run on another branch can read it. +- Give that environment required reviewers, for an approval on GitHub before the job starts. +- Pass `status: review`, to leave the last click in Herald. + +## What it leaves to do + +- **The Portal's catalogue.** `software.liquidweb.com` copies the latest published version from + Herald once a day + ([`SyncService.php`](https://github.com/stellarwp/software.liquidweb.com/blob/develop/content/themes/commerce-portal-theme/src/SLW/CommercePortal/CatalogFeature/SyncService.php)). + To show a release there at once, an administrator clicks **Sync All From Herald** and then + **Flush Catalog Cache** under Products → Catalog Features. +- **Customers on legacy licenses.** They do not get updates through Herald. The release to the + brand's own licensing site stays a step of its own. + +## How it runs + +The logic is in [`herald-publish.js`](./herald-publish.js), run by `actions/github-script`, with no +dependency to install. The calls use the runtime's `fetch`. A redirect is refused rather than +followed, since it would send the key to another address. The upload is given ten minutes and every +other call thirty seconds, so a request that hangs does not hold the deploy. + +Tests are in +[`tests/actions/herald-publish`](../../../tests/actions/herald-publish/herald-publish.test.js), with +Herald's answers recorded: `npm test`. diff --git a/.github/actions/herald-publish/action.yml b/.github/actions/herald-publish/action.yml new file mode 100644 index 00000000..32087e42 --- /dev/null +++ b/.github/actions/herald-publish/action.yml @@ -0,0 +1,92 @@ +# Publishes a plugin ZIP to Herald, the service customers download paid plugins from: uploads the ZIP, +# creates the version when the product does not have it yet, then points the version at the ZIP and +# sets its status, release date and changelog. What a person does by hand in the Herald dashboard +# for a paid release, as one step of the deploy. +# +# The logic lives in herald-publish.js, run by actions/github-script, so there is no dependency to +# install and nothing to build. The calls go to Herald's API, not GitHub's; the checkout is only +# read, for the ZIP and the changelog file. +name: Herald publish +description: Uploads a plugin ZIP to Herald and publishes it as a version of a product + +inputs: + herald-url: + description: >- + The address of the Herald instance, e.g. `https://herald.example.com`. HTTPS only: the API key + goes in every request. + required: true + product: + description: 'The slug of the product in Herald, as its Products page shows it.' + required: true + version: + description: >- + The version being released: three or four numeric parts, such as 4.17.0 or 4.17.0.1. A version + the product already has is updated, so a run can be repeated after a late failure. A ZIP whose + plugin header holds another version is refused. + required: true + zip: + description: 'The build to upload: the path of a `.zip`, relative to the checkout.' + required: true + status: + description: >- + The state the version is left in: `draft`, `review` or `published`. Only a published version + is served to customers. + required: false + default: 'published' + changelog-file: + description: >- + A file in the checkout with the changelog entries of this version, one per line, each starting + with `* `. No version and no date: Herald shows the field as it is. When empty, the changelog + Herald has for the version is kept. + required: false + default: '' + release-date: + description: >- + The release date, as `YYYY-MM-DD`. When empty, a new version gets today's date in UTC and an + existing version keeps its own. + required: false + default: '' + api-key: + description: >- + A Herald API key of scope `ci`, from a secret. That scope can upload ZIPs and create, read and + update versions, and nothing else. + required: true + +outputs: + zip-id: + description: 'The id of the ZIP record in Herald.' + value: ${{ steps.publish.outputs.zip-id }} + sha256: + description: 'The SHA-256 Herald computed for the ZIP. Empty when Herald already held the same bytes.' + value: ${{ steps.publish.outputs.sha256 }} + status: + description: 'The status the version was left in.' + value: ${{ steps.publish.outputs.status }} + created: + description: '`true` when the version was created, `false` when it existed and was updated.' + value: ${{ steps.publish.outputs.created }} + +runs: + using: 'composite' + steps: + - name: Publish the ZIP to Herald + id: publish + 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. + 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_HERALD_URL: ${{ inputs.herald-url }} + INPUT_PRODUCT: ${{ inputs.product }} + INPUT_VERSION: ${{ inputs.version }} + INPUT_ZIP: ${{ inputs.zip }} + INPUT_STATUS: ${{ inputs.status }} + INPUT_CHANGELOG_FILE: ${{ inputs.changelog-file }} + INPUT_RELEASE_DATE: ${{ inputs.release-date }} + INPUT_API_KEY: ${{ inputs.api-key }} + with: + script: | + const { runHeraldPublish } = require(`${process.env.ACTION_PATH}/herald-publish.js`) + await runHeraldPublish({ core, env: process.env }) diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js new file mode 100644 index 00000000..c9814bc5 --- /dev/null +++ b/.github/actions/herald-publish/herald-publish.js @@ -0,0 +1,495 @@ +'use strict' + +/** + * Publishes a plugin ZIP to Herald, the service customers download paid plugins from: uploads the + * ZIP, creates the version when the product does not have it yet, then points the version at the + * ZIP and sets its status, release date and changelog. + * + * It is what a person does by hand in the Herald dashboard for a paid release: New Version, Upload + * new, the release date and the changelog, Create, then Publish. A deploy workflow runs it after the + * build and before release-publish, so a failed upload leaves no GitHub release behind. + * + * Running it again for the same version is safe: the version is updated, never created twice, and a + * ZIP Herald already holds is reused. + * + * Herald is not the GitHub API, so the calls go through `fetch`, with a `ci` API key that can only + * upload ZIPs and create, read and update versions. + */ + +const fs = require('node:fs') +const path = require('node:path') + +const { validateVersion: validateReleaseVersion } = require('../../lib/versions.js') + +/** Closes every error message raised before the first write. */ +const NOTHING = 'Nothing was published to Herald.' + +/** The states a Herald version can be in. Only a published version is served to customers. */ +const STATUSES = ['draft', 'review', 'published'] + +/** How long the upload may take, and every other request. A hung request must not hold the deploy. */ +const UPLOAD_TIMEOUT_MS = 10 * 60 * 1000 +const REQUEST_TIMEOUT_MS = 30 * 1000 + +/** + * What Herald answers, with a 400, to a ZIP whose bytes it already holds. The id in the message is + * the only way a `ci` key learns which record that is, since it cannot list ZIPs. + */ +const DUPLICATE_ZIP = /a ZIP with this content already exists \(id: ([0-9a-f-]{36})\)/i + +/** + * Reads the version to publish: the shared rule, with this action's closing line. + * + * @param {string} version The `version` input. + * + * @throws {Error} When it is empty or not three or four numeric parts. + * + * @returns {string} The version, without surrounding whitespace. + */ +function validateVersion(version) { + return validateReleaseVersion(version, NOTHING) +} + +/** + * Reads the `herald-url` input: where Herald answers, with no path of its own to add. + * + * @param {string} url The input value. + * + * @throws {Error} When it is empty, not a URL, carries credentials, a query or a fragment, or is not + * HTTPS. Plain HTTP is accepted for a Herald on the same machine, for local tests. + * + * @returns {string} The URL without a trailing slash. + */ +function readUrl(url) { + const trimmed = String(url ?? '').trim() + + if (trimmed === '') { + throw new Error(`No herald-url was given: pass the address of the Herald instance. ${NOTHING}`) + } + + let parsed + try { + parsed = new URL(trimmed) + } catch { + throw new Error(`herald-url '${trimmed}' is not a URL. ${NOTHING}`) + } + + const local = ['localhost', '127.0.0.1'].includes(parsed.hostname) + if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && local)) { + throw new Error(`herald-url '${trimmed}' is not HTTPS, and the API key would travel in the clear. ${NOTHING}`) + } + + if (parsed.username !== '' || parsed.password !== '' || parsed.search !== '' || parsed.hash !== '') { + throw new Error(`herald-url has to be an address only, with no credentials, query or fragment. ${NOTHING}`) + } + + return `${parsed.origin}${parsed.pathname}`.replace(/\/+$/, '') +} + +/** + * Reads the `product` input: the slug of the product in Herald, as its Products page shows it. + * + * @param {string} product The input value. + * + * @throws {Error} When it is empty or holds whitespace or a URL delimiter. + * + * @returns {string} The slug, without surrounding whitespace. + */ +function readProduct(product) { + const trimmed = String(product ?? '').trim() + + if (trimmed === '') { + throw new Error(`No product was given: pass the slug of the product in Herald. ${NOTHING}`) + } + + if (/[\s/\\?#]/.test(trimmed)) { + throw new Error(`product '${trimmed}' is not a Herald slug: it holds a space or one of / \\ ? #. ${NOTHING}`) + } + + return trimmed +} + +/** + * Reads the `status` input: the state the version is left in. + * + * @param {string} status The input value. + * + * @throws {Error} When it is not one of Herald's three states. + * + * @returns {string} The status, `published` when the input is empty. + */ +function readStatus(status) { + const trimmed = String(status ?? '') + .trim() + .toLowerCase() + + if (trimmed === '') { + return 'published' + } + + if (!STATUSES.includes(trimmed)) { + throw new Error(`status '${String(status).trim()}' is not one of ${STATUSES.join(', ')}. ${NOTHING}`) + } + + return trimmed +} + +/** + * Reads the `zip` input: the build to upload. + * + * @param {string} zip The input value, a path relative to the checkout. + * @param {string} cwd The checkout. + * + * @throws {Error} When it is empty, not a `.zip`, not a file, or an empty file. + * + * @returns {{name: string, file: string, size: number}} The file's name, its path and its size. + */ +function readZip(zip, cwd) { + const trimmed = String(zip ?? '').trim() + + if (trimmed === '') { + throw new Error(`No zip was given: pass the path of the build to upload. ${NOTHING}`) + } + + if (!trimmed.toLowerCase().endsWith('.zip')) { + throw new Error(`zip '${trimmed}' is not a .zip file. ${NOTHING}`) + } + + const file = path.resolve(cwd, trimmed) + let stat + try { + stat = fs.statSync(file) + } catch { + stat = null + } + + if (!stat?.isFile()) { + throw new Error(`zip '${trimmed}' is not a file in the checkout. ${NOTHING}`) + } + + if (stat.size === 0) { + throw new Error(`zip '${trimmed}' is empty. ${NOTHING}`) + } + + return { name: path.basename(file), file, size: stat.size } +} + +/** + * Reads the `changelog-file` input: the entries of this version, one per line. + * + * Herald's changelog field takes entries only, each starting with `* `. A version header, a date or + * a blank title breaks the page the changelog is shown on, so anything else is refused. + * + * @param {string} input The input value, a path relative to the checkout. + * @param {string} cwd The checkout. + * + * @throws {Error} When the file is missing, has no entry, or has a line that is not an entry. + * + * @returns {string|null} The entries, or null when the input is empty and the changelog is left alone. + */ +function readChangelogFile(input, cwd) { + const trimmed = String(input ?? '').trim() + + if (trimmed === '') { + return null + } + + let text + try { + text = fs.readFileSync(path.resolve(cwd, trimmed), 'utf8') + } catch { + throw new Error(`changelog-file '${trimmed}' is not a file in the checkout. ${NOTHING}`) + } + + const entries = text + .split(/\r?\n/) + .map((line) => line.trim()) + .filter(Boolean) + + if (entries.length === 0) { + throw new Error( + `changelog-file '${trimmed}' has no entry. Leave the input out to keep the changelog Herald has. ${NOTHING}` + ) + } + + const stray = entries.find((line) => !line.startsWith('* ')) + if (stray !== undefined) { + throw new Error( + `changelog-file '${trimmed}' has a line that is not an entry: '${stray}'. Herald takes entries only, ` + + `each starting with '* ', with no version and no date. ${NOTHING}` + ) + } + + return entries.join('\n') +} + +/** + * Reads the `release-date` input. + * + * @param {string} date The input value, as `YYYY-MM-DD`. + * + * @throws {Error} When it is not a calendar date in that form. + * + * @returns {string|null} The date as Herald takes it, or null when the input is empty. + */ +function readReleaseDate(date) { + const trimmed = String(date ?? '').trim() + + if (trimmed === '') { + return null + } + + const iso = `${trimmed}T00:00:00Z` + const parsed = /^\d{4}-\d{2}-\d{2}$/.test(trimmed) ? new Date(iso) : null + + if (parsed === null || Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== trimmed) { + throw new Error(`release-date '${trimmed}' is not a date as YYYY-MM-DD. ${NOTHING}`) + } + + return iso +} + +/** + * Reads the `api-key` input. + * + * @param {string} key The input value. + * + * @throws {Error} When it is empty or holds whitespace, which a pasted secret sometimes does. + * + * @returns {string} The key. + */ +function readApiKey(key) { + const trimmed = String(key ?? '').trim() + + if (trimmed === '') { + throw new Error(`No api-key was given: pass the Herald key of scope ci, from a secret. ${NOTHING}`) + } + + if (/\s/.test(trimmed)) { + throw new Error(`api-key holds whitespace, so it is not the key Herald issued. ${NOTHING}`) + } + + return trimmed +} + +/** + * Sends one request to Herald and reads the answer, without throwing: a request that got no answer + * comes back with status 0, so each caller can say what was already written when it failed. + * + * A redirect is refused rather than followed. It would send the key to another address, and a + * redirected POST loses its body. + * + * @param {object} options + * @param {Function} options.fetch The fetch to use. + * @param {string} options.url The full address. + * @param {string} options.method The HTTP method. + * @param {string} options.apiKey The Herald key. + * @param {object} options.json A value to send as the JSON body. + * @param {FormData} options.form A form to send instead. + * @param {number} options.timeout Milliseconds before the request is given up. + * + * @returns {Promise<{status: number, data: object|null, reason: string}>} The status, the JSON body + * when there is one, and Herald's error message or the network's. + */ +async function send({ fetch, url, method = 'GET', apiKey, json, form, timeout = REQUEST_TIMEOUT_MS }) { + const headers = { authorization: `Bearer ${apiKey}`, accept: 'application/json' } + let body + + if (json !== undefined) { + headers['content-type'] = 'application/json' + body = JSON.stringify(json) + } else if (form !== undefined) { + body = form + } + + let response + try { + response = await fetch(url, { method, headers, body, redirect: 'error', signal: AbortSignal.timeout(timeout) }) + } catch (error) { + return { status: 0, data: null, reason: error.cause?.message ?? error.message } + } + + const text = await response.text() + let data = null + try { + data = text === '' ? null : JSON.parse(text) + } catch { + data = null + } + + return { status: response.status, data, reason: String(data?.error ?? text).slice(0, 300) } +} + +/** + * Says how a request failed, for an error message. + * + * @param {{status: number, reason: string}} answer What `send` returned. + * + * @returns {string} `HTTP 401: invalid API key`, or `no answer: fetch failed`. + */ +function failure(answer) { + return answer.status === 0 ? `no answer: ${answer.reason}` : `HTTP ${answer.status}: ${answer.reason}` +} + +/** + * Uploads the ZIP, or finds the record of a ZIP Herald already holds. + * + * Herald refuses bytes it has already stored and names the record in the refusal. A retry whose + * build came out identical takes that id, so it can go on and update the version. + * + * @param {object} options + * @param {Function} options.fetch The fetch to use. + * @param {string} options.base Herald's address. + * @param {string} options.apiKey The Herald key. + * @param {object} options.zip What `readZip` returned. + * + * @throws {Error} When the upload fails for any reason but a duplicate. + * + * @returns {Promise<{id: string, sha256: string, meta: object|null, reused: boolean}>} The ZIP + * record. `sha256` is empty and `meta` null for a reused record. + */ +async function uploadZip({ fetch, base, apiKey, zip }) { + const form = new FormData() + form.append('file', new Blob([fs.readFileSync(zip.file)], { type: 'application/zip' }), zip.name) + + const answer = await send({ + fetch, + url: `${base}/api/v1/zips/upload`, + method: 'POST', + apiKey, + form, + timeout: UPLOAD_TIMEOUT_MS, + }) + + if (answer.status === 201 && typeof answer.data?.id === 'string') { + return { id: answer.data.id, sha256: String(answer.data.sha256 ?? ''), meta: answer.data.meta ?? null, reused: false } + } + + const duplicate = answer.status === 400 ? DUPLICATE_ZIP.exec(answer.reason) : null + if (duplicate) { + return { id: duplicate[1], sha256: '', meta: null, reused: true } + } + + throw new Error(`Uploading ${zip.name} to Herald failed (${failure(answer)}). ${NOTHING}`) +} + +/** + * Publishes the ZIP as a version of the product. + * + * @param {object} options + * @param {object} options.core The @actions/core toolkit, for the log, the outputs and the summary. + * @param {object} options.env The environment the action manifest put its inputs in. + * @param {Function} options.fetch The fetch to use, the runtime's by default. + * @param {string} options.cwd The checkout, the working directory by default. + * @param {Date} options.now The current time, for the release date of a new version. + * + * @throws {Error} When an input is wrong, the ZIP holds another version, or Herald refuses a call. + * + * @returns {Promise} Resolves once the version points at the ZIP, in the status asked for. + */ +async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = process.cwd(), now = new Date() }) { + const version = validateVersion(env.INPUT_VERSION) + const base = readUrl(env.INPUT_HERALD_URL) + const product = readProduct(env.INPUT_PRODUCT) + const status = readStatus(env.INPUT_STATUS) + const zip = readZip(env.INPUT_ZIP, cwd) + const changelog = readChangelogFile(env.INPUT_CHANGELOG_FILE, cwd) + const releaseDate = readReleaseDate(env.INPUT_RELEASE_DATE) + const apiKey = readApiKey(env.INPUT_API_KEY) + core.setSecret(apiKey) + + const uploaded = await uploadZip({ fetch, base, apiKey, zip }) + const stored = `The ZIP is in Herald as ${uploaded.id}, and no version of ${product} was changed.` + core.info( + uploaded.reused + ? `Herald already holds ${zip.name} as ${uploaded.id}: reusing it.` + : `Uploaded ${zip.name} as ${uploaded.id} (sha256 ${uploaded.sha256}).` + ) + + // Herald reads the plugin header of the ZIP it stores. A ZIP of another version, or of another + // plugin on another version, stops here rather than being published under this one. + const zipVersion = uploaded.meta?.version + if (typeof zipVersion === 'string' && zipVersion.trim() !== '' && zipVersion.trim() !== version) { + throw new Error( + `${zip.name} is version ${zipVersion.trim()} (${uploaded.meta.main_file ?? 'main file unknown'}), ` + + `not ${version}, so it was not published. ${stored}` + ) + } + + const versions = `${base}/api/v1/products/${encodeURIComponent(product)}/versions` + const versionUrl = `${versions}/${encodeURIComponent(version)}` + + const found = await send({ fetch, url: versionUrl, apiKey }) + if (found.status !== 200 && found.status !== 404) { + throw new Error(`Reading ${product} ${version} in Herald failed (${failure(found)}). ${stored}`) + } + + let created = false + if (found.status === 404) { + // A new version starts as a draft whatever is sent, so the status goes in the update below. + const answer = await send({ + fetch, + url: versions, + method: 'POST', + apiKey, + json: { version, zip_id: uploaded.id, release_date: releaseDate ?? `${now.toISOString().slice(0, 10)}T00:00:00Z` }, + }) + + // Two runs for one version: the other created it between the read and this call. + const raced = answer.status === 400 && /already exists/i.test(answer.reason) + if (answer.status !== 201 && !raced) { + throw new Error(`Creating ${product} ${version} in Herald failed (${failure(answer)}). ${stored}`) + } + + created = answer.status === 201 + } + + // One call for the ZIP, the status and the rest: Herald writes them together, so a refused + // update never leaves the version published with the old ZIP. + const answer = await send({ + fetch, + url: versionUrl, + method: 'PATCH', + apiKey, + json: { + zip_id: uploaded.id, + status, + ...(changelog === null ? {} : { changelog }), + ...(releaseDate === null ? {} : { release_date: releaseDate }), + }, + }) + + if (answer.status !== 200) { + const left = created + ? `The version was created as a draft with the ZIP ${uploaded.id}; it is not ${status}.` + : `The version is as it was, and the ZIP ${uploaded.id} is in Herald with no version pointing at it.` + throw new Error(`Updating ${product} ${version} in Herald failed (${failure(answer)}). ${left}`) + } + + const finalStatus = String(answer.data?.status ?? status) + core.info(`${product} ${version} is ${finalStatus} in Herald with the ZIP ${uploaded.id}.`) + core.setOutput('zip-id', uploaded.id) + core.setOutput('sha256', uploaded.sha256) + core.setOutput('status', finalStatus) + core.setOutput('created', created ? 'true' : 'false') + await core.summary + .addRaw( + `Herald: \`${product}\` ${version} is ${finalStatus}, ${created ? 'created' : 'updated'} with the ZIP \`${uploaded.id}\`` + + `${uploaded.sha256 === '' ? '' : ` (sha256 \`${uploaded.sha256}\`)`}.`, + true + ) + .write() +} + +module.exports = { + runHeraldPublish, + validateVersion, + readUrl, + readProduct, + readStatus, + readZip, + readChangelogFile, + readReleaseDate, + readApiKey, + NOTHING, +} diff --git a/README.md b/README.md index eef3fd16..9cf24ccb 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,7 @@ Each phase ends with something people can actually use. - [x] Add `release-merge`: the release branch into the base branch, the base back into develop, each step safe to rerun and a conflict reported with a `MERGE_CONFLICT` line. - [x] Add `release-publish`: the GitHub release for a version at a commit, with a title, notes from a file and assets uploaded before the release is public, skipped when it already exists. The complete deploy workflow to copy, both actions with the build between them, is `templates/workflows/release.yml`. - [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`. - [ ] 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/templates/workflows/release.yml b/templates/workflows/release.yml index 69864acc..0d82c29e 100644 --- a/templates/workflows/release.yml +++ b/templates/workflows/release.yml @@ -83,6 +83,17 @@ jobs: ref: ${{ steps.merge.outputs.base-sha }} persist-credentials: false + # For a product sold through Herald: upload the build and publish the version there before the + # GitHub release, so a failed upload leaves no release behind. As a secret of the environment + # above, the key is read only by a run that environment accepts. + # - uses: stellarwp/plugin-toolbox/.github/actions/herald-publish@v1 + # with: + # herald-url: ${{ vars.HERALD_URL }} + # product: my-plugin + # version: ${{ inputs.version }} + # zip: build/my-plugin.zip + # api-key: ${{ secrets.HERALD_API_KEY }} + - uses: stellarwp/plugin-toolbox/.github/actions/release-publish@v1 id: release with: diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js new file mode 100644 index 00000000..5713f8cc --- /dev/null +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -0,0 +1,385 @@ +'use strict' + +const { describe, it } = require('node:test') +const assert = require('node:assert') +const fs = require('node:fs') +const os = require('node:os') +const path = require('node:path') + +const { + runHeraldPublish, + readUrl, + readProduct, + readStatus, + readZip, + readChangelogFile, + readReleaseDate, + readApiKey, +} = require('../../../.github/actions/herald-publish/herald-publish.js') +const { coreWithOutputs, recordingFetch } = require('../../support/actions.js') + +const BASE = 'https://herald.test' + +/** The Herald addresses the action calls for the product `gift-aid` and the version 2.2.2. */ +const API = { + upload: `${BASE}/api/v1/zips/upload`, + versions: `${BASE}/api/v1/products/gift-aid/versions`, + version: `${BASE}/api/v1/products/gift-aid/versions/2.2.2`, +} + +const ZIP_ID = '11111111-2222-4333-8444-555555555555' +const SHA256 = 'ab'.repeat(32) + +/** The ZIP record Herald answers an upload with: it reads the plugin header of what it stores. */ +const ZIP_RECORD = { + id: ZIP_ID, + sha256: SHA256, + meta: { kind: 'plugin', top_dir: 'give-gift-aid', main_file: 'give-gift-aid/give-gift-aid.php', version: '2.2.2' }, +} + +/** The time the tests run at, for the release date of a new version. */ +const NOW = new Date('2026-11-30T15:00:00Z') + +/** The rules of the common case: a new ZIP, a version the product does not have yet. */ +const FRESH = [ + { method: 'POST', path: API.upload, status: 201, body: ZIP_RECORD }, + { method: 'GET', path: API.version, status: 404, body: { error: "version '2.2.2' not found" } }, + { method: 'POST', path: API.versions, status: 201, body: { version: '2.2.2', status: 'draft', zip_id: ZIP_ID } }, + { method: 'PATCH', path: API.version, body: { version: '2.2.2', status: 'published', zip_id: ZIP_ID } }, +] + +/** + * The environment the manifest hands the script. + * + * @param {object} overrides Inputs to change. + * + * @returns {object} The environment. + */ +function publishEnv(overrides = {}) { + return { + INPUT_HERALD_URL: BASE, + INPUT_PRODUCT: 'gift-aid', + INPUT_VERSION: '2.2.2', + INPUT_ZIP: 'give-gift-aid.zip', + INPUT_STATUS: '', + INPUT_CHANGELOG_FILE: '', + INPUT_RELEASE_DATE: '', + INPUT_API_KEY: 'herald-ci-key', + ...overrides, + } +} + +/** + * A checkout with the build in it, and any other file a test needs. + * + * @param {object} files File contents by path, added to the ZIP. + * + * @returns {string} The directory. + */ +function checkoutWith(files = {}) { + const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'herald-publish-')) + for (const [name, contents] of Object.entries({ 'give-gift-aid.zip': 'PK\u0003\u0004 the build', ...files })) { + fs.mkdirSync(path.dirname(path.join(cwd, name)), { recursive: true }) + fs.writeFileSync(path.join(cwd, name), contents) + } + + return cwd +} + +/** + * A recording fetch that also keeps the headers of each request. + * + * @param {object[]} rules Passed to recordingFetch. + * + * @returns {{fetch: Function, requests: object[], headers: object[]}} The fetch and what it recorded. + */ +function heraldFetch(rules) { + const { fetch, requests } = recordingFetch(rules) + const headers = [] + + return { + fetch: (url, options = {}) => { + headers.push(options.headers) + + return fetch(url, options) + }, + requests, + headers, + } +} + +/** + * Each request as `METHOD path`, for asserting what the action asked Herald. + * + * @param {object[]} requests The requests the fetch recorded. + * + * @returns {string[]} One line per request. + */ +function calls(requests) { + return requests.map((request) => `${request.method} ${request.url.replace(BASE, '')}`) +} + +describe('herald-publish', () => { + describe('reading the inputs', () => { + it('takes an HTTPS address and drops the trailing slash', () => { + assert.strictEqual(readUrl(' https://herald.example.com/ '), 'https://herald.example.com') + }) + + it('refuses an address that would send the key in the clear', () => { + assert.throws(() => readUrl('http://herald.example.com'), /not HTTPS.*Nothing was published to Herald/) + }) + + it('takes plain HTTP for a Herald on the same machine', () => { + assert.strictEqual(readUrl('http://localhost:3000'), 'http://localhost:3000') + }) + + it('refuses an address with credentials or a query', () => { + assert.throws(() => readUrl('https://user:pass@herald.example.com'), /address only/) + assert.throws(() => readUrl('https://herald.example.com/?key=1'), /address only/) + }) + + it('refuses an empty address and one that is not a URL', () => { + assert.throws(() => readUrl(''), /No herald-url was given/) + assert.throws(() => readUrl('herald'), /is not a URL/) + }) + + it('refuses a product that is not a slug', () => { + assert.strictEqual(readProduct(' gift-aid '), 'gift-aid') + assert.throws(() => readProduct(''), /No product was given/) + assert.throws(() => readProduct('gift-aid/versions'), /is not a Herald slug/) + assert.throws(() => readProduct('gift aid'), /is not a Herald slug/) + }) + + it('publishes by default and refuses a status Herald does not have', () => { + assert.strictEqual(readStatus(''), 'published') + assert.strictEqual(readStatus('Review'), 'review') + assert.throws(() => readStatus('live'), /is not one of draft, review, published/) + }) + + it('refuses a zip that is missing, empty or not a .zip', () => { + const cwd = checkoutWith({ 'empty.zip': '', 'build.tar': 'x' }) + + assert.strictEqual(readZip('give-gift-aid.zip', cwd).name, 'give-gift-aid.zip') + assert.throws(() => readZip('', cwd), /No zip was given/) + assert.throws(() => readZip('build.tar', cwd), /is not a \.zip file/) + assert.throws(() => readZip('missing.zip', cwd), /is not a file in the checkout/) + assert.throws(() => readZip('empty.zip', cwd), /is empty/) + }) + + it('reads the changelog entries, one per line', () => { + const cwd = checkoutWith({ 'entries.txt': '* Fix - One thing.\r\n\n* New - Another thing.\n' }) + + assert.strictEqual(readChangelogFile('entries.txt', cwd), '* Fix - One thing.\n* New - Another thing.') + assert.strictEqual(readChangelogFile('', cwd), null) + }) + + it('refuses a changelog with a version header, and one with no entry', () => { + const cwd = checkoutWith({ 'header.txt': '= [2.2.2] 2026-11-25 =\n\n* Fix - One thing.\n', 'blank.txt': '\n\n' }) + + assert.throws(() => readChangelogFile('header.txt', cwd), /a line that is not an entry: '= \[2\.2\.2\] 2026-11-25 ='/) + assert.throws(() => readChangelogFile('blank.txt', cwd), /has no entry/) + assert.throws(() => readChangelogFile('missing.txt', cwd), /is not a file in the checkout/) + }) + + it('reads a release date and refuses one that is not a calendar date', () => { + assert.strictEqual(readReleaseDate('2026-11-25'), '2026-11-25T00:00:00Z') + assert.strictEqual(readReleaseDate(''), null) + assert.throws(() => readReleaseDate('2026-02-30'), /is not a date as YYYY-MM-DD/) + assert.throws(() => readReleaseDate('25/11/2026'), /is not a date as YYYY-MM-DD/) + }) + + it('refuses a missing key and one with whitespace inside', () => { + assert.strictEqual(readApiKey(' herald-ci-key\n'), 'herald-ci-key') + assert.throws(() => readApiKey(''), /No api-key was given/) + assert.throws(() => readApiKey('herald ci key'), /holds whitespace/) + }) + + it('calls nothing when an input is wrong', async (t) => { + const { core } = await coreWithOutputs(t) + const { fetch, requests } = heraldFetch(FRESH) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv({ INPUT_STATUS: 'live' }), fetch, cwd: checkoutWith(), now: NOW }), + /is not one of draft, review, published/ + ) + assert.deepStrictEqual(requests, []) + }) + }) + + describe('a version the product does not have yet', () => { + it('uploads the ZIP, creates the version and publishes it', async (t) => { + const { core, outputs, summary, logged } = await coreWithOutputs(t) + const { fetch, requests, headers } = heraldFetch(FRESH) + + await runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }) + + assert.deepStrictEqual(calls(requests), [ + 'POST /api/v1/zips/upload', + 'GET /api/v1/products/gift-aid/versions/2.2.2', + 'POST /api/v1/products/gift-aid/versions', + 'PATCH /api/v1/products/gift-aid/versions/2.2.2', + ]) + assert.strictEqual(requests[0].body.get('file').name, 'give-gift-aid.zip') + assert.deepStrictEqual(requests[2].body, { version: '2.2.2', zip_id: ZIP_ID, release_date: '2026-11-30T00:00:00Z' }) + assert.deepStrictEqual(requests[3].body, { zip_id: ZIP_ID, status: 'published' }) + assert.ok(headers.every((sent) => sent.authorization === 'Bearer herald-ci-key')) + assert.deepStrictEqual(outputs(), { 'zip-id': ZIP_ID, sha256: SHA256, status: 'published', created: 'true' }) + assert.match(summary(), /`gift-aid` 2\.2\.2 is published, created with the ZIP/) + assert.match(logged(), /Uploaded give-gift-aid\.zip as 11111111/) + }) + + it('sends the changelog and the release date it was given', async (t) => { + const { core } = await coreWithOutputs(t) + const { fetch, requests } = heraldFetch(FRESH) + const cwd = checkoutWith({ 'entries.txt': '* Fix - One thing.\n' }) + + await runHeraldPublish({ + core, + env: publishEnv({ INPUT_CHANGELOG_FILE: 'entries.txt', INPUT_RELEASE_DATE: '2026-11-25', INPUT_STATUS: 'review' }), + fetch, + cwd, + now: NOW, + }) + + assert.strictEqual(requests[2].body.release_date, '2026-11-25T00:00:00Z') + assert.deepStrictEqual(requests[3].body, { + zip_id: ZIP_ID, + status: 'review', + changelog: '* Fix - One thing.', + release_date: '2026-11-25T00:00:00Z', + }) + }) + + it('goes on to the update when another run created the version first', async (t) => { + const { core, outputs } = await coreWithOutputs(t) + const { fetch, requests } = heraldFetch([ + FRESH[0], + FRESH[1], + { method: 'POST', path: API.versions, status: 400, body: { error: 'this version already exists for the product' } }, + FRESH[3], + ]) + + await runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }) + + assert.strictEqual(calls(requests).at(-1), 'PATCH /api/v1/products/gift-aid/versions/2.2.2') + assert.strictEqual(outputs().created, 'false') + }) + }) + + describe('a version the product already has', () => { + it('updates it without creating another, and leaves its release date alone', async (t) => { + const { core, outputs, summary } = await coreWithOutputs(t) + const { fetch, requests } = heraldFetch([ + FRESH[0], + { method: 'GET', path: API.version, body: { version: '2.2.2', status: 'published', zip_id: 'older-zip' } }, + FRESH[3], + ]) + + await runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }) + + assert.deepStrictEqual(calls(requests), [ + 'POST /api/v1/zips/upload', + 'GET /api/v1/products/gift-aid/versions/2.2.2', + 'PATCH /api/v1/products/gift-aid/versions/2.2.2', + ]) + assert.deepStrictEqual(requests[2].body, { zip_id: ZIP_ID, status: 'published' }) + assert.strictEqual(outputs().created, 'false') + assert.match(summary(), /is published, updated with the ZIP/) + }) + + it('reuses a ZIP Herald already holds', async (t) => { + const { core, outputs, logged } = await coreWithOutputs(t) + const { fetch, requests } = heraldFetch([ + { method: 'POST', path: API.upload, status: 400, body: { error: `a ZIP with this content already exists (id: ${ZIP_ID})` } }, + { method: 'GET', path: API.version, body: { version: '2.2.2', status: 'draft', zip_id: ZIP_ID } }, + FRESH[3], + ]) + + await runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }) + + assert.deepStrictEqual(requests[2].body, { zip_id: ZIP_ID, status: 'published' }) + assert.deepStrictEqual(outputs(), { 'zip-id': ZIP_ID, sha256: '', status: 'published', created: 'false' }) + assert.match(logged(), /already holds give-gift-aid\.zip as 11111111.*reusing it/) + }) + }) + + describe('what stops it', () => { + it('refuses a ZIP whose plugin header holds another version', async (t) => { + const { core, outputs } = await coreWithOutputs(t) + const recurring = { ...ZIP_RECORD, meta: { ...ZIP_RECORD.meta, main_file: 'give-recurring/give-recurring.php', version: '2.20.5' } } + const { fetch, requests } = heraldFetch([{ method: 'POST', path: API.upload, status: 201, body: recurring }, ...FRESH.slice(1)]) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + /is version 2\.20\.5 \(give-recurring\/give-recurring\.php\), not 2\.2\.2.*no version of gift-aid was changed/s + ) + assert.deepStrictEqual(calls(requests), ['POST /api/v1/zips/upload']) + assert.deepStrictEqual(outputs(), {}) + }) + + it('stops at an upload Herald refuses', async (t) => { + const { core } = await coreWithOutputs(t) + const { fetch, requests } = heraldFetch([{ method: 'POST', path: API.upload, status: 401, body: { error: 'invalid API key' } }]) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + /Uploading give-gift-aid\.zip to Herald failed \(HTTP 401: invalid API key\)\. Nothing was published to Herald/ + ) + assert.deepStrictEqual(calls(requests), ['POST /api/v1/zips/upload']) + }) + + it('says so when Herald does not answer', async (t) => { + const { core } = await coreWithOutputs(t) + const fetch = async () => { + throw new TypeError('fetch failed', { cause: new Error('getaddrinfo ENOTFOUND herald.test') }) + } + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + /failed \(no answer: getaddrinfo ENOTFOUND herald\.test\)/ + ) + }) + + it('names the product when Herald does not have it', async (t) => { + const { core } = await coreWithOutputs(t) + const { fetch } = heraldFetch([ + FRESH[0], + FRESH[1], + { method: 'POST', path: API.versions, status: 404, body: { error: "product 'gift-aid' not found" } }, + ]) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + /Creating gift-aid 2\.2\.2 in Herald failed \(HTTP 404: product 'gift-aid' not found\)\. The ZIP is in Herald as 11111111/ + ) + }) + + it('says a new version stayed a draft when the update is refused', async (t) => { + const { core, outputs } = await coreWithOutputs(t) + const { fetch } = heraldFetch([ + ...FRESH.slice(0, 3), + { method: 'PATCH', path: API.version, status: 500, body: { error: 'database error' } }, + ]) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + /Updating gift-aid 2\.2\.2 in Herald failed \(HTTP 500: database error\)\. The version was created as a draft.*it is not published/ + ) + assert.deepStrictEqual(outputs(), {}) + }) + + it('says an existing version is as it was when the update is refused', async (t) => { + const { core } = await coreWithOutputs(t) + const { fetch } = heraldFetch([ + FRESH[0], + { method: 'GET', path: API.version, body: { version: '2.2.2', status: 'published', zip_id: 'older-zip' } }, + { method: 'PATCH', path: API.version, status: 403, body: { error: 'forbidden' } }, + ]) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + /failed \(HTTP 403: forbidden\)\. The version is as it was/ + ) + }) + }) +}) From ea4660ce8f373423018b154ff0e61fa5370eb1d5 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Mon, 30 Nov 2026 17:23:43 -0300 Subject: [PATCH 02/45] herald-publish README: get the changelog file from the changelogger The changelog-file input takes the entries of one version, and the README did not say where a caller gets them. The changelogger prints them without the header: get-changelog-contents --version=. With a space instead of the equals sign it prints its own version. SOFT-5788 --- .github/actions/herald-publish/README.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index 64400f35..f4523255 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -81,6 +81,25 @@ The changelog file holds entries only, with no version and no date: Herald shows the field as it is, and a header in it breaks the page the changelog appears on. The action refuses a file with a line that is not an entry. +A repository that writes its changelog with the +[changelogger](https://github.com/stellarwp/changelogger) gets the file from it. The command prints +the entries of one version, without the header, in the form above: + +```yaml +- name: Write the changelog entries of this version to a file + env: + VERSION: ${{ inputs.version }} + run: npx @stellarwp/changelogger get-changelog-contents --version="$VERSION" > herald-changelog.txt + +- uses: stellarwp/plugin-toolbox/.github/actions/herald-publish@v1 + with: + # ... + changelog-file: herald-changelog.txt +``` + +Write the version with `=`. With a space (`--version 4.17.0`), the command prints the changelogger's +own version instead of the entries. + ## Outputs | Output | What it is | From 92410cea8a83e51c9b325d8419ed834fe96e74bc Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Mon, 30 Nov 2026 17:52:05 -0300 Subject: [PATCH 03/45] herald-publish: keep what Herald reads from the ZIP, and confirm what it wrote Herald fills the changelog and the release date of a new version from the entry of that version in the ZIP's readme.txt. The action sent today's date with the create, which replaced the readme's date, and left the changelog with the header line Herald writes above the entries ("= 4.17.0 | 2026-11-25 ="), which the changelog field must not hold. The create now sends the version and the ZIP only. The update takes the header out of the changelog and gives today's date to a version Herald found none for. The release-date input is gone: nothing used it. A create or an update that got no answer, or a server error, may have been applied all the same. Its error no longer says that nothing changed. An answer whose body cannot be read counts as no answer. A 200 on the update is no longer taken as the proof: the answer has to show the status and the ZIP that were asked for. The example in the README and in the template skips the step when the GitHub release of the version already exists, so the rerun of a published version does not replace a ZIP customers are downloading. SOFT-5788 --- .github/actions/herald-publish/README.md | 89 ++++---- .github/actions/herald-publish/action.yml | 24 +- .../actions/herald-publish/herald-publish.js | 134 +++++++---- templates/workflows/release.yml | 4 +- .../herald-publish/herald-publish.test.js | 209 ++++++++++++++---- 5 files changed, 322 insertions(+), 138 deletions(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index f4523255..bdd07157 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -1,13 +1,13 @@ # herald-publish Publishes a plugin ZIP to [Herald](https://github.com/stellarwp/herald), the service customers -download paid plugins from. It uploads the ZIP, creates the version when the product does not have -it yet, then points the version at the ZIP and sets its status, release date and changelog. +download paid plugins from. It uploads the ZIP and creates the version when the product does not +have it yet. It then points the version at the ZIP and sets its status. -It is what a person does by hand in the Herald dashboard for a paid release: New Version, Upload -new, the release date and the changelog, Create, then Publish. In a deploy it runs after the build -and before [release-publish](../release-publish/README.md), so a failed upload leaves no GitHub -release behind: +It is what a person does by hand in the Herald dashboard for a paid release. They click New Version, +upload the ZIP, check the changelog and the release date, create the version and publish it. In a +deploy the action runs after the build and before +[release-publish](../release-publish/README.md), so a failed upload leaves no GitHub release behind: ```yaml - uses: stellarwp/plugin-toolbox/.github/actions/release-merge@v1 @@ -23,6 +23,7 @@ release behind: # Build the plugin here, from the merged commit. - uses: stellarwp/plugin-toolbox/.github/actions/herald-publish@v1 + if: steps.merge.outputs.already-published == 'no' with: herald-url: ${{ vars.HERALD_URL }} product: my-plugin @@ -43,8 +44,7 @@ product has to exist: the action creates versions, never products. ## What it does -1. Checks every input before any call: the address, the slug, the version, the status, the ZIP and - the changelog file. +1. Checks every input before any call. 2. Uploads the ZIP (`POST /api/v1/zips/upload`). Herald stores it, computes its SHA-256 and reads the plugin header inside. 3. Compares the version Herald read from the ZIP with `version`, and stops when they differ. A ZIP of @@ -52,54 +52,60 @@ product has to exist: the action creates versions, never products. 4. Reads the version of the product (`GET /api/v1/products/{product}/versions/{version}`) and creates it when it is missing (`POST /api/v1/products/{product}/versions`). A new version is a draft. -5. Updates the version in one call (`PATCH` on the same address): the ZIP, the status, and the - changelog and the release date when they were given. Herald writes them together, so a refused +5. Updates the version in one call (`PATCH` on the same address): the ZIP, the status and, when they + need a change, the changelog and the release date. Herald writes them together, so a refused update never leaves the version published with the old ZIP. +6. Checks that Herald's answer shows the status and the ZIP it asked for, and fails when it does + not. The run log and the job summary show the ZIP id and its SHA-256. -## Inputs +## The changelog and the release date -| Input | Required | Default | What it is | -|---|---|---|---| -| `herald-url` | yes | | The address of the Herald instance. HTTPS only. | -| `product` | yes | | The slug of the product in Herald. | -| `version` | yes | | The version being released: three or four numeric parts. | -| `zip` | yes | | The build to upload, a `.zip` path relative to the checkout. | -| `status` | no | `published` | `draft`, `review` or `published`. Only a published version is served to customers. | -| `changelog-file` | no | | A file with the entries of this version, one per line, each starting with `* `. Empty keeps the changelog Herald has. | -| `release-date` | no | | `YYYY-MM-DD`. Empty gives a new version today's date in UTC and leaves an existing version's date alone. | -| `api-key` | yes | | A Herald API key of scope `ci`, from a secret. | +Herald fills both for a new version, from the entry of that version in the `readme.txt` inside the +ZIP. The action sends neither when it creates the version, and then makes two corrections: + +- **The changelog.** Herald writes the entry with a header line above it, such as + `= 4.17.0 | 2026-11-25 =`. The changelog field takes entries only, and a header in it can break the + page the changelog appears on. The action takes the header line out and keeps the entries. +- **The release date.** A version Herald found no date for gets today's date in UTC. + +A version that already has entries only, or already has a date, is left as it is. -The changelog file holds entries only, with no version and no date: +To send another changelog, pass `changelog-file`: a file with the entries of this version, one per +line, with no version and no date. The action refuses a file with a line that is not an entry. ```text * Fix - Resolved an error when the fee is disabled for the gateway. * New - Added a setting for the maximum fee. ``` -Herald shows the field as it is, and a header in it breaks the page the changelog appears on. The -action refuses a file with a line that is not an entry. - A repository that writes its changelog with the -[changelogger](https://github.com/stellarwp/changelogger) gets the file from it. The command prints -the entries of one version, without the header, in the form above: +[changelogger](https://github.com/stellarwp/changelogger) can get that file from it. The command +prints the entries of one version, without the header: ```yaml - name: Write the changelog entries of this version to a file env: VERSION: ${{ inputs.version }} run: npx @stellarwp/changelogger get-changelog-contents --version="$VERSION" > herald-changelog.txt - -- uses: stellarwp/plugin-toolbox/.github/actions/herald-publish@v1 - with: - # ... - changelog-file: herald-changelog.txt ``` Write the version with `=`. With a space (`--version 4.17.0`), the command prints the changelogger's own version instead of the entries. +## Inputs + +| Input | Required | Default | What it is | +|---|---|---|---| +| `herald-url` | yes | | The address of the Herald instance. HTTPS, or plain HTTP for `localhost`. | +| `product` | yes | | The slug of the product in Herald. | +| `version` | yes | | The version being released: three or four numeric parts. | +| `zip` | yes | | The build to upload, a `.zip` path relative to the checkout. | +| `status` | no | `published` | `draft`, `review` or `published`. Only a published version is served to customers. | +| `changelog-file` | no | | A file with the entries of this version. Empty keeps what Herald read from the ZIP, without the header. | +| `api-key` | yes | | A Herald API key of scope `ci`, from a secret. | + ## Outputs | Output | What it is | @@ -121,8 +127,15 @@ A run can be repeated after a late failure, for the same version: - **Another run created the version in between.** The create is refused as a duplicate, and the action goes on to the update. -When a step fails, the error says what Herald holds at that point: nothing, the ZIP with no version -pointing at it, or a new version left as a draft. +When a step fails, the error says what Herald holds at that point. That is nothing, the ZIP with no +version pointing at it, or a new version left as a draft. When Herald did not answer a write, or +answered with a server error, the error says that what Herald holds is not known. + +Skip the step for a version whose GitHub release already exists, as the example at the top does with +release-merge's +[`already-published`](../release-merge/README.md#outputs) output. The rerun of a published version +builds the ZIP again, and without the condition it would replace a ZIP customers are already +downloading. ## The key, and who can publish @@ -132,9 +145,9 @@ Herald's `docs/github-actions.md` says how to create one. With `status: published`, the version is live in Herald when the step ends, with no second click there. So whoever can start the deploy can publish. On GitHub, starting a workflow by hand -[needs write access to the repository](https://docs.github.com/en/actions/how-tos/manage-workflow-runs/manually-run-a-workflow): -keep that access to the people who release and to the app that dispatches for the release -dashboard, where the review and the QA approval come before the deploy. +[needs write access to the repository](https://docs.github.com/en/actions/how-tos/manage-workflow-runs/manually-run-a-workflow). +Keep that access to the people who release and to the app that dispatches for the release dashboard. +The review and the QA approval happen there, before the deploy. How much more to add is each repository's choice: @@ -147,7 +160,7 @@ How much more to add is each repository's choice: - **The Portal's catalogue.** `software.liquidweb.com` copies the latest published version from Herald once a day - ([`SyncService.php`](https://github.com/stellarwp/software.liquidweb.com/blob/develop/content/themes/commerce-portal-theme/src/SLW/CommercePortal/CatalogFeature/SyncService.php)). + ([`SyncService.php`](https://github.com/stellarwp/software.liquidweb.com/blob/82dd6de40ec9253afef2cf227ba250f7d961829f/content/themes/commerce-portal-theme/src/SLW/CommercePortal/CatalogFeature/SyncService.php#L18-L53)). To show a release there at once, an administrator clicks **Sync All From Herald** and then **Flush Catalog Cache** under Products → Catalog Features. - **Customers on legacy licenses.** They do not get updates through Herald. The release to the diff --git a/.github/actions/herald-publish/action.yml b/.github/actions/herald-publish/action.yml index 32087e42..fb5929e5 100644 --- a/.github/actions/herald-publish/action.yml +++ b/.github/actions/herald-publish/action.yml @@ -1,7 +1,7 @@ -# Publishes a plugin ZIP to Herald, the service customers download paid plugins from: uploads the ZIP, -# creates the version when the product does not have it yet, then points the version at the ZIP and -# sets its status, release date and changelog. What a person does by hand in the Herald dashboard -# for a paid release, as one step of the deploy. +# Publishes a plugin ZIP to Herald, the service customers download paid plugins from. It uploads the +# ZIP and creates the version when the product does not have it yet. It then points the version at +# the ZIP and sets its status. What a person does by hand in the Herald dashboard for a paid +# release, as one step of the deploy. # # The logic lives in herald-publish.js, run by actions/github-script, so there is no dependency to # install and nothing to build. The calls go to Herald's API, not GitHub's; the checkout is only @@ -12,8 +12,8 @@ description: Uploads a plugin ZIP to Herald and publishes it as a version of a p inputs: herald-url: description: >- - The address of the Herald instance, e.g. `https://herald.example.com`. HTTPS only: the API key - goes in every request. + The address of the Herald instance, e.g. `https://herald.example.com`. HTTPS, since the API key + goes in every request; plain HTTP is accepted for `localhost` only. required: true product: description: 'The slug of the product in Herald, as its Products page shows it.' @@ -36,14 +36,9 @@ inputs: changelog-file: description: >- A file in the checkout with the changelog entries of this version, one per line, each starting - with `* `. No version and no date: Herald shows the field as it is. When empty, the changelog - Herald has for the version is kept. - required: false - default: '' - release-date: - description: >- - The release date, as `YYYY-MM-DD`. When empty, a new version gets today's date in UTC and an - existing version keeps its own. + with `* `. No version and no date: Herald shows the field as it is. When empty, the version + keeps the entries Herald read from the readme.txt in the ZIP, without the header line Herald + writes above them. required: false default: '' api-key: @@ -84,7 +79,6 @@ runs: INPUT_ZIP: ${{ inputs.zip }} INPUT_STATUS: ${{ inputs.status }} INPUT_CHANGELOG_FILE: ${{ inputs.changelog-file }} - INPUT_RELEASE_DATE: ${{ inputs.release-date }} INPUT_API_KEY: ${{ inputs.api-key }} with: script: | diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index c9814bc5..075c9b7f 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -1,13 +1,17 @@ 'use strict' /** - * Publishes a plugin ZIP to Herald, the service customers download paid plugins from: uploads the - * ZIP, creates the version when the product does not have it yet, then points the version at the - * ZIP and sets its status, release date and changelog. + * Publishes a plugin ZIP to Herald, the service customers download paid plugins from. It uploads + * the ZIP and creates the version when the product does not have it yet. It then points the version + * at the ZIP and sets its status. * * It is what a person does by hand in the Herald dashboard for a paid release: New Version, Upload - * new, the release date and the changelog, Create, then Publish. A deploy workflow runs it after the - * build and before release-publish, so a failed upload leaves no GitHub release behind. + * new, check the changelog and the release date, Create, then Publish. A deploy workflow runs it + * after the build and before release-publish, so a failed upload leaves no GitHub release behind. + * + * Herald fills the changelog and the release date of a new version from the entry of that version + * in the ZIP's readme.txt. The action keeps both, takes the version header out of the changelog, + * and gives today's date to a version Herald found none for. * * Running it again for the same version is safe: the version is updated, never created twice, and a * ZIP Herald already holds is reused. @@ -224,29 +228,28 @@ function readChangelogFile(input, cwd) { } /** - * Reads the `release-date` input. + * Takes the version headers out of a changelog Herald filled from the ZIP's readme.txt. * - * @param {string} date The input value, as `YYYY-MM-DD`. + * Herald writes the entry it found as `= 4.17.0 | 2026-11-25 =` followed by the entries. The + * changelog field takes entries only, so the header line goes and the entries stay as they are. * - * @throws {Error} When it is not a calendar date in that form. + * @param {*} changelog The changelog of the version, as Herald answered it. * - * @returns {string|null} The date as Herald takes it, or null when the input is empty. + * @returns {string|null} The changelog without header lines, or null when there is nothing to + * change: no changelog, no header in it, or nothing but headers. */ -function readReleaseDate(date) { - const trimmed = String(date ?? '').trim() - - if (trimmed === '') { +function entriesOnly(changelog) { + if (typeof changelog !== 'string' || changelog.trim() === '') { return null } - const iso = `${trimmed}T00:00:00Z` - const parsed = /^\d{4}-\d{2}-\d{2}$/.test(trimmed) ? new Date(iso) : null - - if (parsed === null || Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== trimmed) { - throw new Error(`release-date '${trimmed}' is not a date as YYYY-MM-DD. ${NOTHING}`) - } + const kept = changelog + .split(/\r?\n/) + .filter((line) => !/^=.*=$/.test(line.trim())) + .join('\n') + .trim() - return iso + return kept === '' || kept === changelog.trim() ? null : kept } /** @@ -273,8 +276,9 @@ function readApiKey(key) { } /** - * Sends one request to Herald and reads the answer, without throwing: a request that got no answer - * comes back with status 0, so each caller can say what was already written when it failed. + * Sends one request to Herald and reads the answer, without throwing. A request that got no answer, + * or whose answer could not be read, comes back with status 0, so each caller can say what was + * already written when it failed. * * A redirect is refused rather than followed. It would send the key to another address, and a * redirected POST loses its body. @@ -309,7 +313,13 @@ async function send({ fetch, url, method = 'GET', apiKey, json, form, timeout = return { status: 0, data: null, reason: error.cause?.message ?? error.message } } - const text = await response.text() + let text + try { + text = await response.text() + } catch (error) { + return { status: 0, data: null, reason: error.cause?.message ?? error.message } + } + let data = null try { data = text === '' ? null : JSON.parse(text) @@ -331,6 +341,18 @@ function failure(answer) { return answer.status === 0 ? `no answer: ${answer.reason}` : `HTTP ${answer.status}: ${answer.reason}` } +/** + * Whether a failed write may have been applied all the same: Herald did not answer, or answered + * with a server error. A refusal (4xx) wrote nothing. + * + * @param {{status: number}} answer What `send` returned. + * + * @returns {boolean} True when what Herald holds is not known. + */ +function unconfirmed(answer) { + return answer.status === 0 || answer.status >= 500 +} + /** * Uploads the ZIP, or finds the record of a ZIP Herald already holds. * @@ -381,11 +403,13 @@ async function uploadZip({ fetch, base, apiKey, zip }) { * @param {object} options.env The environment the action manifest put its inputs in. * @param {Function} options.fetch The fetch to use, the runtime's by default. * @param {string} options.cwd The checkout, the working directory by default. - * @param {Date} options.now The current time, for the release date of a new version. + * @param {Date} options.now The current time, for the release date of a version with none. * - * @throws {Error} When an input is wrong, the ZIP holds another version, or Herald refuses a call. + * @throws {Error} When an input is wrong, the ZIP holds another version, Herald refuses a call, or + * its answer to the update shows another status or another ZIP. * - * @returns {Promise} Resolves once the version points at the ZIP, in the status asked for. + * @returns {Promise} Resolves once Herald confirms the version points at the ZIP, in the + * status asked for. */ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = process.cwd(), now = new Date() }) { const version = validateVersion(env.INPUT_VERSION) @@ -394,7 +418,6 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro const status = readStatus(env.INPUT_STATUS) const zip = readZip(env.INPUT_ZIP, cwd) const changelog = readChangelogFile(env.INPUT_CHANGELOG_FILE, cwd) - const releaseDate = readReleaseDate(env.INPUT_RELEASE_DATE) const apiKey = readApiKey(env.INPUT_API_KEY) core.setSecret(apiKey) @@ -424,26 +447,33 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro throw new Error(`Reading ${product} ${version} in Herald failed (${failure(found)}). ${stored}`) } + // What Herald holds for the version: read above, or answered by the create below. Null when + // another run created it in between, and nothing is known about it. + let current = found.status === 200 ? found.data : null let created = false if (found.status === 404) { - // A new version starts as a draft whatever is sent, so the status goes in the update below. - const answer = await send({ - fetch, - url: versions, - method: 'POST', - apiKey, - json: { version, zip_id: uploaded.id, release_date: releaseDate ?? `${now.toISOString().slice(0, 10)}T00:00:00Z` }, - }) + // Only the version and the ZIP: Herald fills the changelog and the release date from the entry + // of this version in the ZIP's readme.txt, and a date sent here would replace the readme's. + const answer = await send({ fetch, url: versions, method: 'POST', apiKey, json: { version, zip_id: uploaded.id } }) // Two runs for one version: the other created it between the read and this call. const raced = answer.status === 400 && /already exists/i.test(answer.reason) if (answer.status !== 201 && !raced) { - throw new Error(`Creating ${product} ${version} in Herald failed (${failure(answer)}). ${stored}`) + const left = unconfirmed(answer) + ? `Herald may have created the version all the same: run it again, and a version found there is updated. The ZIP is in Herald as ${uploaded.id}.` + : stored + throw new Error(`Creating ${product} ${version} in Herald failed (${failure(answer)}). ${left}`) } created = answer.status === 201 + current = created ? answer.data : null } + // The changelog field takes entries only. Without a file, the header Herald wrote above the + // entries it read from the ZIP goes; a changelog that holds entries only is left alone. + const entries = changelog ?? entriesOnly(current?.changelog) + const undated = current !== null && !current?.release_date + // One call for the ZIP, the status and the rest: Herald writes them together, so a refused // update never leaves the version published with the old ZIP. const answer = await send({ @@ -454,27 +484,38 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro json: { zip_id: uploaded.id, status, - ...(changelog === null ? {} : { changelog }), - ...(releaseDate === null ? {} : { release_date: releaseDate }), + ...(entries === null ? {} : { changelog: entries }), + ...(undated ? { release_date: `${now.toISOString().slice(0, 10)}T00:00:00Z` } : {}), }, }) if (answer.status !== 200) { - const left = created - ? `The version was created as a draft with the ZIP ${uploaded.id}; it is not ${status}.` - : `The version is as it was, and the ZIP ${uploaded.id} is in Herald with no version pointing at it.` + let left = `The version is as it was, and the ZIP ${uploaded.id} is in Herald with no version pointing at it.` + if (unconfirmed(answer)) { + left = `Herald did not confirm the update, so the version may or may not be ${status} with the ZIP ${uploaded.id}. Run it again: the version is updated, not created twice.` + } else if (created) { + left = `The version was created as a draft with the ZIP ${uploaded.id}; it is not ${status}.` + } + throw new Error(`Updating ${product} ${version} in Herald failed (${failure(answer)}). ${left}`) } - const finalStatus = String(answer.data?.status ?? status) - core.info(`${product} ${version} is ${finalStatus} in Herald with the ZIP ${uploaded.id}.`) + // A 200 is not the proof: the answer has to show the status and the ZIP that were asked for. + if (answer.data?.status !== status || answer.data?.zip_id !== uploaded.id) { + throw new Error( + `Herald answered the update of ${product} ${version} with status '${answer.data?.status}' and the ZIP ` + + `${answer.data?.zip_id}, not '${status}' and ${uploaded.id}. Check the version in Herald before running it again.` + ) + } + + core.info(`${product} ${version} is ${status} in Herald with the ZIP ${uploaded.id}.`) core.setOutput('zip-id', uploaded.id) core.setOutput('sha256', uploaded.sha256) - core.setOutput('status', finalStatus) + core.setOutput('status', status) core.setOutput('created', created ? 'true' : 'false') await core.summary .addRaw( - `Herald: \`${product}\` ${version} is ${finalStatus}, ${created ? 'created' : 'updated'} with the ZIP \`${uploaded.id}\`` + + `Herald: \`${product}\` ${version} is ${status}, ${created ? 'created' : 'updated'} with the ZIP \`${uploaded.id}\`` + `${uploaded.sha256 === '' ? '' : ` (sha256 \`${uploaded.sha256}\`)`}.`, true ) @@ -489,7 +530,6 @@ module.exports = { readStatus, readZip, readChangelogFile, - readReleaseDate, + entriesOnly, readApiKey, - NOTHING, } diff --git a/templates/workflows/release.yml b/templates/workflows/release.yml index 0d82c29e..ba625493 100644 --- a/templates/workflows/release.yml +++ b/templates/workflows/release.yml @@ -85,8 +85,10 @@ jobs: # For a product sold through Herald: upload the build and publish the version there before the # GitHub release, so a failed upload leaves no release behind. As a secret of the environment - # above, the key is read only by a run that environment accepts. + # above, the key is read only by a run that environment accepts. The condition skips the rerun + # of a version already published, which would replace a ZIP customers are downloading. # - uses: stellarwp/plugin-toolbox/.github/actions/herald-publish@v1 + # if: steps.merge.outputs.already-published == 'no' # with: # herald-url: ${{ vars.HERALD_URL }} # product: my-plugin diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index 5713f8cc..fde8be88 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -13,7 +13,7 @@ const { readStatus, readZip, readChangelogFile, - readReleaseDate, + entriesOnly, readApiKey, } = require('../../../.github/actions/herald-publish/herald-publish.js') const { coreWithOutputs, recordingFetch } = require('../../support/actions.js') @@ -37,14 +37,26 @@ const ZIP_RECORD = { meta: { kind: 'plugin', top_dir: 'give-gift-aid', main_file: 'give-gift-aid/give-gift-aid.php', version: '2.2.2' }, } -/** The time the tests run at, for the release date of a new version. */ +/** + * The version Herald answers a create with. It fills the changelog and the release date from the + * entry of that version in the ZIP's readme.txt, and the changelog comes with a header line. + */ +const CREATED = { + version: '2.2.2', + status: 'draft', + zip_id: ZIP_ID, + changelog: '= 2.2.2 | 2026-11-25 =\n* Fix - One thing.\n* New - Another thing.', + release_date: '2026-11-25T00:00:00Z', +} + +/** The time the tests run at, for the release date of a version Herald found no date for. */ const NOW = new Date('2026-11-30T15:00:00Z') /** The rules of the common case: a new ZIP, a version the product does not have yet. */ const FRESH = [ { method: 'POST', path: API.upload, status: 201, body: ZIP_RECORD }, { method: 'GET', path: API.version, status: 404, body: { error: "version '2.2.2' not found" } }, - { method: 'POST', path: API.versions, status: 201, body: { version: '2.2.2', status: 'draft', zip_id: ZIP_ID } }, + { method: 'POST', path: API.versions, status: 201, body: CREATED }, { method: 'PATCH', path: API.version, body: { version: '2.2.2', status: 'published', zip_id: ZIP_ID } }, ] @@ -63,7 +75,6 @@ function publishEnv(overrides = {}) { INPUT_ZIP: 'give-gift-aid.zip', INPUT_STATUS: '', INPUT_CHANGELOG_FILE: '', - INPUT_RELEASE_DATE: '', INPUT_API_KEY: 'herald-ci-key', ...overrides, } @@ -87,27 +98,38 @@ function checkoutWith(files = {}) { } /** - * A recording fetch that also keeps the headers of each request. + * A recording fetch that also keeps the options of each request. * * @param {object[]} rules Passed to recordingFetch. * - * @returns {{fetch: Function, requests: object[], headers: object[]}} The fetch and what it recorded. + * @returns {{fetch: Function, requests: object[], sent: object[]}} The fetch and what it recorded. */ function heraldFetch(rules) { const { fetch, requests } = recordingFetch(rules) - const headers = [] + const sent = [] return { fetch: (url, options = {}) => { - headers.push(options.headers) + sent.push(options) return fetch(url, options) }, requests, - headers, + sent, } } +/** + * The rules of a version Herald answers the create with, and the update that publishes it. + * + * @param {object} created Fields to change in what the create answers. + * + * @returns {object[]} The rules. + */ +function freshWith(created) { + return [FRESH[0], FRESH[1], { method: 'POST', path: API.versions, status: 201, body: { ...CREATED, ...created } }, FRESH[3]] +} + /** * Each request as `METHOD path`, for asserting what the action asked Herald. * @@ -181,11 +203,16 @@ describe('herald-publish', () => { assert.throws(() => readChangelogFile('missing.txt', cwd), /is not a file in the checkout/) }) - it('reads a release date and refuses one that is not a calendar date', () => { - assert.strictEqual(readReleaseDate('2026-11-25'), '2026-11-25T00:00:00Z') - assert.strictEqual(readReleaseDate(''), null) - assert.throws(() => readReleaseDate('2026-02-30'), /is not a date as YYYY-MM-DD/) - assert.throws(() => readReleaseDate('25/11/2026'), /is not a date as YYYY-MM-DD/) + it('takes the version header out of a changelog and keeps the entries', () => { + assert.strictEqual(entriesOnly('= 2.2.2 | 2026-11-25 =\r\n* Fix - One thing.\r\n* New - Another thing.'), '* Fix - One thing.\n* New - Another thing.') + assert.strictEqual(entriesOnly('= 2.2.2 =\n\n* Fix - One thing.'), '* Fix - One thing.') + }) + + it('has nothing to change in a changelog with no header, with headers only, or with no text', () => { + assert.strictEqual(entriesOnly('* Fix - One thing.'), null) + assert.strictEqual(entriesOnly('= 2.2.2 | 2026-11-25 ='), null) + assert.strictEqual(entriesOnly(''), null) + assert.strictEqual(entriesOnly(undefined), null) }) it('refuses a missing key and one with whitespace inside', () => { @@ -209,7 +236,7 @@ describe('herald-publish', () => { describe('a version the product does not have yet', () => { it('uploads the ZIP, creates the version and publishes it', async (t) => { const { core, outputs, summary, logged } = await coreWithOutputs(t) - const { fetch, requests, headers } = heraldFetch(FRESH) + const { fetch, requests, sent } = heraldFetch(FRESH) await runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }) @@ -220,34 +247,55 @@ describe('herald-publish', () => { 'PATCH /api/v1/products/gift-aid/versions/2.2.2', ]) assert.strictEqual(requests[0].body.get('file').name, 'give-gift-aid.zip') - assert.deepStrictEqual(requests[2].body, { version: '2.2.2', zip_id: ZIP_ID, release_date: '2026-11-30T00:00:00Z' }) - assert.deepStrictEqual(requests[3].body, { zip_id: ZIP_ID, status: 'published' }) - assert.ok(headers.every((sent) => sent.authorization === 'Bearer herald-ci-key')) + assert.deepStrictEqual(requests[2].body, { version: '2.2.2', zip_id: ZIP_ID }) + assert.deepStrictEqual(requests[3].body, { + zip_id: ZIP_ID, + status: 'published', + changelog: '* Fix - One thing.\n* New - Another thing.', + }) + assert.ok(sent.every((options) => options.headers.authorization === 'Bearer herald-ci-key')) + assert.ok(sent.every((options) => options.redirect === 'error')) assert.deepStrictEqual(outputs(), { 'zip-id': ZIP_ID, sha256: SHA256, status: 'published', created: 'true' }) assert.match(summary(), /`gift-aid` 2\.2\.2 is published, created with the ZIP/) assert.match(logged(), /Uploaded give-gift-aid\.zip as 11111111/) }) - it('sends the changelog and the release date it was given', async (t) => { - const { core } = await coreWithOutputs(t) - const { fetch, requests } = heraldFetch(FRESH) - const cwd = checkoutWith({ 'entries.txt': '* Fix - One thing.\n' }) + it('sends the changelog file instead of what Herald read from the ZIP', async (t) => { + const { core, outputs } = await coreWithOutputs(t) + const { fetch, requests } = heraldFetch([ + ...FRESH.slice(0, 3), + { method: 'PATCH', path: API.version, body: { version: '2.2.2', status: 'review', zip_id: ZIP_ID } }, + ]) + const cwd = checkoutWith({ 'entries.txt': '* Fix - From the file.\n' }) await runHeraldPublish({ core, - env: publishEnv({ INPUT_CHANGELOG_FILE: 'entries.txt', INPUT_RELEASE_DATE: '2026-11-25', INPUT_STATUS: 'review' }), + env: publishEnv({ INPUT_CHANGELOG_FILE: 'entries.txt', INPUT_STATUS: 'review' }), fetch, cwd, now: NOW, }) - assert.strictEqual(requests[2].body.release_date, '2026-11-25T00:00:00Z') - assert.deepStrictEqual(requests[3].body, { - zip_id: ZIP_ID, - status: 'review', - changelog: '* Fix - One thing.', - release_date: '2026-11-25T00:00:00Z', - }) + assert.deepStrictEqual(requests[3].body, { zip_id: ZIP_ID, status: 'review', changelog: '* Fix - From the file.' }) + assert.strictEqual(outputs().status, 'review') + }) + + it('gives today as the release date when Herald found none in the ZIP', async (t) => { + const { core } = await coreWithOutputs(t) + const { fetch, requests } = heraldFetch(freshWith({ changelog: '', release_date: null })) + + await runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }) + + assert.deepStrictEqual(requests[3].body, { zip_id: ZIP_ID, status: 'published', release_date: '2026-11-30T00:00:00Z' }) + }) + + it('leaves a changelog that already holds entries only', async (t) => { + const { core } = await coreWithOutputs(t) + const { fetch, requests } = heraldFetch(freshWith({ changelog: '* Fix - One thing.' })) + + await runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }) + + assert.deepStrictEqual(requests[3].body, { zip_id: ZIP_ID, status: 'published' }) }) it('goes on to the update when another run created the version first', async (t) => { @@ -267,11 +315,11 @@ describe('herald-publish', () => { }) describe('a version the product already has', () => { - it('updates it without creating another, and leaves its release date alone', async (t) => { + it('updates it without creating another, and leaves its release date and changelog alone', async (t) => { const { core, outputs, summary } = await coreWithOutputs(t) const { fetch, requests } = heraldFetch([ FRESH[0], - { method: 'GET', path: API.version, body: { version: '2.2.2', status: 'published', zip_id: 'older-zip' } }, + { method: 'GET', path: API.version, body: { ...CREATED, status: 'published', zip_id: 'older-zip', changelog: '* Fix - One thing.' } }, FRESH[3], ]) @@ -291,13 +339,18 @@ describe('herald-publish', () => { const { core, outputs, logged } = await coreWithOutputs(t) const { fetch, requests } = heraldFetch([ { method: 'POST', path: API.upload, status: 400, body: { error: `a ZIP with this content already exists (id: ${ZIP_ID})` } }, - { method: 'GET', path: API.version, body: { version: '2.2.2', status: 'draft', zip_id: ZIP_ID } }, + { method: 'GET', path: API.version, body: CREATED }, FRESH[3], ]) await runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }) - assert.deepStrictEqual(requests[2].body, { zip_id: ZIP_ID, status: 'published' }) + // The draft a failed run left behind still has the header Herald wrote: it goes now. + assert.deepStrictEqual(requests[2].body, { + zip_id: ZIP_ID, + status: 'published', + changelog: '* Fix - One thing.\n* New - Another thing.', + }) assert.deepStrictEqual(outputs(), { 'zip-id': ZIP_ID, sha256: '', status: 'published', created: 'false' }) assert.match(logged(), /already holds give-gift-aid\.zip as 11111111.*reusing it/) }) @@ -340,6 +393,55 @@ describe('herald-publish', () => { ) }) + it('says no version changed when the read of the version fails', async (t) => { + const { core } = await coreWithOutputs(t) + const { fetch, requests } = heraldFetch([FRESH[0], { method: 'GET', path: API.version, status: 500, body: { error: 'database error' } }]) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + /Reading gift-aid 2\.2\.2 in Herald failed \(HTTP 500: database error\)\. The ZIP is in Herald as 11111111.*no version of gift-aid was changed/ + ) + assert.strictEqual(requests.length, 2) + }) + + it('does not say the version is missing when the create got no answer', async (t) => { + const { core } = await coreWithOutputs(t) + const recorded = heraldFetch(FRESH.slice(0, 2)) + const fetch = (url, options = {}) => { + if (options.method === 'POST' && url === API.versions) { + throw new TypeError('fetch failed', { cause: new Error('socket hang up') }) + } + + return recorded.fetch(url, options) + } + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + (error) => { + assert.match(error.message, /Creating gift-aid 2\.2\.2 in Herald failed \(no answer: socket hang up\)/) + assert.match(error.message, /may have created the version/) + assert.doesNotMatch(error.message, /no version of gift-aid was changed/) + + return true + } + ) + }) + + it('treats an answer whose body cannot be read as no answer', async (t) => { + const { core } = await coreWithOutputs(t) + const fetch = async () => ({ + status: 201, + text: async () => { + throw new TypeError('terminated') + }, + }) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + /Uploading give-gift-aid\.zip to Herald failed \(no answer: terminated\)/ + ) + }) + it('names the product when Herald does not have it', async (t) => { const { core } = await coreWithOutputs(t) const { fetch } = heraldFetch([ @@ -354,7 +456,7 @@ describe('herald-publish', () => { ) }) - it('says a new version stayed a draft when the update is refused', async (t) => { + it('does not say what the version holds when the update gets a server error', async (t) => { const { core, outputs } = await coreWithOutputs(t) const { fetch } = heraldFetch([ ...FRESH.slice(0, 3), @@ -363,7 +465,40 @@ describe('herald-publish', () => { await assert.rejects( runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), - /Updating gift-aid 2\.2\.2 in Herald failed \(HTTP 500: database error\)\. The version was created as a draft.*it is not published/ + (error) => { + assert.match(error.message, /Updating gift-aid 2\.2\.2 in Herald failed \(HTTP 500: database error\)/) + assert.match(error.message, /did not confirm the update/) + assert.doesNotMatch(error.message, /it is not published|is as it was/) + + return true + } + ) + assert.deepStrictEqual(outputs(), {}) + }) + + it('says a new version stayed a draft when Herald refuses the update', async (t) => { + const { core } = await coreWithOutputs(t) + const { fetch } = heraldFetch([ + ...FRESH.slice(0, 3), + { method: 'PATCH', path: API.version, status: 400, body: { error: 'changelog too long' } }, + ]) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + /failed \(HTTP 400: changelog too long\)\. The version was created as a draft.*it is not published/ + ) + }) + + it('fails when Herald answers the update with another status', async (t) => { + const { core, outputs } = await coreWithOutputs(t) + const { fetch } = heraldFetch([ + ...FRESH.slice(0, 3), + { method: 'PATCH', path: API.version, body: { version: '2.2.2', status: 'draft', zip_id: ZIP_ID } }, + ]) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + /Herald answered the update of gift-aid 2\.2\.2 with status 'draft'.*not 'published'/ ) assert.deepStrictEqual(outputs(), {}) }) @@ -372,7 +507,7 @@ describe('herald-publish', () => { const { core } = await coreWithOutputs(t) const { fetch } = heraldFetch([ FRESH[0], - { method: 'GET', path: API.version, body: { version: '2.2.2', status: 'published', zip_id: 'older-zip' } }, + { method: 'GET', path: API.version, body: { ...CREATED, status: 'published', zip_id: 'older-zip', changelog: '* Fix - One thing.' } }, { method: 'PATCH', path: API.version, status: 403, body: { error: 'forbidden' } }, ]) From e2eccb92a2400a7a3fd3762b9c9f242bde940d0a Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Mon, 30 Nov 2026 17:57:13 -0300 Subject: [PATCH 04/45] herald-publish README: link Herald's guide for the ci key SOFT-5788 --- .github/actions/herald-publish/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index bdd07157..d8a02127 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -141,7 +141,8 @@ downloading. The key is a Herald API key of scope `ci`. That scope can upload ZIPs and create, read and update versions, and nothing else: it cannot delete a version or touch products, brands or other keys. -Herald's `docs/github-actions.md` says how to create one. +Herald's [GitHub Actions guide](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/docs/github-actions.md#1-create-a-ci-api-key) +says how to create one. With `status: published`, the version is live in Herald when the step ends, with no second click there. So whoever can start the deploy can publish. On GitHub, starting a workflow by hand From 82b947e688722ddafb22c7076c9d30bc996d175c Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Mon, 30 Nov 2026 19:05:08 -0300 Subject: [PATCH 05/45] herald-publish: check the ZIP's version, the product and the key before the upload Run against the Herald staging, three cases went wrong or left a ZIP behind: - A ZIP whose bytes Herald already held was published under any version passed with it. Herald names such a ZIP without saying what is in it, so the comparison with the version Herald reads was skipped. - A ZIP of another version was refused only after the upload. - A product Herald does not have was found out only after the upload. The action now reads the version in the plugin header inside the ZIP itself, from the zip's central directory, and compares it before anything is sent. It reads the version of the product before the upload too, so a key Herald refuses and a product it does not have stop there. The version Herald reads stays as the check for a ZIP the action cannot read; when neither reads one, the run goes on with a warning. The version message is the action's own: the shared one says the version becomes the tag of a published release, which is not what happens here. SOFT-5788 --- .github/actions/herald-publish/README.md | 27 +-- .../actions/herald-publish/herald-publish.js | 190 ++++++++++++++++-- .../herald-publish/herald-publish.test.js | 178 ++++++++++++++-- 3 files changed, 352 insertions(+), 43 deletions(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index d8a02127..33b9110e 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -45,21 +45,25 @@ product has to exist: the action creates versions, never products. ## What it does 1. Checks every input before any call. -2. Uploads the ZIP (`POST /api/v1/zips/upload`). Herald stores it, computes its SHA-256 and reads the - plugin header inside. -3. Compares the version Herald read from the ZIP with `version`, and stops when they differ. A ZIP of - another version, or of another plugin on another version, is not published under this one. -4. Reads the version of the product (`GET /api/v1/products/{product}/versions/{version}`) and - creates it when it is missing (`POST /api/v1/products/{product}/versions`). A new version is a - draft. -5. Updates the version in one call (`PATCH` on the same address): the ZIP, the status and, when they - need a change, the changelog and the release date. Herald writes them together, so a refused +2. Reads the version in the plugin header inside the ZIP and compares it with `version`. A ZIP of + another version, or of another plugin on another version, stops here, before anything is sent. +3. Reads the version of the product (`GET /api/v1/products/{product}/versions/{version}`). A key + Herald refuses and a product it does not have stop here too, with no ZIP left in Herald. +4. Uploads the ZIP (`POST /api/v1/zips/upload`). Herald stores it and computes its SHA-256. +5. Creates the version when it is missing (`POST /api/v1/products/{product}/versions`). A new + version is a draft. +6. Updates the version in one call (`PATCH` on the address of step 3): the ZIP, the status and, when + they need a change, the changelog and the release date. Herald writes them together, so a refused update never leaves the version published with the old ZIP. -6. Checks that Herald's answer shows the status and the ZIP it asked for, and fails when it does +7. Checks that Herald's answer shows the status and the ZIP it asked for, and fails when it does not. The run log and the job summary show the ZIP id and its SHA-256. +The version of step 2 is read as WordPress finds it: in a `.php` right inside the top folder with a +`Plugin Name` header, or in the `style.css` of a theme. When the action cannot read it, the check +falls to what Herald read from the ZIP in step 4. When neither can, the run goes on with a warning. + ## The changelog and the release date Herald fills both for a new version, from the entry of that version in the `readme.txt` inside the @@ -122,8 +126,7 @@ A run can be repeated after a late failure, for the same version: - **The version exists.** It is updated to point at the ZIP of this run. No second version is created. - **The build came out identical.** Herald refuses bytes it already stores and names the record in - the refusal. The action takes that id and goes on. It cannot read that ZIP's plugin header with a - `ci` key, so the version check of step 3 is skipped for a reused ZIP. + the refusal. The action takes that id and goes on. - **Another run created the version in between.** The create is refused as a duplicate, and the action goes on to the update. diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index 075c9b7f..42eff3c6 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -22,8 +22,9 @@ const fs = require('node:fs') const path = require('node:path') +const zlib = require('node:zlib') -const { validateVersion: validateReleaseVersion } = require('../../lib/versions.js') +const { STELLARWP_VERSION_PATTERN } = require('../../lib/versions.js') /** Closes every error message raised before the first write. */ const NOTHING = 'Nothing was published to Herald.' @@ -41,8 +42,17 @@ const REQUEST_TIMEOUT_MS = 30 * 1000 */ const DUPLICATE_ZIP = /a ZIP with this content already exists \(id: ([0-9a-f-]{36})\)/i +/** The signatures of the zip records the reader below walks. */ +const ZIP_END_OF_DIRECTORY = 0x06054b50 +const ZIP_DIRECTORY_ENTRY = 0x02014b50 +const ZIP_LOCAL_HEADER = 0x04034b50 + +/** How much of a file WordPress reads to find its header, and the most a main file may inflate to. */ +const HEADER_BYTES = 8192 +const MAIN_FILE_LIMIT = 5 * 1024 * 1024 + /** - * Reads the version to publish: the shared rule, with this action's closing line. + * Reads the version to publish: three or four numeric parts, the shape every release has. * * @param {string} version The `version` input. * @@ -51,7 +61,20 @@ const DUPLICATE_ZIP = /a ZIP with this content already exists \(id: ([0-9a-f-]{3 * @returns {string} The version, without surrounding whitespace. */ function validateVersion(version) { - return validateReleaseVersion(version, NOTHING) + const trimmed = String(version ?? '').trim() + + if (trimmed === '') { + throw new Error(`No version was given: pass the version being released. ${NOTHING}`) + } + + if (!STELLARWP_VERSION_PATTERN.test(trimmed)) { + throw new Error( + `'${trimmed}' is not a version Herald gets from this action. It takes three or four numeric parts, ` + + `such as 4.17.0 or 4.17.0.1, with no pre-release suffix and no leading v. ${NOTHING}` + ) + } + + return trimmed } /** @@ -146,7 +169,8 @@ function readStatus(status) { * * @throws {Error} When it is empty, not a `.zip`, not a file, or an empty file. * - * @returns {{name: string, file: string, size: number}} The file's name, its path and its size. + * @returns {{name: string, file: string, size: number, data: Buffer}} The file's name, its path, its + * size and its bytes. */ function readZip(zip, cwd) { const trimmed = String(zip ?? '').trim() @@ -175,7 +199,7 @@ function readZip(zip, cwd) { throw new Error(`zip '${trimmed}' is empty. ${NOTHING}`) } - return { name: path.basename(file), file, size: stat.size } + return { name: path.basename(file), file, size: stat.size, data: fs.readFileSync(file) } } /** @@ -227,6 +251,121 @@ function readChangelogFile(input, cwd) { return entries.join('\n') } +/** + * Lists the files of a zip from its central directory, the index at the end of the archive. + * + * @param {Buffer} zip The archive. + * + * @returns {Array<{name: string, method: number, size: number, offset: number}>|null} Each file's + * name, compression method, compressed size and the offset of its local header. Null when + * the bytes are not a zip this reader walks: no directory, or a zip64 archive. + */ +function zipEntries(zip) { + // The end record is the last 22 bytes, or sits before a comment of at most 65535. + let end = -1 + for (let at = zip.length - 22; at >= Math.max(0, zip.length - 22 - 0xffff); at--) { + if (zip.readUInt32LE(at) === ZIP_END_OF_DIRECTORY) { + end = at + break + } + } + + if (end === -1) { + return null + } + + const count = zip.readUInt16LE(end + 10) + let at = zip.readUInt32LE(end + 16) + if (count === 0xffff || at === 0xffffffff) { + return null + } + + const entries = [] + for (let index = 0; index < count; index++) { + if (at + 46 > zip.length || zip.readUInt32LE(at) !== ZIP_DIRECTORY_ENTRY) { + return null + } + + const nameLength = zip.readUInt16LE(at + 28) + entries.push({ + name: zip.toString('utf8', at + 46, at + 46 + nameLength), + method: zip.readUInt16LE(at + 10), + size: zip.readUInt32LE(at + 20), + offset: zip.readUInt32LE(at + 42), + }) + at += 46 + nameLength + zip.readUInt16LE(at + 30) + zip.readUInt16LE(at + 32) + } + + return entries +} + +/** + * Reads the first bytes of one file of a zip. + * + * @param {Buffer} zip The archive. + * @param {object} entry One of `zipEntries`. + * + * @returns {string|null} The start of the file as text, or null when it cannot be read: a method + * other than stored or deflated, or data that does not inflate. + */ +function zipFileStart(zip, entry) { + const at = entry.offset + if (at + 30 > zip.length || zip.readUInt32LE(at) !== ZIP_LOCAL_HEADER) { + return null + } + + const start = at + 30 + zip.readUInt16LE(at + 26) + zip.readUInt16LE(at + 28) + const data = zip.subarray(start, start + entry.size) + + try { + const file = entry.method === 0 ? data : entry.method === 8 ? zlib.inflateRawSync(data, { maxOutputLength: MAIN_FILE_LIMIT }) : null + + return file === null ? null : file.subarray(0, HEADER_BYTES).toString('utf8') + } catch { + return null + } +} + +/** + * Reads the version in the header of the plugin or the theme inside a zip, as WordPress finds it: + * a `.php` right inside the top folder with a `Plugin Name` header, or the `style.css` there with + * a `Theme Name` header. + * + * It is what makes the version check possible before anything is sent, and for a ZIP Herald + * already holds, which Herald names without saying what is in it. + * + * @param {Buffer} zip The archive. + * + * @returns {{file: string, version: string}|null} The main file and its version, or null when the + * bytes are not a zip this reads, or no main file with a version is found. + */ +function readZipVersion(zip) { + const entries = zipEntries(zip) + if (entries === null) { + return null + } + + for (const entry of entries) { + const plugin = /^[^/]+\/[^/]+\.php$/.test(entry.name) + const theme = /^[^/]+\/style\.css$/.test(entry.name) + if (!plugin && !theme) { + continue + } + + const start = zipFileStart(zip, entry) + const named = plugin ? /^[ \t/*#@]*Plugin Name:/im : /^[ \t/*#@]*Theme Name:/im + if (start === null || !named.test(start)) { + continue + } + + const version = /^[ \t/*#@]*Version:[ \t]*(\S+)/im.exec(start) + + return version ? { file: entry.name, version: version[1] } : null + } + + return null +} + /** * Takes the version headers out of a changelog Herald filled from the ZIP's readme.txt. * @@ -372,7 +511,7 @@ function unconfirmed(answer) { */ async function uploadZip({ fetch, base, apiKey, zip }) { const form = new FormData() - form.append('file', new Blob([fs.readFileSync(zip.file)], { type: 'application/zip' }), zip.name) + form.append('file', new Blob([zip.data], { type: 'application/zip' }), zip.name) const answer = await send({ fetch, @@ -405,8 +544,9 @@ async function uploadZip({ fetch, base, apiKey, zip }) { * @param {string} options.cwd The checkout, the working directory by default. * @param {Date} options.now The current time, for the release date of a version with none. * - * @throws {Error} When an input is wrong, the ZIP holds another version, Herald refuses a call, or - * its answer to the update shows another status or another ZIP. + * @throws {Error} When an input is wrong, the ZIP holds another version, Herald does not have the + * product or refuses a call, or its answer to the update shows another status or + * another ZIP. * * @returns {Promise} Resolves once Herald confirms the version points at the ZIP, in the * status asked for. @@ -421,6 +561,27 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro const apiKey = readApiKey(env.INPUT_API_KEY) core.setSecret(apiKey) + // The version in the ZIP's own plugin header, read here so a ZIP of another version, or of + // another plugin on another version, stops before anything is sent. + const inside = readZipVersion(zip.data) + if (inside !== null && inside.version !== version) { + throw new Error(`${zip.name} is version ${inside.version} (${inside.file}), not ${version}. ${NOTHING}`) + } + + const versions = `${base}/api/v1/products/${encodeURIComponent(product)}/versions` + const versionUrl = `${versions}/${encodeURIComponent(version)}` + + // Read before the upload: a key Herald refuses and a product it does not have stop here, with + // no ZIP left behind. Herald answers 404 for both a missing product and a missing version. + const found = await send({ fetch, url: versionUrl, apiKey }) + if (found.status === 404 && /product .* not found/i.test(found.reason)) { + throw new Error(`Herald has no product '${product}': create it there, or correct the slug. ${NOTHING}`) + } + + if (found.status !== 200 && found.status !== 404) { + throw new Error(`Reading ${product} ${version} in Herald failed (${failure(found)}). ${NOTHING}`) + } + const uploaded = await uploadZip({ fetch, base, apiKey, zip }) const stored = `The ZIP is in Herald as ${uploaded.id}, and no version of ${product} was changed.` core.info( @@ -429,8 +590,8 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro : `Uploaded ${zip.name} as ${uploaded.id} (sha256 ${uploaded.sha256}).` ) - // Herald reads the plugin header of the ZIP it stores. A ZIP of another version, or of another - // plugin on another version, stops here rather than being published under this one. + // Herald reads the plugin header too, of a ZIP it stores for the first time. It is the check + // left when the read above found no version. const zipVersion = uploaded.meta?.version if (typeof zipVersion === 'string' && zipVersion.trim() !== '' && zipVersion.trim() !== version) { throw new Error( @@ -439,12 +600,8 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro ) } - const versions = `${base}/api/v1/products/${encodeURIComponent(product)}/versions` - const versionUrl = `${versions}/${encodeURIComponent(version)}` - - const found = await send({ fetch, url: versionUrl, apiKey }) - if (found.status !== 200 && found.status !== 404) { - throw new Error(`Reading ${product} ${version} in Herald failed (${failure(found)}). ${stored}`) + if (inside === null && (typeof zipVersion !== 'string' || zipVersion.trim() === '')) { + core.warning(`The version inside ${zip.name} could not be read, so it was not compared with ${version}.`) } // What Herald holds for the version: read above, or answered by the create below. Null when @@ -531,5 +688,6 @@ module.exports = { readZip, readChangelogFile, entriesOnly, + readZipVersion, readApiKey, } diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index fde8be88..f884707e 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -5,15 +5,18 @@ const assert = require('node:assert') const fs = require('node:fs') const os = require('node:os') const path = require('node:path') +const zlib = require('node:zlib') const { runHeraldPublish, + validateVersion, readUrl, readProduct, readStatus, readZip, readChangelogFile, entriesOnly, + readZipVersion, readApiKey, } = require('../../../.github/actions/herald-publish/herald-publish.js') const { coreWithOutputs, recordingFetch } = require('../../support/actions.js') @@ -80,6 +83,71 @@ function publishEnv(overrides = {}) { } } +/** + * Builds a zip in memory, as `zip` writes it: a local header and the data per file, then the + * central directory and its end record. + * + * @param {object} files File contents by path inside the zip. + * @param {boolean} deflate Whether the files are compressed (method 8) or stored (method 0). + * + * @returns {Buffer} The zip. + */ +function zipOf(files, deflate = true) { + const locals = [] + const directory = [] + let offset = 0 + + for (const [name, contents] of Object.entries(files)) { + const raw = Buffer.from(contents) + const data = deflate ? zlib.deflateRawSync(raw) : raw + const file = Buffer.from(name) + + const local = Buffer.alloc(30) + local.writeUInt32LE(0x04034b50, 0) + local.writeUInt16LE(deflate ? 8 : 0, 8) + local.writeUInt32LE(data.length, 18) + local.writeUInt32LE(raw.length, 22) + local.writeUInt16LE(file.length, 26) + locals.push(local, file, data) + + const entry = Buffer.alloc(46) + entry.writeUInt32LE(0x02014b50, 0) + entry.writeUInt16LE(deflate ? 8 : 0, 10) + entry.writeUInt32LE(data.length, 20) + entry.writeUInt32LE(raw.length, 24) + entry.writeUInt16LE(file.length, 28) + entry.writeUInt32LE(offset, 42) + directory.push(entry, file) + + offset += 30 + file.length + data.length + } + + const central = Buffer.concat(directory) + const end = Buffer.alloc(22) + end.writeUInt32LE(0x06054b50, 0) + end.writeUInt16LE(Object.keys(files).length, 8) + end.writeUInt16LE(Object.keys(files).length, 10) + end.writeUInt32LE(central.length, 12) + end.writeUInt32LE(offset, 16) + + return Buffer.concat([...locals, central, end]) +} + +/** + * The zip of the plugin at a version: a readme, an include, and the main file with its header. + * + * @param {string} version The version in the plugin header. + * + * @returns {Buffer} The zip. + */ +function pluginZip(version = '2.2.2') { + return zipOf({ + 'give-gift-aid/readme.txt': `=== Gift Aid ===\nStable tag: ${version}\n`, + 'give-gift-aid/includes/version.php': " { assert.strictEqual(entriesOnly(undefined), null) }) + it('reads the version in the plugin header of a zip, compressed or stored', () => { + assert.deepStrictEqual(readZipVersion(pluginZip('2.2.2')), { file: 'give-gift-aid/give-gift-aid.php', version: '2.2.2' }) + + const stored = zipOf({ 'my-plugin/my-plugin.php': ' { + const theme = zipOf({ 'my-theme/functions.php': ' { + assert.strictEqual(readZipVersion(Buffer.from('PK\u0003\u0004 not a zip')), null) + assert.strictEqual(readZipVersion(zipOf({ 'my-plugin/readme.txt': 'Stable tag: 1.0.0\n' })), null) + assert.strictEqual(readZipVersion(zipOf({ 'my-plugin/includes/deep.php': ' { + assert.throws(() => validateVersion('2.2.2-rc.1'), /is not a version Herald gets from this action.*Nothing was published to Herald/) + assert.throws(() => validateVersion(''), /No version was given/) + assert.strictEqual(validateVersion(' 2.2.2.1 '), '2.2.2.1') + }) + it('refuses a missing key and one with whitespace inside', () => { assert.strictEqual(readApiKey(' herald-ci-key\n'), 'herald-ci-key') assert.throws(() => readApiKey(''), /No api-key was given/) @@ -241,12 +334,12 @@ describe('herald-publish', () => { await runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }) assert.deepStrictEqual(calls(requests), [ - 'POST /api/v1/zips/upload', 'GET /api/v1/products/gift-aid/versions/2.2.2', + 'POST /api/v1/zips/upload', 'POST /api/v1/products/gift-aid/versions', 'PATCH /api/v1/products/gift-aid/versions/2.2.2', ]) - assert.strictEqual(requests[0].body.get('file').name, 'give-gift-aid.zip') + assert.strictEqual(requests[1].body.get('file').name, 'give-gift-aid.zip') assert.deepStrictEqual(requests[2].body, { version: '2.2.2', zip_id: ZIP_ID }) assert.deepStrictEqual(requests[3].body, { zip_id: ZIP_ID, @@ -326,8 +419,8 @@ describe('herald-publish', () => { await runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }) assert.deepStrictEqual(calls(requests), [ - 'POST /api/v1/zips/upload', 'GET /api/v1/products/gift-aid/versions/2.2.2', + 'POST /api/v1/zips/upload', 'PATCH /api/v1/products/gift-aid/versions/2.2.2', ]) assert.deepStrictEqual(requests[2].body, { zip_id: ZIP_ID, status: 'published' }) @@ -357,28 +450,83 @@ describe('herald-publish', () => { }) describe('what stops it', () => { - it('refuses a ZIP whose plugin header holds another version', async (t) => { + it('refuses a ZIP whose plugin header holds another version, before any call', async (t) => { const { core, outputs } = await coreWithOutputs(t) + // Herald would take these bytes as a ZIP it already holds and say nothing about their version. + const { fetch, requests } = heraldFetch([ + { method: 'POST', path: API.upload, status: 400, body: { error: `a ZIP with this content already exists (id: ${ZIP_ID})` } }, + ...FRESH.slice(1), + ]) + const cwd = checkoutWith({ 'give-gift-aid.zip': pluginZip('2.20.5') }) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd, now: NOW }), + /give-gift-aid\.zip is version 2\.20\.5 \(give-gift-aid\/give-gift-aid\.php\), not 2\.2\.2\. Nothing was published to Herald/ + ) + assert.deepStrictEqual(requests, []) + assert.deepStrictEqual(outputs(), {}) + }) + + it('refuses a ZIP it could not read when Herald reads another version in it', async (t) => { + const { core } = await coreWithOutputs(t) const recurring = { ...ZIP_RECORD, meta: { ...ZIP_RECORD.meta, main_file: 'give-recurring/give-recurring.php', version: '2.20.5' } } const { fetch, requests } = heraldFetch([{ method: 'POST', path: API.upload, status: 201, body: recurring }, ...FRESH.slice(1)]) + const cwd = checkoutWith({ 'give-gift-aid.zip': 'PK\u0003\u0004 not a zip the action can read' }) await assert.rejects( - runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + runHeraldPublish({ core, env: publishEnv(), fetch, cwd, now: NOW }), /is version 2\.20\.5 \(give-recurring\/give-recurring\.php\), not 2\.2\.2.*no version of gift-aid was changed/s ) - assert.deepStrictEqual(calls(requests), ['POST /api/v1/zips/upload']) - assert.deepStrictEqual(outputs(), {}) + assert.deepStrictEqual(calls(requests), ['GET /api/v1/products/gift-aid/versions/2.2.2', 'POST /api/v1/zips/upload']) + }) + + it('warns when neither the action nor Herald could read the version of the ZIP', async (t) => { + const { core, logged } = await coreWithOutputs(t) + const { fetch } = heraldFetch([ + { method: 'POST', path: API.upload, status: 400, body: { error: `a ZIP with this content already exists (id: ${ZIP_ID})` } }, + ...FRESH.slice(1), + ]) + const cwd = checkoutWith({ 'give-gift-aid.zip': 'PK\u0003\u0004 not a zip the action can read' }) + + await runHeraldPublish({ core, env: publishEnv(), fetch, cwd, now: NOW }) + + assert.match(logged(), /::warning::The version inside give-gift-aid\.zip could not be read, so it was not compared with 2\.2\.2/) + }) + + it('stops before the upload when Herald does not have the product', async (t) => { + const { core } = await coreWithOutputs(t) + const { fetch, requests } = heraldFetch([ + FRESH[0], + { method: 'GET', path: API.version, status: 404, body: { error: "product 'gift-aid' not found" } }, + ]) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + /Herald has no product 'gift-aid'.*Nothing was published to Herald/ + ) + assert.deepStrictEqual(calls(requests), ['GET /api/v1/products/gift-aid/versions/2.2.2']) + }) + + it('stops before the upload when Herald refuses the key', async (t) => { + const { core } = await coreWithOutputs(t) + const { fetch, requests } = heraldFetch([FRESH[0], { method: 'GET', path: API.version, status: 401, body: { error: 'unauthorized' } }]) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + /Reading gift-aid 2\.2\.2 in Herald failed \(HTTP 401: unauthorized\)\. Nothing was published to Herald/ + ) + assert.deepStrictEqual(calls(requests), ['GET /api/v1/products/gift-aid/versions/2.2.2']) }) it('stops at an upload Herald refuses', async (t) => { const { core } = await coreWithOutputs(t) - const { fetch, requests } = heraldFetch([{ method: 'POST', path: API.upload, status: 401, body: { error: 'invalid API key' } }]) + const { fetch, requests } = heraldFetch([FRESH[1], { method: 'POST', path: API.upload, status: 400, body: { error: 'ZIP security check failed: too many entries' } }]) await assert.rejects( runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), - /Uploading give-gift-aid\.zip to Herald failed \(HTTP 401: invalid API key\)\. Nothing was published to Herald/ + /Uploading give-gift-aid\.zip to Herald failed \(HTTP 400: ZIP security check failed: too many entries\)\. Nothing was published to Herald/ ) - assert.deepStrictEqual(calls(requests), ['POST /api/v1/zips/upload']) + assert.deepStrictEqual(calls(requests), ['GET /api/v1/products/gift-aid/versions/2.2.2', 'POST /api/v1/zips/upload']) }) it('says so when Herald does not answer', async (t) => { @@ -393,15 +541,15 @@ describe('herald-publish', () => { ) }) - it('says no version changed when the read of the version fails', async (t) => { + it('uploads nothing when the read of the version fails', async (t) => { const { core } = await coreWithOutputs(t) const { fetch, requests } = heraldFetch([FRESH[0], { method: 'GET', path: API.version, status: 500, body: { error: 'database error' } }]) await assert.rejects( runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), - /Reading gift-aid 2\.2\.2 in Herald failed \(HTTP 500: database error\)\. The ZIP is in Herald as 11111111.*no version of gift-aid was changed/ + /Reading gift-aid 2\.2\.2 in Herald failed \(HTTP 500: database error\)\. Nothing was published to Herald/ ) - assert.strictEqual(requests.length, 2) + assert.strictEqual(requests.length, 1) }) it('does not say the version is missing when the create got no answer', async (t) => { @@ -438,7 +586,7 @@ describe('herald-publish', () => { await assert.rejects( runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), - /Uploading give-gift-aid\.zip to Herald failed \(no answer: terminated\)/ + /Reading gift-aid 2\.2\.2 in Herald failed \(no answer: terminated\)\. Nothing was published to Herald/ ) }) From 7131af2400bbe68e2253df47cb13bca2d13b0166 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Mon, 30 Nov 2026 19:07:14 -0300 Subject: [PATCH 06/45] herald-publish: say in the log when the version header is taken out of the changelog SOFT-5788 --- .github/actions/herald-publish/herald-publish.js | 3 +++ tests/actions/herald-publish/herald-publish.test.js | 1 + 2 files changed, 4 insertions(+) diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index 42eff3c6..725c368b 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -629,6 +629,9 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro // The changelog field takes entries only. Without a file, the header Herald wrote above the // entries it read from the ZIP goes; a changelog that holds entries only is left alone. const entries = changelog ?? entriesOnly(current?.changelog) + if (changelog === null && entries !== null) { + core.info('Took the version header out of the changelog Herald read from the ZIP.') + } const undated = current !== null && !current?.release_date // One call for the ZIP, the status and the rest: Herald writes them together, so a refused diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index f884707e..72180bc1 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -351,6 +351,7 @@ describe('herald-publish', () => { assert.deepStrictEqual(outputs(), { 'zip-id': ZIP_ID, sha256: SHA256, status: 'published', created: 'true' }) assert.match(summary(), /`gift-aid` 2\.2\.2 is published, created with the ZIP/) assert.match(logged(), /Uploaded give-gift-aid\.zip as 11111111/) + assert.match(logged(), /Took the version header out of the changelog/) }) it('sends the changelog file instead of what Herald read from the ZIP', async (t) => { From 457541ebbe8c1932961219c508e62897056d8647 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Mon, 30 Nov 2026 19:14:08 -0300 Subject: [PATCH 07/45] herald-publish README: shorter sentences in What it does SOFT-5788 --- .github/actions/herald-publish/README.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index 33b9110e..25f86d25 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -52,17 +52,18 @@ product has to exist: the action creates versions, never products. 4. Uploads the ZIP (`POST /api/v1/zips/upload`). Herald stores it and computes its SHA-256. 5. Creates the version when it is missing (`POST /api/v1/products/{product}/versions`). A new version is a draft. -6. Updates the version in one call (`PATCH` on the address of step 3): the ZIP, the status and, when - they need a change, the changelog and the release date. Herald writes them together, so a refused - update never leaves the version published with the old ZIP. +6. Updates the version in one call, a `PATCH` on the address of step 3. It sends the ZIP, the status + and, when they need a change, the changelog and the release date. Herald writes them together, so + a refused update never leaves the version published with the old ZIP. 7. Checks that Herald's answer shows the status and the ZIP it asked for, and fails when it does not. The run log and the job summary show the ZIP id and its SHA-256. -The version of step 2 is read as WordPress finds it: in a `.php` right inside the top folder with a -`Plugin Name` header, or in the `style.css` of a theme. When the action cannot read it, the check -falls to what Herald read from the ZIP in step 4. When neither can, the run goes on with a warning. +The version of step 2 is read where WordPress finds it. That is a `.php` right inside the top folder +with a `Plugin Name` header, or the `style.css` of a theme. When the action cannot read it, the +check falls to what Herald read from the ZIP in step 4. When neither can, the run goes on with a +warning. ## The changelog and the release date From fb7c538fc9e2f95020abe4057c2ec469cbf49bf2 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 11:16:25 -0300 Subject: [PATCH 08/45] herald-publish: production Herald by default, and a link to the product's versions A repository had to carry the Herald address in a variable of its own. The address is the same for every plugin and is no secret, so herald-url is now optional and defaults to the production Herald. An empty value is refused rather than taken as production, so a caller that wires a variable that turns out empty does not publish to production by accident. The log, the job summary and a new versions-url output link the page of the Herald dashboard that lists the product's versions. Herald has no page per version; that page lists them newest first. The README and the template show how the step runs only where the HERALD_API_KEY secret exists, which is meant to be an organization secret: a step's `if` cannot read a secret, so the job sets HERALD_CONFIGURED. SOFT-5788 --- .github/actions/herald-publish/README.md | 24 +++++++++++++--- .github/actions/herald-publish/action.yml | 11 ++++++-- .../actions/herald-publish/herald-publish.js | 12 ++++++-- templates/workflows/release.yml | 15 ++++++---- .../herald-publish/herald-publish.test.js | 28 ++++++++++++++++--- 5 files changed, 71 insertions(+), 19 deletions(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index 25f86d25..175907d9 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -23,9 +23,8 @@ deploy the action runs after the build and before # Build the plugin here, from the merged commit. - uses: stellarwp/plugin-toolbox/.github/actions/herald-publish@v1 - if: steps.merge.outputs.already-published == 'no' + if: env.HERALD_CONFIGURED == 'true' && steps.merge.outputs.already-published == 'no' with: - herald-url: ${{ vars.HERALD_URL }} product: my-plugin version: ${{ inputs.version }} zip: build/my-plugin.zip @@ -42,6 +41,21 @@ deploy the action runs after the build and before `product` is the slug of the product in Herald, which is not always the repository's name. The product has to exist: the action creates versions, never products. +The step runs only where the key exists. A step's `if` cannot read a secret, so the job says whether +there is one: + +```yaml +jobs: + release: + env: + HERALD_CONFIGURED: ${{ secrets.HERALD_API_KEY != '' }} +``` + +The key is meant to be an organization secret, created once and made available to the repositories +that release to Herald. A repository the secret does not reach skips the step and deploys as before. +The address needs no setup: the action goes to the production Herald unless `herald-url` says +otherwise. + ## What it does 1. Checks every input before any call. @@ -58,7 +72,8 @@ product has to exist: the action creates versions, never products. 7. Checks that Herald's answer shows the status and the ZIP it asked for, and fails when it does not. -The run log and the job summary show the ZIP id and its SHA-256. +The run log and the job summary show the ZIP id, its SHA-256 and a link to the product's versions in +the Herald dashboard. Herald has no page per version; that page lists them newest first. The version of step 2 is read where WordPress finds it. That is a `.php` right inside the top folder with a `Plugin Name` header, or the `style.css` of a theme. When the action cannot read it, the @@ -103,7 +118,7 @@ own version instead of the entries. | Input | Required | Default | What it is | |---|---|---|---| -| `herald-url` | yes | | The address of the Herald instance. HTTPS, or plain HTTP for `localhost`. | +| `herald-url` | no | `https://herald.nexcess.com` | The address of the Herald instance. Pass another one to test against a staging Herald. HTTPS, or plain HTTP for `localhost`. An empty value is refused. | | `product` | yes | | The slug of the product in Herald. | | `version` | yes | | The version being released: three or four numeric parts. | | `zip` | yes | | The build to upload, a `.zip` path relative to the checkout. | @@ -119,6 +134,7 @@ own version instead of the entries. | `sha256` | The SHA-256 Herald computed for the ZIP. Empty when Herald already held the same bytes. | | `status` | The status the version was left in. | | `created` | `true` when the version was created, `false` when it existed and was updated. | +| `versions-url` | The page of the Herald dashboard that lists the product's versions, newest first. | ## Running it again diff --git a/.github/actions/herald-publish/action.yml b/.github/actions/herald-publish/action.yml index fb5929e5..cc2f6fd3 100644 --- a/.github/actions/herald-publish/action.yml +++ b/.github/actions/herald-publish/action.yml @@ -12,9 +12,11 @@ description: Uploads a plugin ZIP to Herald and publishes it as a version of a p inputs: herald-url: description: >- - The address of the Herald instance, e.g. `https://herald.example.com`. HTTPS, since the API key - goes in every request; plain HTTP is accepted for `localhost` only. - required: true + The address of the Herald instance. The production Herald when left out; pass another address + to test against a staging one. HTTPS, since the API key goes in every request; plain HTTP is + accepted for `localhost` only. An empty value is refused rather than taken as production. + required: false + default: 'https://herald.nexcess.com' product: description: 'The slug of the product in Herald, as its Products page shows it.' required: true @@ -60,6 +62,9 @@ outputs: created: description: '`true` when the version was created, `false` when it existed and was updated.' value: ${{ steps.publish.outputs.created }} + versions-url: + description: "The page of the Herald dashboard that lists the product's versions, newest first." + value: ${{ steps.publish.outputs.versions-url }} runs: using: 'composite' diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index 725c368b..bfacc97b 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -91,7 +91,9 @@ function readUrl(url) { const trimmed = String(url ?? '').trim() if (trimmed === '') { - throw new Error(`No herald-url was given: pass the address of the Herald instance. ${NOTHING}`) + throw new Error( + `herald-url is empty: pass the address of the Herald instance, or leave the input out for the production one. ${NOTHING}` + ) } let parsed @@ -668,15 +670,19 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro ) } - core.info(`${product} ${version} is ${status} in Herald with the ZIP ${uploaded.id}.`) + // Herald has no page per version. The product's versions page lists them newest first. + const versionsUrl = `${base}/admin/products/${encodeURIComponent(product)}/versions` + + core.info(`${product} ${version} is ${status} in Herald with the ZIP ${uploaded.id}: ${versionsUrl}`) core.setOutput('zip-id', uploaded.id) core.setOutput('sha256', uploaded.sha256) core.setOutput('status', status) core.setOutput('created', created ? 'true' : 'false') + core.setOutput('versions-url', versionsUrl) await core.summary .addRaw( `Herald: \`${product}\` ${version} is ${status}, ${created ? 'created' : 'updated'} with the ZIP \`${uploaded.id}\`` + - `${uploaded.sha256 === '' ? '' : ` (sha256 \`${uploaded.sha256}\`)`}.`, + `${uploaded.sha256 === '' ? '' : ` (sha256 \`${uploaded.sha256}\`)`}: ${versionsUrl}`, true ) .write() diff --git a/templates/workflows/release.yml b/templates/workflows/release.yml index ba625493..beaeb510 100644 --- a/templates/workflows/release.yml +++ b/templates/workflows/release.yml @@ -50,6 +50,10 @@ jobs: environment: live permissions: contents: write # release-merge writes the merges, release-publish creates the tag and the release + # For the herald-publish step below: the secrets context is not available in a step's `if`, so + # whether the Herald key exists is decided here. + # env: + # HERALD_CONFIGURED: ${{ secrets.HERALD_API_KEY != '' }} steps: # The environment's branch policy protects the branch the run was started on, not the input. # The two have to be the same branch, so the policy covers what is actually merged and @@ -84,13 +88,14 @@ jobs: persist-credentials: false # For a product sold through Herald: upload the build and publish the version there before the - # GitHub release, so a failed upload leaves no release behind. As a secret of the environment - # above, the key is read only by a run that environment accepts. The condition skips the rerun - # of a version already published, which would replace a ZIP customers are downloading. + # GitHub release, so a failed upload leaves no release behind. The key is the HERALD_API_KEY + # secret, of the organization or of the environment above. The condition runs the step only + # where that secret exists, and skips the rerun of a version already published, which would + # replace a ZIP customers are downloading. It needs the HERALD_CONFIGURED line of the job's + # `env` above. # - uses: stellarwp/plugin-toolbox/.github/actions/herald-publish@v1 - # if: steps.merge.outputs.already-published == 'no' + # if: env.HERALD_CONFIGURED == 'true' && steps.merge.outputs.already-published == 'no' # with: - # herald-url: ${{ vars.HERALD_URL }} # product: my-plugin # version: ${{ inputs.version }} # zip: build/my-plugin.zip diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index 72180bc1..8127fb5b 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -31,6 +31,9 @@ const API = { } const ZIP_ID = '11111111-2222-4333-8444-555555555555' + +/** The page of the Herald dashboard that lists the product's versions, newest first. */ +const VERSIONS_URL = `${BASE}/admin/products/gift-aid/versions` const SHA256 = 'ab'.repeat(32) /** The ZIP record Herald answers an upload with: it reads the plugin header of what it stores. */ @@ -228,8 +231,24 @@ describe('herald-publish', () => { assert.throws(() => readUrl('https://herald.example.com/?key=1'), /address only/) }) + it('links the versions page of the product, with a slug that needs encoding kept safe', async (t) => { + const { core, outputs } = await coreWithOutputs(t) + const product = 'gift aid'.replace(' ', '%') + const base = `${BASE}/api/v1/products/${encodeURIComponent(product)}/versions` + const { fetch } = heraldFetch([ + FRESH[0], + { method: 'GET', path: `${base}/2.2.2`, status: 404, body: { error: "version '2.2.2' not found" } }, + { method: 'POST', path: base, status: 201, body: CREATED }, + { method: 'PATCH', path: `${base}/2.2.2`, body: { version: '2.2.2', status: 'published', zip_id: ZIP_ID } }, + ]) + + await runHeraldPublish({ core, env: publishEnv({ INPUT_PRODUCT: product }), fetch, cwd: checkoutWith(), now: NOW }) + + assert.strictEqual(outputs()['versions-url'], `${BASE}/admin/products/gift%25aid/versions`) + }) + it('refuses an empty address and one that is not a URL', () => { - assert.throws(() => readUrl(''), /No herald-url was given/) + assert.throws(() => readUrl(''), /herald-url is empty.*leave the input out for the production one/) assert.throws(() => readUrl('herald'), /is not a URL/) }) @@ -348,8 +367,9 @@ describe('herald-publish', () => { }) assert.ok(sent.every((options) => options.headers.authorization === 'Bearer herald-ci-key')) assert.ok(sent.every((options) => options.redirect === 'error')) - assert.deepStrictEqual(outputs(), { 'zip-id': ZIP_ID, sha256: SHA256, status: 'published', created: 'true' }) - assert.match(summary(), /`gift-aid` 2\.2\.2 is published, created with the ZIP/) + assert.deepStrictEqual(outputs(), { 'zip-id': ZIP_ID, sha256: SHA256, status: 'published', created: 'true', 'versions-url': VERSIONS_URL }) + assert.match(summary(), /`gift-aid` 2\.2\.2 is published, created with the ZIP.*: https:\/\/herald\.test\/admin\/products\/gift-aid\/versions/) + assert.match(logged(), /gift-aid 2\.2\.2 is published in Herald with the ZIP 11111111.*: https:\/\/herald\.test\/admin\/products\/gift-aid\/versions/) assert.match(logged(), /Uploaded give-gift-aid\.zip as 11111111/) assert.match(logged(), /Took the version header out of the changelog/) }) @@ -445,7 +465,7 @@ describe('herald-publish', () => { status: 'published', changelog: '* Fix - One thing.\n* New - Another thing.', }) - assert.deepStrictEqual(outputs(), { 'zip-id': ZIP_ID, sha256: '', status: 'published', created: 'false' }) + assert.deepStrictEqual(outputs(), { 'zip-id': ZIP_ID, sha256: '', status: 'published', created: 'false', 'versions-url': VERSIONS_URL }) assert.match(logged(), /already holds give-gift-aid\.zip as 11111111.*reusing it/) }) }) From 6886787abe2a359b24bb3db6f65a98a75cfceee2 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 11:17:19 -0300 Subject: [PATCH 09/45] herald-publish: name the Herald address in the log SOFT-5788 --- .github/actions/herald-publish/herald-publish.js | 2 ++ tests/actions/herald-publish/herald-publish.test.js | 1 + 2 files changed, 3 insertions(+) diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index bfacc97b..8d807745 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -563,6 +563,8 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro const apiKey = readApiKey(env.INPUT_API_KEY) core.setSecret(apiKey) + core.info(`Publishing ${product} ${version} to ${base}.`) + // The version in the ZIP's own plugin header, read here so a ZIP of another version, or of // another plugin on another version, stops before anything is sent. const inside = readZipVersion(zip.data) diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index 8127fb5b..4d961ec0 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -372,6 +372,7 @@ describe('herald-publish', () => { assert.match(logged(), /gift-aid 2\.2\.2 is published in Herald with the ZIP 11111111.*: https:\/\/herald\.test\/admin\/products\/gift-aid\/versions/) assert.match(logged(), /Uploaded give-gift-aid\.zip as 11111111/) assert.match(logged(), /Took the version header out of the changelog/) + assert.match(logged(), /Publishing gift-aid 2\.2\.2 to https:\/\/herald\.test/) }) it('sends the changelog file instead of what Herald read from the ZIP', async (t) => { From 913f463dbc44ceb36a8c1a7eca874534e9412888 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 11:26:38 -0300 Subject: [PATCH 10/45] herald-publish: the caller names the Herald instance, with no default herald-url is required again. A shared action in a public repository should not point at one organization's instance by default, and a workflow that forgets the input should fail rather than publish somewhere nobody chose. The workflow that calls the action says where the release goes. SOFT-5788 --- .github/actions/herald-publish/README.md | 10 +++++----- .github/actions/herald-publish/action.yml | 9 ++++----- .github/actions/herald-publish/herald-publish.js | 7 +++---- templates/workflows/release.yml | 1 + tests/actions/herald-publish/herald-publish.test.js | 2 +- 5 files changed, 14 insertions(+), 15 deletions(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index 175907d9..b365e99f 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -25,6 +25,7 @@ deploy the action runs after the build and before - uses: stellarwp/plugin-toolbox/.github/actions/herald-publish@v1 if: env.HERALD_CONFIGURED == 'true' && steps.merge.outputs.already-published == 'no' with: + herald-url: https://herald.example.com product: my-plugin version: ${{ inputs.version }} zip: build/my-plugin.zip @@ -38,8 +39,9 @@ deploy the action runs after the build and before build/my-plugin.zip ``` -`product` is the slug of the product in Herald, which is not always the repository's name. The -product has to exist: the action creates versions, never products. +`herald-url` is the address of the Herald instance, and the action has no default for it: the +workflow says where the release goes. `product` is the slug of the product in Herald, which is not +always the repository's name. The product has to exist: the action creates versions, never products. The step runs only where the key exists. A step's `if` cannot read a secret, so the job says whether there is one: @@ -53,8 +55,6 @@ jobs: The key is meant to be an organization secret, created once and made available to the repositories that release to Herald. A repository the secret does not reach skips the step and deploys as before. -The address needs no setup: the action goes to the production Herald unless `herald-url` says -otherwise. ## What it does @@ -118,7 +118,7 @@ own version instead of the entries. | Input | Required | Default | What it is | |---|---|---|---| -| `herald-url` | no | `https://herald.nexcess.com` | The address of the Herald instance. Pass another one to test against a staging Herald. HTTPS, or plain HTTP for `localhost`. An empty value is refused. | +| `herald-url` | yes | | The address of the Herald instance to publish to. HTTPS, or plain HTTP for `localhost`. | | `product` | yes | | The slug of the product in Herald. | | `version` | yes | | The version being released: three or four numeric parts. | | `zip` | yes | | The build to upload, a `.zip` path relative to the checkout. | diff --git a/.github/actions/herald-publish/action.yml b/.github/actions/herald-publish/action.yml index cc2f6fd3..ccd1d447 100644 --- a/.github/actions/herald-publish/action.yml +++ b/.github/actions/herald-publish/action.yml @@ -12,11 +12,10 @@ description: Uploads a plugin ZIP to Herald and publishes it as a version of a p inputs: herald-url: description: >- - The address of the Herald instance. The production Herald when left out; pass another address - to test against a staging one. HTTPS, since the API key goes in every request; plain HTTP is - accepted for `localhost` only. An empty value is refused rather than taken as production. - required: false - default: 'https://herald.nexcess.com' + The address of the Herald instance to publish to, e.g. `https://herald.example.com`. There is + no default: the caller names it. HTTPS, since the API key goes in every request; plain HTTP is + accepted for `localhost` only. + required: true product: description: 'The slug of the product in Herald, as its Products page shows it.' required: true diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index 8d807745..d0e9cd42 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -78,7 +78,8 @@ function validateVersion(version) { } /** - * Reads the `herald-url` input: where Herald answers, with no path of its own to add. + * Reads the `herald-url` input: where Herald answers, with no path of its own to add. There is no + * default: the caller names the instance, so a run never reaches one nobody chose. * * @param {string} url The input value. * @@ -91,9 +92,7 @@ function readUrl(url) { const trimmed = String(url ?? '').trim() if (trimmed === '') { - throw new Error( - `herald-url is empty: pass the address of the Herald instance, or leave the input out for the production one. ${NOTHING}` - ) + throw new Error(`No herald-url was given: pass the address of the Herald instance to publish to. ${NOTHING}`) } let parsed diff --git a/templates/workflows/release.yml b/templates/workflows/release.yml index beaeb510..93bfc72b 100644 --- a/templates/workflows/release.yml +++ b/templates/workflows/release.yml @@ -96,6 +96,7 @@ jobs: # - uses: stellarwp/plugin-toolbox/.github/actions/herald-publish@v1 # if: env.HERALD_CONFIGURED == 'true' && steps.merge.outputs.already-published == 'no' # with: + # herald-url: https://herald.example.com # product: my-plugin # version: ${{ inputs.version }} # zip: build/my-plugin.zip diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index 4d961ec0..0333c84c 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -248,7 +248,7 @@ describe('herald-publish', () => { }) it('refuses an empty address and one that is not a URL', () => { - assert.throws(() => readUrl(''), /herald-url is empty.*leave the input out for the production one/) + assert.throws(() => readUrl(''), /No herald-url was given: pass the address of the Herald instance to publish to/) assert.throws(() => readUrl('herald'), /is not a URL/) }) From 2dc249c838fdf343a3438a11e36941cefa071bed Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 12:01:23 -0300 Subject: [PATCH 11/45] herald-publish README: how to set Herald up for a repository or an organization The README said what the step needs and not how to get it. A new section gives the path: the product in Herald, the key of scope ci, the HERALD_API_KEY secret for an organization or for one repository, the step and the job's HERALD_CONFIGURED line, and how to try it against a staging Herald. SOFT-5788 --- .github/actions/herald-publish/README.md | 43 +++++++++++++++++------- 1 file changed, 31 insertions(+), 12 deletions(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index b365e99f..f0aa6b8a 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -43,18 +43,37 @@ deploy the action runs after the build and before workflow says where the release goes. `product` is the slug of the product in Herald, which is not always the repository's name. The product has to exist: the action creates versions, never products. -The step runs only where the key exists. A step's `if` cannot read a secret, so the job says whether -there is one: - -```yaml -jobs: - release: - env: - HERALD_CONFIGURED: ${{ secrets.HERALD_API_KEY != '' }} -``` - -The key is meant to be an organization secret, created once and made available to the repositories -that release to Herald. A repository the secret does not reach skips the step and deploys as before. +## Setting it up + +Herald is set up once, and then each workflow gets the step. An administrator of the Herald instance +does steps 1 and 2: other roles there are read-only and do not see API Keys. + +1. **The product exists in Herald.** On the Products page, check the slug under the product's name, + or create the product. That slug is the `product` input. +2. **Create a key of scope `ci`.** In Herald, open API Keys, click New API Key and choose the CI + scope. Copy the key: Herald shows it once. +3. **Store the key as the `HERALD_API_KEY` secret.** + - For every repository of an organization, which is how a production key is meant to be kept: an + organization owner creates it under the organization's Settings → Secrets and variables → + Actions → New organization secret, and chooses the repositories that release to Herald. Or: + `gh secret set HERALD_API_KEY --org --visibility selected --repos ,`. + - For one repository, to try the step out: its Settings → Secrets and variables → Actions → New + repository secret. Or: `gh secret set HERALD_API_KEY -R /`. +4. **Add the step to the deploy workflow,** as in the example above, with `herald-url` and `product`. +5. **Say in the job whether the key exists.** A step's `if` cannot read a secret, so the job sets a + value the step's `if` reads: + + ```yaml + jobs: + release: + env: + HERALD_CONFIGURED: ${{ secrets.HERALD_API_KEY != '' }} + ``` + +A repository the secret does not reach skips the step and deploys as before. + +To try the step out before a real release, use a staging Herald: its address in `herald-url`, a key +created there, and a product made for the test. A key works only in the instance that created it. ## What it does From 48d2c1447db6b7572fc64ff861c159f977440bb5 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 12:30:28 -0300 Subject: [PATCH 12/45] herald-publish: say only what a failed write is known to have left in Herald Three error messages stated more than the action knew: - An upload that got no answer, or a server error, said that nothing was published. Herald may have stored the ZIP by then. Only a refusal (4xx) shows that a write was not applied, so any other failed write now says that what Herald holds is not known. - A refused update said that no version points at the ZIP. That is not known for a ZIP Herald already held: on a rerun with the same bytes, the version already points at it. - A refused update of a new version said "it is not draft" when draft was the status asked for. SOFT-5788 --- .github/actions/herald-publish/README.md | 5 +- .../actions/herald-publish/herald-publish.js | 21 +++-- .../herald-publish/herald-publish.test.js | 81 ++++++++++++++++++- 3 files changed, 95 insertions(+), 12 deletions(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index f0aa6b8a..5d1e8ebe 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -167,8 +167,9 @@ A run can be repeated after a late failure, for the same version: action goes on to the update. When a step fails, the error says what Herald holds at that point. That is nothing, the ZIP with no -version pointing at it, or a new version left as a draft. When Herald did not answer a write, or -answered with a server error, the error says that what Herald holds is not known. +version changed, or a new version left as a draft. Only a refusal from Herald (an HTTP 4xx) shows +that a write was not applied. When Herald did not answer a write, or answered with a server error, +the error says that what Herald holds is not known. Skip the step for a version whose GitHub release already exists, as the example at the top does with release-merge's diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index d0e9cd42..f8732687 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -26,7 +26,7 @@ const zlib = require('node:zlib') const { STELLARWP_VERSION_PATTERN } = require('../../lib/versions.js') -/** Closes every error message raised before the first write. */ +/** Closes every error message raised with nothing of this run written to Herald. */ const NOTHING = 'Nothing was published to Herald.' /** The states a Herald version can be in. Only a published version is served to customers. */ @@ -482,15 +482,16 @@ function failure(answer) { } /** - * Whether a failed write may have been applied all the same: Herald did not answer, or answered - * with a server error. A refusal (4xx) wrote nothing. + * Whether a failed write may have been applied all the same. Only a refusal (4xx) says that Herald + * wrote nothing. No answer, a server error, or an answer of a shape the action does not expect + * leaves it unknown. * * @param {{status: number}} answer What `send` returned. * * @returns {boolean} True when what Herald holds is not known. */ function unconfirmed(answer) { - return answer.status === 0 || answer.status >= 500 + return answer.status < 400 || answer.status >= 500 } /** @@ -505,7 +506,8 @@ function unconfirmed(answer) { * @param {string} options.apiKey The Herald key. * @param {object} options.zip What `readZip` returned. * - * @throws {Error} When the upload fails for any reason but a duplicate. + * @throws {Error} When the upload fails for any reason but a duplicate. A refused upload stored + * nothing; any other failure may have left the ZIP in Herald, and the error says so. * * @returns {Promise<{id: string, sha256: string, meta: object|null, reused: boolean}>} The ZIP * record. `sha256` is empty and `meta` null for a reused record. @@ -532,7 +534,9 @@ async function uploadZip({ fetch, base, apiKey, zip }) { return { id: duplicate[1], sha256: '', meta: null, reused: true } } - throw new Error(`Uploading ${zip.name} to Herald failed (${failure(answer)}). ${NOTHING}`) + const left = unconfirmed(answer) ? 'Herald may have stored the ZIP all the same. No version was changed.' : NOTHING + + throw new Error(`Uploading ${zip.name} to Herald failed (${failure(answer)}). ${left}`) } /** @@ -653,11 +657,12 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro }) if (answer.status !== 200) { - let left = `The version is as it was, and the ZIP ${uploaded.id} is in Herald with no version pointing at it.` + // A ZIP Herald already held may have a version pointing at it, this one included. + let left = `The version is as it was. The ZIP ${uploaded.id} is in Herald${uploaded.reused ? '' : ', with no version pointing at it'}.` if (unconfirmed(answer)) { left = `Herald did not confirm the update, so the version may or may not be ${status} with the ZIP ${uploaded.id}. Run it again: the version is updated, not created twice.` } else if (created) { - left = `The version was created as a draft with the ZIP ${uploaded.id}; it is not ${status}.` + left = `The version was created as a draft with the ZIP ${uploaded.id} and is still that draft: the update was not applied.` } throw new Error(`Updating ${product} ${version} in Herald failed (${failure(answer)}). ${left}`) diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index 0333c84c..03df286d 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -551,6 +551,45 @@ describe('herald-publish', () => { assert.deepStrictEqual(calls(requests), ['GET /api/v1/products/gift-aid/versions/2.2.2', 'POST /api/v1/zips/upload']) }) + it('does not say Herald holds nothing when the upload got no answer', async (t) => { + const { core } = await coreWithOutputs(t) + const recorded = heraldFetch([FRESH[1]]) + const fetch = (url, options = {}) => { + if (url === API.upload) { + throw new TypeError('fetch failed', { cause: new Error('socket hang up') }) + } + + return recorded.fetch(url, options) + } + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + (error) => { + assert.match(error.message, /Uploading give-gift-aid\.zip to Herald failed \(no answer: socket hang up\)/) + assert.match(error.message, /may have stored the ZIP all the same.*No version was changed/) + assert.doesNotMatch(error.message, /Nothing was published/) + + return true + } + ) + }) + + it('does not say Herald holds nothing when the upload answer names no ZIP', async (t) => { + const { core } = await coreWithOutputs(t) + const { fetch } = heraldFetch([FRESH[1], { method: 'POST', path: API.upload, status: 201, body: {} }]) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + (error) => { + assert.match(error.message, /Uploading give-gift-aid\.zip to Herald failed \(HTTP 201: \{\}\)/) + assert.match(error.message, /may have stored the ZIP all the same/) + assert.doesNotMatch(error.message, /Nothing was published/) + + return true + } + ) + }) + it('says so when Herald does not answer', async (t) => { const { core } = await coreWithOutputs(t) const fetch = async () => { @@ -655,7 +694,25 @@ describe('herald-publish', () => { await assert.rejects( runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), - /failed \(HTTP 400: changelog too long\)\. The version was created as a draft.*it is not published/ + /failed \(HTTP 400: changelog too long\)\. The version was created as a draft with the ZIP 11111111.* and is still that draft/ + ) + }) + + it('does not say a new draft is not a draft when Herald refuses the update', async (t) => { + const { core } = await coreWithOutputs(t) + const { fetch } = heraldFetch([ + ...FRESH.slice(0, 3), + { method: 'PATCH', path: API.version, status: 400, body: { error: 'changelog too long' } }, + ]) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv({ INPUT_STATUS: 'draft' }), fetch, cwd: checkoutWith(), now: NOW }), + (error) => { + assert.match(error.message, /The version was created as a draft with the ZIP 11111111.* and is still that draft: the update was not applied\.$/) + assert.doesNotMatch(error.message, /is not draft/) + + return true + } ) }) @@ -683,7 +740,27 @@ describe('herald-publish', () => { await assert.rejects( runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), - /failed \(HTTP 403: forbidden\)\. The version is as it was/ + /failed \(HTTP 403: forbidden\)\. The version is as it was.*ZIP 11111111.*with no version pointing at it/ + ) + }) + + it('does not say no version points at a ZIP Herald already held when the update is refused', async (t) => { + const { core } = await coreWithOutputs(t) + // The version already points at these bytes: a rerun whose build came out identical. + const { fetch } = heraldFetch([ + { method: 'POST', path: API.upload, status: 400, body: { error: `a ZIP with this content already exists (id: ${ZIP_ID})` } }, + { method: 'GET', path: API.version, body: { ...CREATED, status: 'published', changelog: '* Fix - One thing.' } }, + { method: 'PATCH', path: API.version, status: 403, body: { error: 'forbidden' } }, + ]) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + (error) => { + assert.match(error.message, /failed \(HTTP 403: forbidden\)\. The version is as it was.*ZIP 11111111/) + assert.doesNotMatch(error.message, /no version pointing at it/) + + return true + } ) }) }) From a813617b6dcb5ebdf14cc75c08d7c79cd3b853ee Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 12:30:37 -0300 Subject: [PATCH 13/45] herald-publish: correct the version another run created, like one of its own When another run created the version between the read and the create, the action went on to the update knowing nothing about that version. It left the changelog header and a missing release date for the other run to correct. If that run stopped before its own update, the version was published with the header in the changelog and with no date. The action now reads the version again after such a create and makes the same two corrections. A read that fails there does not stop the run: the update decides the outcome. SOFT-5788 --- .github/actions/herald-publish/README.md | 4 +-- .../actions/herald-publish/herald-publish.js | 12 +++++-- .../herald-publish/herald-publish.test.js | 32 +++++++++++++++++-- 3 files changed, 42 insertions(+), 6 deletions(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index 5d1e8ebe..28024979 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -163,8 +163,8 @@ A run can be repeated after a late failure, for the same version: created. - **The build came out identical.** Herald refuses bytes it already stores and names the record in the refusal. The action takes that id and goes on. -- **Another run created the version in between.** The create is refused as a duplicate, and the - action goes on to the update. +- **Another run created the version in between.** The create is refused as a duplicate. The action + reads the version the other run created and goes on to the update. When a step fails, the error says what Herald holds at that point. That is nothing, the ZIP with no version changed, or a new version left as a draft. Only a refusal from Herald (an HTTP 4xx) shows diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index f8732687..9dbd6032 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -611,8 +611,8 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro core.warning(`The version inside ${zip.name} could not be read, so it was not compared with ${version}.`) } - // What Herald holds for the version: read above, or answered by the create below. Null when - // another run created it in between, and nothing is known about it. + // What Herald holds for the version: read above, answered by the create below, or read again + // after another run created it. Null only when that last read fails. let current = found.status === 200 ? found.data : null let created = false if (found.status === 404) { @@ -631,6 +631,14 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro created = answer.status === 201 current = created ? answer.data : null + + // The other run may stop before its own update, so this one reads what was created and makes + // the same corrections to the changelog and the release date. The update decides the outcome + // either way, so a read that fails here does not stop the run. + if (raced) { + const again = await send({ fetch, url: versionUrl, apiKey }) + current = again.status === 200 ? again.data : null + } } // The changelog field takes entries only. Without a file, the header Herald wrote above the diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index 03df286d..66639cfd 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -413,7 +413,35 @@ describe('herald-publish', () => { assert.deepStrictEqual(requests[3].body, { zip_id: ZIP_ID, status: 'published' }) }) - it('goes on to the update when another run created the version first', async (t) => { + it('reads the version another run created first, and corrects it like one of its own', async (t) => { + const { core, outputs } = await coreWithOutputs(t) + const missing = { status: 404, body: { error: "version '2.2.2' not found" } } + const { fetch, requests } = heraldFetch([ + FRESH[0], + { method: 'GET', path: API.version, responses: [missing, { body: { ...CREATED, release_date: null } }] }, + { method: 'POST', path: API.versions, status: 400, body: { error: 'this version already exists for the product' } }, + FRESH[3], + ]) + + await runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }) + + assert.deepStrictEqual(calls(requests), [ + 'GET /api/v1/products/gift-aid/versions/2.2.2', + 'POST /api/v1/zips/upload', + 'POST /api/v1/products/gift-aid/versions', + 'GET /api/v1/products/gift-aid/versions/2.2.2', + 'PATCH /api/v1/products/gift-aid/versions/2.2.2', + ]) + assert.deepStrictEqual(requests[4].body, { + zip_id: ZIP_ID, + status: 'published', + changelog: '* Fix - One thing.\n* New - Another thing.', + release_date: '2026-11-30T00:00:00Z', + }) + assert.strictEqual(outputs().created, 'false') + }) + + it('goes on to the update when the version another run created cannot be read', async (t) => { const { core, outputs } = await coreWithOutputs(t) const { fetch, requests } = heraldFetch([ FRESH[0], @@ -424,7 +452,7 @@ describe('herald-publish', () => { await runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }) - assert.strictEqual(calls(requests).at(-1), 'PATCH /api/v1/products/gift-aid/versions/2.2.2') + assert.deepStrictEqual(requests.at(-1).body, { zip_id: ZIP_ID, status: 'published' }) assert.strictEqual(outputs().created, 'false') }) }) From 293af65c8f4444a5a6f1a8540ddf35260d450a94 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 12:30:46 -0300 Subject: [PATCH 14/45] herald-publish: decide by the lines removed whether a changelog had a header entriesOnly compared the text without its headers with the text it was given, to tell whether there was a header to take out. Two changelogs came out wrong: - One with Windows line endings and no header differed from itself once its lines were joined again. The action sent it back to Herald and logged that it took a header out. - One with nothing but the header was left as it was, so the header stayed in a field that takes entries only. It is now left empty, as Herald leaves the changelog of a version with no entry in the ZIP. A header is still a line that starts and ends with "=", the lines Herald's own changelog check skips. SOFT-5788 --- .github/actions/herald-publish/README.md | 5 +++-- .../actions/herald-publish/herald-publish.js | 19 +++++++++---------- .../herald-publish/herald-publish.test.js | 17 +++++++++++++++-- 3 files changed, 27 insertions(+), 14 deletions(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index 28024979..c035a49c 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -106,10 +106,11 @@ ZIP. The action sends neither when it creates the version, and then makes two co - **The changelog.** Herald writes the entry with a header line above it, such as `= 4.17.0 | 2026-11-25 =`. The changelog field takes entries only, and a header in it can break the - page the changelog appears on. The action takes the header line out and keeps the entries. + page the changelog appears on. The action takes the header line out and keeps the entries. An + entry with nothing under its header leaves the changelog empty. - **The release date.** A version Herald found no date for gets today's date in UTC. -A version that already has entries only, or already has a date, is left as it is. +A changelog with no header line, and a version that already has a date, are left as they are. To send another changelog, pass `changelog-file`: a file with the entries of this version, one per line, with no version and no date. The action refuses a file with a line that is not an entry. diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index 9dbd6032..c3ccad6e 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -368,28 +368,27 @@ function readZipVersion(zip) { } /** - * Takes the version headers out of a changelog Herald filled from the ZIP's readme.txt. + * Takes the version headers out of a changelog Herald filled from the ZIP. * * Herald writes the entry it found as `= 4.17.0 | 2026-11-25 =` followed by the entries. The * changelog field takes entries only, so the header line goes and the entries stay as they are. + * A header is a line that starts and ends with `=`, the lines Herald's own changelog check does + * not count as entries. * * @param {*} changelog The changelog of the version, as Herald answered it. * - * @returns {string|null} The changelog without header lines, or null when there is nothing to - * change: no changelog, no header in it, or nothing but headers. + * @returns {string|null} The changelog without header lines, empty when it held nothing else. Null + * when there is nothing to change: no changelog, or no header in it. */ function entriesOnly(changelog) { if (typeof changelog !== 'string' || changelog.trim() === '') { return null } - const kept = changelog - .split(/\r?\n/) - .filter((line) => !/^=.*=$/.test(line.trim())) - .join('\n') - .trim() + const lines = changelog.split(/\r?\n/) + const kept = lines.filter((line) => !/^=.*=$/.test(line.trim())) - return kept === '' || kept === changelog.trim() ? null : kept + return kept.length === lines.length ? null : kept.join('\n').trim() } /** @@ -642,7 +641,7 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro } // The changelog field takes entries only. Without a file, the header Herald wrote above the - // entries it read from the ZIP goes; a changelog that holds entries only is left alone. + // entries it read from the ZIP goes; a changelog with no header is left alone. const entries = changelog ?? entriesOnly(current?.changelog) if (changelog === null && entries !== null) { core.info('Took the version header out of the changelog Herald read from the ZIP.') diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index 66639cfd..cd9163b4 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -295,13 +295,17 @@ describe('herald-publish', () => { assert.strictEqual(entriesOnly('= 2.2.2 =\n\n* Fix - One thing.'), '* Fix - One thing.') }) - it('has nothing to change in a changelog with no header, with headers only, or with no text', () => { + it('has nothing to change in a changelog with no header or with no text', () => { assert.strictEqual(entriesOnly('* Fix - One thing.'), null) - assert.strictEqual(entriesOnly('= 2.2.2 | 2026-11-25 ='), null) + assert.strictEqual(entriesOnly('* Fix - One thing.\r\n* New - Another thing.\r\n'), null) assert.strictEqual(entriesOnly(''), null) assert.strictEqual(entriesOnly(undefined), null) }) + it('leaves a changelog with nothing but the header empty', () => { + assert.strictEqual(entriesOnly('= 2.2.2 | 2026-11-25 ='), '') + }) + it('reads the version in the plugin header of a zip, compressed or stored', () => { assert.deepStrictEqual(readZipVersion(pluginZip('2.2.2')), { file: 'give-gift-aid/give-gift-aid.php', version: '2.2.2' }) @@ -413,6 +417,15 @@ describe('herald-publish', () => { assert.deepStrictEqual(requests[3].body, { zip_id: ZIP_ID, status: 'published' }) }) + it('empties a changelog that holds nothing but the header', async (t) => { + const { core } = await coreWithOutputs(t) + const { fetch, requests } = heraldFetch(freshWith({ changelog: '= 2.2.2 | 2026-11-25 =' })) + + await runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }) + + assert.deepStrictEqual(requests[3].body, { zip_id: ZIP_ID, status: 'published', changelog: '' }) + }) + it('reads the version another run created first, and corrects it like one of its own', async (t) => { const { core, outputs } = await coreWithOutputs(t) const missing = { status: 404, body: { error: "version '2.2.2' not found" } } From 5bc96eb49941030e49891bdb40897872b587fea8 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 12:30:54 -0300 Subject: [PATCH 15/45] herald-publish docs: Herald reads changelog.txt before readme.txt, and which role sets it up The README, the manifest and the comments said that Herald fills the changelog and the release date from the readme.txt in the ZIP. Herald reads the entry in a changelog.txt at the top of the ZIP when there is one, and in readme.txt otherwise. Setting it up said that every role but the administrator is read-only in Herald. Contributors create products and editors publish. Only the API Keys page is for administrators alone. SOFT-5788 --- .github/actions/herald-publish/README.md | 10 ++++++---- .github/actions/herald-publish/action.yml | 4 ++-- .github/actions/herald-publish/herald-publish.js | 8 +++++--- tests/actions/herald-publish/herald-publish.test.js | 3 ++- 4 files changed, 15 insertions(+), 10 deletions(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index c035a49c..066fc824 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -45,8 +45,9 @@ always the repository's name. The product has to exist: the action creates versi ## Setting it up -Herald is set up once, and then each workflow gets the step. An administrator of the Herald instance -does steps 1 and 2: other roles there are read-only and do not see API Keys. +Herald is set up once, and then each workflow gets the step. Step 2 needs an administrator of the +Herald instance, the only role that sees API Keys. Creating a product in step 1 needs the +contributor role or above. 1. **The product exists in Herald.** On the Products page, check the slug under the product's name, or create the product. That slug is the `product` input. @@ -101,8 +102,9 @@ warning. ## The changelog and the release date -Herald fills both for a new version, from the entry of that version in the `readme.txt` inside the -ZIP. The action sends neither when it creates the version, and then makes two corrections: +Herald fills both for a new version, from the entry of that version in the ZIP. It reads the entry +in `changelog.txt` when the ZIP has one, and in the Changelog section of `readme.txt` otherwise. The +action sends neither when it creates the version, and then makes two corrections: - **The changelog.** Herald writes the entry with a header line above it, such as `= 4.17.0 | 2026-11-25 =`. The changelog field takes entries only, and a header in it can break the diff --git a/.github/actions/herald-publish/action.yml b/.github/actions/herald-publish/action.yml index ccd1d447..5c906ecb 100644 --- a/.github/actions/herald-publish/action.yml +++ b/.github/actions/herald-publish/action.yml @@ -38,8 +38,8 @@ inputs: description: >- A file in the checkout with the changelog entries of this version, one per line, each starting with `* `. No version and no date: Herald shows the field as it is. When empty, the version - keeps the entries Herald read from the readme.txt in the ZIP, without the header line Herald - writes above them. + keeps the entries Herald read from the ZIP (its changelog.txt, or its readme.txt when it has + none), without the header line Herald writes above them. required: false default: '' api-key: diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index c3ccad6e..07131e4b 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -10,8 +10,9 @@ * after the build and before release-publish, so a failed upload leaves no GitHub release behind. * * Herald fills the changelog and the release date of a new version from the entry of that version - * in the ZIP's readme.txt. The action keeps both, takes the version header out of the changelog, - * and gives today's date to a version Herald found none for. + * in the ZIP: in its changelog.txt when it has one, in its readme.txt otherwise. The action keeps + * both, takes the version header out of the changelog, and gives today's date to a version Herald + * found none for. * * Running it again for the same version is safe: the version is updated, never created twice, and a * ZIP Herald already holds is reused. @@ -616,7 +617,8 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro let created = false if (found.status === 404) { // Only the version and the ZIP: Herald fills the changelog and the release date from the entry - // of this version in the ZIP's readme.txt, and a date sent here would replace the readme's. + // of this version in the ZIP's changelog.txt or readme.txt, and a date sent here would replace + // that one. const answer = await send({ fetch, url: versions, method: 'POST', apiKey, json: { version, zip_id: uploaded.id } }) // Two runs for one version: the other created it between the read and this call. diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index cd9163b4..2750a9da 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -45,7 +45,8 @@ const ZIP_RECORD = { /** * The version Herald answers a create with. It fills the changelog and the release date from the - * entry of that version in the ZIP's readme.txt, and the changelog comes with a header line. + * entry of that version in the ZIP's changelog.txt or readme.txt, and the changelog comes with a + * header line. */ const CREATED = { version: '2.2.2', From a31d75f03255bf84bdf7210c6a5058fe66afba5c Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 12:31:03 -0300 Subject: [PATCH 16/45] herald-publish tests: zips as other tools write them, the timeout and the masked key The zip reader was tested with one shape of zip. It now reads one with an archive comment (git archive writes the commit there) and one whose sizes come after the data (a zip written to a stream), and gives no version for a zip64 archive. The plugin's zip also holds a .php beside the main file, with a Version line and no Plugin Name, which the reader has to pass over. No test failed when the request timeout or the mask on the API key was taken out of the action. The main case now checks both. SOFT-5788 --- .../herald-publish/herald-publish.test.js | 78 +++++++++++++++---- 1 file changed, 65 insertions(+), 13 deletions(-) diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index 2750a9da..aea15a94 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -91,12 +91,16 @@ function publishEnv(overrides = {}) { * Builds a zip in memory, as `zip` writes it: a local header and the data per file, then the * central directory and its end record. * - * @param {object} files File contents by path inside the zip. - * @param {boolean} deflate Whether the files are compressed (method 8) or stored (method 0). + * @param {object} files File contents by path inside the zip. + * @param {object} options + * @param {boolean} options.deflate Whether the files are compressed (method 8) or stored (method 0). + * @param {boolean} options.descriptors Whether the sizes come after the data, as a tool that writes + * to a stream leaves them: the local header holds zeros. + * @param {string} options.comment The archive comment, written after the end record. * * @returns {Buffer} The zip. */ -function zipOf(files, deflate = true) { +function zipOf(files, { deflate = true, descriptors = false, comment = '' } = {}) { const locals = [] const directory = [] let offset = 0 @@ -108,14 +112,24 @@ function zipOf(files, deflate = true) { const local = Buffer.alloc(30) local.writeUInt32LE(0x04034b50, 0) + local.writeUInt16LE(descriptors ? 8 : 0, 6) local.writeUInt16LE(deflate ? 8 : 0, 8) - local.writeUInt32LE(data.length, 18) - local.writeUInt32LE(raw.length, 22) + local.writeUInt32LE(descriptors ? 0 : data.length, 18) + local.writeUInt32LE(descriptors ? 0 : raw.length, 22) local.writeUInt16LE(file.length, 26) locals.push(local, file, data) + const descriptor = Buffer.alloc(descriptors ? 16 : 0) + if (descriptors) { + descriptor.writeUInt32LE(0x08074b50, 0) + descriptor.writeUInt32LE(data.length, 8) + descriptor.writeUInt32LE(raw.length, 12) + locals.push(descriptor) + } + const entry = Buffer.alloc(46) entry.writeUInt32LE(0x02014b50, 0) + entry.writeUInt16LE(descriptors ? 8 : 0, 8) entry.writeUInt16LE(deflate ? 8 : 0, 10) entry.writeUInt32LE(data.length, 20) entry.writeUInt32LE(raw.length, 24) @@ -123,33 +137,48 @@ function zipOf(files, deflate = true) { entry.writeUInt32LE(offset, 42) directory.push(entry, file) - offset += 30 + file.length + data.length + offset += 30 + file.length + data.length + descriptor.length } const central = Buffer.concat(directory) + const note = Buffer.from(comment) const end = Buffer.alloc(22) end.writeUInt32LE(0x06054b50, 0) end.writeUInt16LE(Object.keys(files).length, 8) end.writeUInt16LE(Object.keys(files).length, 10) end.writeUInt32LE(central.length, 12) end.writeUInt32LE(offset, 16) + end.writeUInt16LE(note.length, 20) - return Buffer.concat([...locals, central, end]) + return Buffer.concat([...locals, central, end, note]) } /** - * The zip of the plugin at a version: a readme, an include, and the main file with its header. + * The files of the plugin at a version: a readme, a `.php` beside the main file and one in a + * folder, neither of them the plugin's, and the main file with its header. * * @param {string} version The version in the plugin header. * - * @returns {Buffer} The zip. + * @returns {object} File contents by path inside the zip. */ -function pluginZip(version = '2.2.2') { - return zipOf({ +function pluginFiles(version = '2.2.2') { + return { 'give-gift-aid/readme.txt': `=== Gift Aid ===\nStable tag: ${version}\n`, 'give-gift-aid/includes/version.php': " { it('reads the version in the plugin header of a zip, compressed or stored', () => { assert.deepStrictEqual(readZipVersion(pluginZip('2.2.2')), { file: 'give-gift-aid/give-gift-aid.php', version: '2.2.2' }) - const stored = zipOf({ 'my-plugin/my-plugin.php': ' { + const commented = zipOf(pluginFiles('2.2.2'), { comment: '3870a4f0d1c2b3a4958677665544332211009988' }) + + assert.deepStrictEqual(readZipVersion(commented), { file: 'give-gift-aid/give-gift-aid.php', version: '2.2.2' }) + }) + + it('reads the version of a zip whose sizes come after the data, as a streamed zip has them', () => { + const streamed = zipOf(pluginFiles('2.2.2'), { descriptors: true }) + + assert.deepStrictEqual(readZipVersion(streamed), { file: 'give-gift-aid/give-gift-aid.php', version: '2.2.2' }) + }) + + it('reads no version from a zip64 archive', () => { + const zip64 = pluginZip('2.2.2') + // What `zip -fz` writes: the offset of the directory is in another record, and this marker + // takes its place in the end record. + zip64.writeUInt32LE(0xffffffff, zip64.length - 22 + 16) + + assert.strictEqual(readZipVersion(zip64), null) + }) + it('reads the version of a theme from its style.css', () => { const theme = zipOf({ 'my-theme/functions.php': ' { }) assert.ok(sent.every((options) => options.headers.authorization === 'Bearer herald-ci-key')) assert.ok(sent.every((options) => options.redirect === 'error')) + assert.ok(sent.every((options) => options.signal instanceof AbortSignal)) assert.deepStrictEqual(outputs(), { 'zip-id': ZIP_ID, sha256: SHA256, status: 'published', created: 'true', 'versions-url': VERSIONS_URL }) assert.match(summary(), /`gift-aid` 2\.2\.2 is published, created with the ZIP.*: https:\/\/herald\.test\/admin\/products\/gift-aid\/versions/) assert.match(logged(), /gift-aid 2\.2\.2 is published in Herald with the ZIP 11111111.*: https:\/\/herald\.test\/admin\/products\/gift-aid\/versions/) assert.match(logged(), /Uploaded give-gift-aid\.zip as 11111111/) assert.match(logged(), /Took the version header out of the changelog/) assert.match(logged(), /Publishing gift-aid 2\.2\.2 to https:\/\/herald\.test/) + assert.match(logged(), /::add-mask::herald-ci-key/) }) it('sends the changelog file instead of what Herald read from the ZIP', async (t) => { From 09cdfd786a29480df09bd981bdfd98f0ecedb4d8 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 13:06:51 -0300 Subject: [PATCH 17/45] herald-publish: show the whole answer when its error is not text Herald's error is always text. A gateway in front of it can answer with an object under the same key, and the failure then read "HTTP 502: [object Object]". The reason is now the body as it came whenever the error is not text. SOFT-5788 --- .github/actions/herald-publish/herald-publish.js | 6 +++++- tests/actions/herald-publish/herald-publish.test.js | 11 +++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index 07131e4b..18c91c99 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -467,7 +467,11 @@ async function send({ fetch, url, method = 'GET', apiKey, json, form, timeout = data = null } - return { status: response.status, data, reason: String(data?.error ?? text).slice(0, 300) } + // Herald's `error` is text. An answer from something in front of it may carry an object there, + // and then the body as it came says more than `[object Object]`. + const reason = typeof data?.error === 'string' ? data.error : text + + return { status: response.status, data, reason: reason.slice(0, 300) } } /** diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index aea15a94..1a78b953 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -707,6 +707,17 @@ describe('herald-publish', () => { assert.strictEqual(requests.length, 1) }) + it('shows the whole answer when its error is not text', async (t) => { + const { core } = await coreWithOutputs(t) + // The shape a gateway in front of Herald answers with; Herald's own `error` is always text. + const { fetch } = heraldFetch([{ method: 'GET', path: API.version, status: 502, body: { error: { code: 502, message: 'Bad Gateway' } } }]) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + /Reading gift-aid 2\.2\.2 in Herald failed \(HTTP 502: \{"error":\{"code":502,"message":"Bad Gateway"\}\}\)/ + ) + }) + it('does not say the version is missing when the create got no answer', async (t) => { const { core } = await coreWithOutputs(t) const recorded = heraldFetch(FRESH.slice(0, 2)) From 3dd41a826c56565fd3662d9d2880b43448261d56 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 13:06:51 -0300 Subject: [PATCH 18/45] herald-publish: readZip gives the name and the bytes, and no other field readZip also returned the file's path and size, which nothing read. The choice between a stored and a deflated file was a ternary inside another. A method the reader does not take now returns before the read, and the ternary that is left has two sides. The tests now compare the bytes readZip returns and the bytes the upload sends with the zip in the checkout, and read no version from a main file under another compression method. SOFT-5788 --- .../actions/herald-publish/herald-publish.js | 14 ++++++++----- .../herald-publish/herald-publish.test.js | 21 ++++++++++++++----- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index 18c91c99..107b8d7d 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -171,8 +171,7 @@ function readStatus(status) { * * @throws {Error} When it is empty, not a `.zip`, not a file, or an empty file. * - * @returns {{name: string, file: string, size: number, data: Buffer}} The file's name, its path, its - * size and its bytes. + * @returns {{name: string, data: Buffer}} The file's name and its bytes. */ function readZip(zip, cwd) { const trimmed = String(zip ?? '').trim() @@ -201,7 +200,7 @@ function readZip(zip, cwd) { throw new Error(`zip '${trimmed}' is empty. ${NOTHING}`) } - return { name: path.basename(file), file, size: stat.size, data: fs.readFileSync(file) } + return { name: path.basename(file), data: fs.readFileSync(file) } } /** @@ -319,10 +318,15 @@ function zipFileStart(zip, entry) { const start = at + 30 + zip.readUInt16LE(at + 26) + zip.readUInt16LE(at + 28) const data = zip.subarray(start, start + entry.size) + // Stored (0) and deflated (8) are the two methods this reads. + if (entry.method !== 0 && entry.method !== 8) { + return null + } + try { - const file = entry.method === 0 ? data : entry.method === 8 ? zlib.inflateRawSync(data, { maxOutputLength: MAIN_FILE_LIMIT }) : null + const file = entry.method === 0 ? data : zlib.inflateRawSync(data, { maxOutputLength: MAIN_FILE_LIMIT }) - return file === null ? null : file.subarray(0, HEADER_BYTES).toString('utf8') + return file.subarray(0, HEADER_BYTES).toString('utf8') } catch { return null } diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index 1a78b953..ca13fbcb 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -97,10 +97,12 @@ function publishEnv(overrides = {}) { * @param {boolean} options.descriptors Whether the sizes come after the data, as a tool that writes * to a stream leaves them: the local header holds zeros. * @param {string} options.comment The archive comment, written after the end record. + * @param {number} options.method The compression method the headers name, when it is not the + * one the data was written with. * * @returns {Buffer} The zip. */ -function zipOf(files, { deflate = true, descriptors = false, comment = '' } = {}) { +function zipOf(files, { deflate = true, descriptors = false, comment = '', method = deflate ? 8 : 0 } = {}) { const locals = [] const directory = [] let offset = 0 @@ -113,7 +115,7 @@ function zipOf(files, { deflate = true, descriptors = false, comment = '' } = {} const local = Buffer.alloc(30) local.writeUInt32LE(0x04034b50, 0) local.writeUInt16LE(descriptors ? 8 : 0, 6) - local.writeUInt16LE(deflate ? 8 : 0, 8) + local.writeUInt16LE(method, 8) local.writeUInt32LE(descriptors ? 0 : data.length, 18) local.writeUInt32LE(descriptors ? 0 : raw.length, 22) local.writeUInt16LE(file.length, 26) @@ -130,7 +132,7 @@ function zipOf(files, { deflate = true, descriptors = false, comment = '' } = {} const entry = Buffer.alloc(46) entry.writeUInt32LE(0x02014b50, 0) entry.writeUInt16LE(descriptors ? 8 : 0, 8) - entry.writeUInt16LE(deflate ? 8 : 0, 10) + entry.writeUInt16LE(method, 10) entry.writeUInt32LE(data.length, 20) entry.writeUInt32LE(raw.length, 24) entry.writeUInt16LE(file.length, 28) @@ -295,10 +297,10 @@ describe('herald-publish', () => { assert.throws(() => readStatus('live'), /is not one of draft, review, published/) }) - it('refuses a zip that is missing, empty or not a .zip', () => { + it('reads the name and the bytes of the zip, and refuses one that is missing, empty or not a .zip', () => { const cwd = checkoutWith({ 'empty.zip': '', 'build.tar': 'x' }) - assert.strictEqual(readZip('give-gift-aid.zip', cwd).name, 'give-gift-aid.zip') + assert.deepStrictEqual(readZip('give-gift-aid.zip', cwd), { name: 'give-gift-aid.zip', data: pluginZip() }) assert.throws(() => readZip('', cwd), /No zip was given/) assert.throws(() => readZip('build.tar', cwd), /is not a \.zip file/) assert.throws(() => readZip('missing.zip', cwd), /is not a file in the checkout/) @@ -376,6 +378,14 @@ describe('herald-publish', () => { assert.strictEqual(readZipVersion(zipOf({ 'my-plugin/includes/deep.php': ' { + // The bytes are the file as it is, under the method number of bzip2: reading them as stored + // would find the header. + const bzip2 = zipOf({ 'my-plugin/my-plugin.php': ' { assert.throws(() => validateVersion('2.2.2-rc.1'), /is not a version Herald gets from this action.*Nothing was published to Herald/) assert.throws(() => validateVersion(''), /No version was given/) @@ -414,6 +424,7 @@ describe('herald-publish', () => { 'PATCH /api/v1/products/gift-aid/versions/2.2.2', ]) assert.strictEqual(requests[1].body.get('file').name, 'give-gift-aid.zip') + assert.deepStrictEqual(Buffer.from(await requests[1].body.get('file').arrayBuffer()), pluginZip()) assert.deepStrictEqual(requests[2].body, { version: '2.2.2', zip_id: ZIP_ID }) assert.deepStrictEqual(requests[3].body, { zip_id: ZIP_ID, From 8c0779dd5572502ab8d343e64628b88d73714920 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 13:06:51 -0300 Subject: [PATCH 19/45] release template: say that the Herald step goes after the build The header asks for the build between the checkout and release-publish, and the Herald step sits in that same place. A build pasted after it would leave the step with no ZIP to read. SOFT-5788 --- templates/workflows/release.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/templates/workflows/release.yml b/templates/workflows/release.yml index 93bfc72b..305f9d57 100644 --- a/templates/workflows/release.yml +++ b/templates/workflows/release.yml @@ -88,11 +88,11 @@ jobs: persist-credentials: false # For a product sold through Herald: upload the build and publish the version there before the - # GitHub release, so a failed upload leaves no release behind. The key is the HERALD_API_KEY - # secret, of the organization or of the environment above. The condition runs the step only - # where that secret exists, and skips the rerun of a version already published, which would - # replace a ZIP customers are downloading. It needs the HERALD_CONFIGURED line of the job's - # `env` above. + # GitHub release, so a failed upload leaves no release behind. The step goes after the one + # that builds the ZIP, which it reads from the checkout. The key is the HERALD_API_KEY secret, + # of the organization or of the environment above. The condition runs the step only where that + # secret exists, and skips the rerun of a version already published, which would replace a ZIP + # customers are downloading. It needs the HERALD_CONFIGURED line of the job's `env` above. # - uses: stellarwp/plugin-toolbox/.github/actions/herald-publish@v1 # if: env.HERALD_CONFIGURED == 'true' && steps.merge.outputs.already-published == 'no' # with: From c2d44df55335e93884617d264a399b9be74580d5 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 13:06:51 -0300 Subject: [PATCH 20/45] herald-publish docs: Herald reads a changelog.txt only when it has version headers The README said Herald reads the entry in changelog.txt when the ZIP has one. It does only when the file has headers such as "= 4.17.0 =". With any other format, such as the changelog.txt the Give add-ons build, Herald reads readme.txt. SOFT-5788 --- .github/actions/herald-publish/README.md | 5 +++-- .github/actions/herald-publish/action.yml | 4 ++-- .github/actions/herald-publish/herald-publish.js | 5 ++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index 066fc824..b1a3f1a0 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -103,8 +103,9 @@ warning. ## The changelog and the release date Herald fills both for a new version, from the entry of that version in the ZIP. It reads the entry -in `changelog.txt` when the ZIP has one, and in the Changelog section of `readme.txt` otherwise. The -action sends neither when it creates the version, and then makes two corrections: +in `changelog.txt` when the ZIP has one with version headers such as `= 4.17.0 =`, and in the +Changelog section of `readme.txt` otherwise. The action sends neither when it creates the version, +and then makes two corrections: - **The changelog.** Herald writes the entry with a header line above it, such as `= 4.17.0 | 2026-11-25 =`. The changelog field takes entries only, and a header in it can break the diff --git a/.github/actions/herald-publish/action.yml b/.github/actions/herald-publish/action.yml index 5c906ecb..95099125 100644 --- a/.github/actions/herald-publish/action.yml +++ b/.github/actions/herald-publish/action.yml @@ -38,8 +38,8 @@ inputs: description: >- A file in the checkout with the changelog entries of this version, one per line, each starting with `* `. No version and no date: Herald shows the field as it is. When empty, the version - keeps the entries Herald read from the ZIP (its changelog.txt, or its readme.txt when it has - none), without the header line Herald writes above them. + keeps the entries Herald read from the changelog.txt or the readme.txt in the ZIP, without the + header line Herald writes above them. required: false default: '' api-key: diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index 107b8d7d..eeee0d8f 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -10,9 +10,8 @@ * after the build and before release-publish, so a failed upload leaves no GitHub release behind. * * Herald fills the changelog and the release date of a new version from the entry of that version - * in the ZIP: in its changelog.txt when it has one, in its readme.txt otherwise. The action keeps - * both, takes the version header out of the changelog, and gives today's date to a version Herald - * found none for. + * in the ZIP's changelog.txt or readme.txt. The action keeps both, takes the version header out of + * the changelog, and gives today's date to a version Herald found none for. * * Running it again for the same version is safe: the version is updated, never created twice, and a * ZIP Herald already holds is reused. From 452e5fab5e015f050a569cb63b02a8fedd6a67a0 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 13:19:59 -0300 Subject: [PATCH 21/45] herald-publish: the product input is product-slug, and the README says where zip comes from The input took the slug of the product in Herald under the name product, which does not say whether it is the name, the id or the slug. Herald's own guide calls it the product slug. No release carries the old name: the callers pin a commit of this pull request. The README, the manifest and the template now say that zip is the file a build step wrote before this one, that the action builds nothing, and that build/my-plugin.zip in the example stands for wherever the build leaves it. A test compares the inputs the manifest declares with the ones the script reads, since a mismatch there only shows in a real run. SOFT-5788 --- .github/actions/herald-publish/README.md | 31 +++++++++++------ .github/actions/herald-publish/action.yml | 8 +++-- .../actions/herald-publish/herald-publish.js | 16 ++++----- templates/workflows/release.yml | 11 +++--- .../herald-publish/herald-publish.test.js | 34 ++++++++++++++----- 5 files changed, 65 insertions(+), 35 deletions(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index b1a3f1a0..47d34e23 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -20,13 +20,14 @@ deploy the action runs after the build and before with: ref: ${{ steps.merge.outputs.base-sha }} -# Build the plugin here, from the merged commit. +# Build the plugin here, from the merged commit. In this example the build writes +# build/my-plugin.zip. - uses: stellarwp/plugin-toolbox/.github/actions/herald-publish@v1 if: env.HERALD_CONFIGURED == 'true' && steps.merge.outputs.already-published == 'no' with: herald-url: https://herald.example.com - product: my-plugin + product-slug: my-plugin version: ${{ inputs.version }} zip: build/my-plugin.zip api-key: ${{ secrets.HERALD_API_KEY }} @@ -39,9 +40,16 @@ deploy the action runs after the build and before build/my-plugin.zip ``` -`herald-url` is the address of the Herald instance, and the action has no default for it: the -workflow says where the release goes. `product` is the slug of the product in Herald, which is not -always the repository's name. The product has to exist: the action creates versions, never products. +Three of the values are the workflow's own: + +- `herald-url` is the address of the Herald instance. The action has no default for it: the workflow + says where the release goes. +- `product-slug` is the slug of the product in Herald, which is not always the repository's name. + The product has to exist: the action creates versions, never products. +- `zip` is the file the build step wrote, as a path from the root of the checkout. The action builds + nothing and looks for no file, so the workflow names it. `build/my-plugin.zip` stands for wherever + the repository's build leaves its ZIP. It is the file release-publish gets in `files`, so Herald + and the GitHub release hold the same build. ## Setting it up @@ -50,7 +58,7 @@ Herald instance, the only role that sees API Keys. Creating a product in step 1 contributor role or above. 1. **The product exists in Herald.** On the Products page, check the slug under the product's name, - or create the product. That slug is the `product` input. + or create the product. That slug is the `product-slug` input. 2. **Create a key of scope `ci`.** In Herald, open API Keys, click New API Key and choose the CI scope. Copy the key: Herald shows it once. 3. **Store the key as the `HERALD_API_KEY` secret.** @@ -60,7 +68,8 @@ contributor role or above. `gh secret set HERALD_API_KEY --org --visibility selected --repos ,`. - For one repository, to try the step out: its Settings → Secrets and variables → Actions → New repository secret. Or: `gh secret set HERALD_API_KEY -R /`. -4. **Add the step to the deploy workflow,** as in the example above, with `herald-url` and `product`. +4. **Add the step to the deploy workflow,** as in the example above, with `herald-url`, + `product-slug` and `zip`. 5. **Say in the job whether the key exists.** A step's `if` cannot read a secret, so the job sets a value the step's `if` reads: @@ -81,10 +90,10 @@ created there, and a product made for the test. A key works only in the instance 1. Checks every input before any call. 2. Reads the version in the plugin header inside the ZIP and compares it with `version`. A ZIP of another version, or of another plugin on another version, stops here, before anything is sent. -3. Reads the version of the product (`GET /api/v1/products/{product}/versions/{version}`). A key +3. Reads the version of the product (`GET /api/v1/products/{product-slug}/versions/{version}`). A key Herald refuses and a product it does not have stop here too, with no ZIP left in Herald. 4. Uploads the ZIP (`POST /api/v1/zips/upload`). Herald stores it and computes its SHA-256. -5. Creates the version when it is missing (`POST /api/v1/products/{product}/versions`). A new +5. Creates the version when it is missing (`POST /api/v1/products/{product-slug}/versions`). A new version is a draft. 6. Updates the version in one call, a `PATCH` on the address of step 3. It sends the ZIP, the status and, when they need a change, the changelog and the release date. Herald writes them together, so @@ -142,9 +151,9 @@ own version instead of the entries. | Input | Required | Default | What it is | |---|---|---|---| | `herald-url` | yes | | The address of the Herald instance to publish to. HTTPS, or plain HTTP for `localhost`. | -| `product` | yes | | The slug of the product in Herald. | +| `product-slug` | yes | | The slug of the product in Herald. | | `version` | yes | | The version being released: three or four numeric parts. | -| `zip` | yes | | The build to upload, a `.zip` path relative to the checkout. | +| `zip` | yes | | The build to upload, a `.zip` path relative to the checkout. A step before this one builds it. | | `status` | no | `published` | `draft`, `review` or `published`. Only a published version is served to customers. | | `changelog-file` | no | | A file with the entries of this version. Empty keeps what Herald read from the ZIP, without the header. | | `api-key` | yes | | A Herald API key of scope `ci`, from a secret. | diff --git a/.github/actions/herald-publish/action.yml b/.github/actions/herald-publish/action.yml index 95099125..dc935eee 100644 --- a/.github/actions/herald-publish/action.yml +++ b/.github/actions/herald-publish/action.yml @@ -16,7 +16,7 @@ inputs: no default: the caller names it. HTTPS, since the API key goes in every request; plain HTTP is accepted for `localhost` only. required: true - product: + product-slug: description: 'The slug of the product in Herald, as its Products page shows it.' required: true version: @@ -26,7 +26,9 @@ inputs: plugin header holds another version is refused. required: true zip: - description: 'The build to upload: the path of a `.zip`, relative to the checkout.' + description: >- + The build to upload: the path of a `.zip`, relative to the checkout. A step before this one + builds it. The action builds nothing and looks for no file on its own. required: true status: description: >- @@ -78,7 +80,7 @@ runs: # Read from process.env rather than interpolated into the script, so an input is data and # never part of the program. INPUT_HERALD_URL: ${{ inputs.herald-url }} - INPUT_PRODUCT: ${{ inputs.product }} + INPUT_PRODUCT_SLUG: ${{ inputs.product-slug }} INPUT_VERSION: ${{ inputs.version }} INPUT_ZIP: ${{ inputs.zip }} INPUT_STATUS: ${{ inputs.status }} diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index eeee0d8f..e21ba1ca 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -115,23 +115,23 @@ function readUrl(url) { } /** - * Reads the `product` input: the slug of the product in Herald, as its Products page shows it. + * Reads the `product-slug` input: the slug of the product in Herald, as its Products page shows it. * - * @param {string} product The input value. + * @param {string} slug The input value. * * @throws {Error} When it is empty or holds whitespace or a URL delimiter. * * @returns {string} The slug, without surrounding whitespace. */ -function readProduct(product) { - const trimmed = String(product ?? '').trim() +function readProductSlug(slug) { + const trimmed = String(slug ?? '').trim() if (trimmed === '') { - throw new Error(`No product was given: pass the slug of the product in Herald. ${NOTHING}`) + throw new Error(`No product-slug was given: pass the slug of the product in Herald. ${NOTHING}`) } if (/[\s/\\?#]/.test(trimmed)) { - throw new Error(`product '${trimmed}' is not a Herald slug: it holds a space or one of / \\ ? #. ${NOTHING}`) + throw new Error(`product-slug '${trimmed}' is not a Herald slug: it holds a space or one of / \\ ? #. ${NOTHING}`) } return trimmed @@ -566,7 +566,7 @@ async function uploadZip({ fetch, base, apiKey, zip }) { async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = process.cwd(), now = new Date() }) { const version = validateVersion(env.INPUT_VERSION) const base = readUrl(env.INPUT_HERALD_URL) - const product = readProduct(env.INPUT_PRODUCT) + const product = readProductSlug(env.INPUT_PRODUCT_SLUG) const status = readStatus(env.INPUT_STATUS) const zip = readZip(env.INPUT_ZIP, cwd) const changelog = readChangelogFile(env.INPUT_CHANGELOG_FILE, cwd) @@ -714,7 +714,7 @@ module.exports = { runHeraldPublish, validateVersion, readUrl, - readProduct, + readProductSlug, readStatus, readZip, readChangelogFile, diff --git a/templates/workflows/release.yml b/templates/workflows/release.yml index 305f9d57..6afc0ef9 100644 --- a/templates/workflows/release.yml +++ b/templates/workflows/release.yml @@ -89,15 +89,16 @@ jobs: # For a product sold through Herald: upload the build and publish the version there before the # GitHub release, so a failed upload leaves no release behind. The step goes after the one - # that builds the ZIP, which it reads from the checkout. The key is the HERALD_API_KEY secret, - # of the organization or of the environment above. The condition runs the step only where that - # secret exists, and skips the rerun of a version already published, which would replace a ZIP - # customers are downloading. It needs the HERALD_CONFIGURED line of the job's `env` above. + # that builds the ZIP, and `zip` is the path of that file in the checkout, the same one + # release-publish gets in `files`. The key is the HERALD_API_KEY secret, of the organization + # or of the environment above. The condition runs the step only where that secret exists, and + # skips the rerun of a version already published, which would replace a ZIP customers are + # downloading. It needs the HERALD_CONFIGURED line of the job's `env` above. # - uses: stellarwp/plugin-toolbox/.github/actions/herald-publish@v1 # if: env.HERALD_CONFIGURED == 'true' && steps.merge.outputs.already-published == 'no' # with: # herald-url: https://herald.example.com - # product: my-plugin + # product-slug: my-plugin # version: ${{ inputs.version }} # zip: build/my-plugin.zip # api-key: ${{ secrets.HERALD_API_KEY }} diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index ca13fbcb..f37309f4 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -11,7 +11,7 @@ const { runHeraldPublish, validateVersion, readUrl, - readProduct, + readProductSlug, readStatus, readZip, readChangelogFile, @@ -77,7 +77,7 @@ const FRESH = [ function publishEnv(overrides = {}) { return { INPUT_HERALD_URL: BASE, - INPUT_PRODUCT: 'gift-aid', + INPUT_PRODUCT_SLUG: 'gift-aid', INPUT_VERSION: '2.2.2', INPUT_ZIP: 'give-gift-aid.zip', INPUT_STATUS: '', @@ -274,7 +274,7 @@ describe('herald-publish', () => { { method: 'PATCH', path: `${base}/2.2.2`, body: { version: '2.2.2', status: 'published', zip_id: ZIP_ID } }, ]) - await runHeraldPublish({ core, env: publishEnv({ INPUT_PRODUCT: product }), fetch, cwd: checkoutWith(), now: NOW }) + await runHeraldPublish({ core, env: publishEnv({ INPUT_PRODUCT_SLUG: product }), fetch, cwd: checkoutWith(), now: NOW }) assert.strictEqual(outputs()['versions-url'], `${BASE}/admin/products/gift%25aid/versions`) }) @@ -284,11 +284,29 @@ describe('herald-publish', () => { assert.throws(() => readUrl('herald'), /is not a URL/) }) - it('refuses a product that is not a slug', () => { - assert.strictEqual(readProduct(' gift-aid '), 'gift-aid') - assert.throws(() => readProduct(''), /No product was given/) - assert.throws(() => readProduct('gift-aid/versions'), /is not a Herald slug/) - assert.throws(() => readProduct('gift aid'), /is not a Herald slug/) + it('refuses a product slug that is empty or holds a space or a URL delimiter', () => { + assert.strictEqual(readProductSlug(' gift-aid '), 'gift-aid') + assert.throws(() => readProductSlug(''), /No product-slug was given: pass the slug of the product in Herald/) + assert.throws(() => readProductSlug('gift-aid/versions'), /product-slug 'gift-aid\/versions' is not a Herald slug/) + assert.throws(() => readProductSlug('gift aid'), /product-slug 'gift aid' is not a Herald slug/) + }) + + it('gets every input of the manifest under the name the script reads', () => { + const directory = path.join(__dirname, '../../../.github/actions/herald-publish') + const manifest = fs.readFileSync(path.join(directory, 'action.yml'), 'utf8') + const script = fs.readFileSync(path.join(directory, 'herald-publish.js'), 'utf8') + + const inputs = manifest.slice(manifest.indexOf('\ninputs:'), manifest.indexOf('\noutputs:')) + const declared = [...inputs.matchAll(/^ ([a-z-]+):$/gm)].map((match) => match[1]) + const handed = [...manifest.matchAll(/^ +(INPUT_[A-Z_]+): \$\{\{ inputs\.([a-z-]+) \}\}$/gm)].map((match) => [match[1], match[2]]) + const read = [...new Set([...script.matchAll(/env\.(INPUT_[A-Z_]+)/g)].map((match) => match[1]))] + + assert.ok(declared.includes('product-slug')) + assert.deepStrictEqual(handed.map(([, input]) => input).sort(), [...declared].sort()) + assert.deepStrictEqual(handed.map(([name]) => name).sort(), read.sort()) + for (const [name, input] of handed) { + assert.strictEqual(name, `INPUT_${input.toUpperCase().replaceAll('-', '_')}`) + } }) it('publishes by default and refuses a status Herald does not have', () => { From 4c0250535db97bb8c29d21165a77b53c8323fd35 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 13:25:14 -0300 Subject: [PATCH 22/45] herald-publish README: shorter paragraphs, and a link for each claim about Herald The README stated what Herald does (who sees API Keys, that a new version is a draft, that an update is written in one statement, where the changelog comes from) with nothing to check it against. Each of those now links the line of Herald or the page of its guide that shows it. It said a version header in the changelog field can break the page the changelog appears on, which no code here or in Herald shows. It now says what Herald does: its own check reports the header as an error. Paragraphs that held four or five sentences are split, the two ways to store the secret read as two labelled items, and the changelog file is said to hold lines that start with "* ", as the manifest already said. SOFT-5788 --- .github/actions/herald-publish/README.md | 121 +++++++++++++---------- 1 file changed, 71 insertions(+), 50 deletions(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index 47d34e23..c42cc3cd 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -5,8 +5,9 @@ download paid plugins from. It uploads the ZIP and creates the version when the have it yet. It then points the version at the ZIP and sets its status. It is what a person does by hand in the Herald dashboard for a paid release. They click New Version, -upload the ZIP, check the changelog and the release date, create the version and publish it. In a -deploy the action runs after the build and before +upload the ZIP, check the changelog and the release date, create the version and publish it. + +In a deploy, the action runs after the build and before [release-publish](../release-publish/README.md), so a failed upload leaves no GitHub release behind: ```yaml @@ -40,38 +41,42 @@ deploy the action runs after the build and before build/my-plugin.zip ``` -Three of the values are the workflow's own: +Each workflow sets three of these values for itself: - `herald-url` is the address of the Herald instance. The action has no default for it: the workflow says where the release goes. - `product-slug` is the slug of the product in Herald, which is not always the repository's name. The product has to exist: the action creates versions, never products. -- `zip` is the file the build step wrote, as a path from the root of the checkout. The action builds - nothing and looks for no file, so the workflow names it. `build/my-plugin.zip` stands for wherever - the repository's build leaves its ZIP. It is the file release-publish gets in `files`, so Herald - and the GitHub release hold the same build. +- `zip` is the path of the ZIP the build step wrote, from the root of the checkout. The action + builds nothing and looks for no file. `build/my-plugin.zip` is the path of this example: pass the + one your build writes, the same file release-publish gets in `files`. ## Setting it up -Herald is set up once, and then each workflow gets the step. Step 2 needs an administrator of the -Herald instance, the only role that sees API Keys. Creating a product in step 1 needs the -contributor role or above. +Herald is set up once, and then each workflow gets the step. 1. **The product exists in Herald.** On the Products page, check the slug under the product's name, - or create the product. That slug is the `product-slug` input. + or create the product. That slug is the `product-slug` input. Creating a product + [needs the contributor role](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/crates/herald-server/src/routes/products.rs#L118-L123) + or above. 2. **Create a key of scope `ci`.** In Herald, open API Keys, click New API Key and choose the CI - scope. Copy the key: Herald shows it once. + scope. Copy the key: Herald + [shows it once](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/docs/github-actions.md#1-create-a-ci-api-key). + Only an administrator of the Herald instance + [sees API Keys](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/dashboard/components/layout/sidebar.tsx#L51). 3. **Store the key as the `HERALD_API_KEY` secret.** - - For every repository of an organization, which is how a production key is meant to be kept: an - organization owner creates it under the organization's Settings → Secrets and variables → - Actions → New organization secret, and chooses the repositories that release to Herald. Or: + - **For an organization,** which is how a production key is meant to be kept. An organization + owner opens the organization's Settings → Secrets and variables → Actions → New organization + secret, and chooses the repositories that release to Herald. With the CLI: `gh secret set HERALD_API_KEY --org --visibility selected --repos ,`. - - For one repository, to try the step out: its Settings → Secrets and variables → Actions → New - repository secret. Or: `gh secret set HERALD_API_KEY -R /`. + - **For one repository,** to try the step out. Open its Settings → Secrets and variables → + Actions → New repository secret. With the CLI: + `gh secret set HERALD_API_KEY -R /`. 4. **Add the step to the deploy workflow,** as in the example above, with `herald-url`, `product-slug` and `zip`. -5. **Say in the job whether the key exists.** A step's `if` cannot read a secret, so the job sets a - value the step's `if` reads: +5. **Say in the job whether the key exists.** A step's `if` + [cannot read a secret](https://docs.github.com/en/actions/how-tos/write-workflows/choose-what-workflows-do/use-secrets#using-secrets-in-a-workflow), + so the job sets a value the step's `if` reads: ```yaml jobs: @@ -80,7 +85,7 @@ contributor role or above. HERALD_CONFIGURED: ${{ secrets.HERALD_API_KEY != '' }} ``` -A repository the secret does not reach skips the step and deploys as before. +A repository the secret does not reach skips the step, and the rest of the deploy runs. To try the step out before a real release, use a staging Herald: its address in `herald-url`, a key created there, and a product made for the test. A key works only in the instance that created it. @@ -94,38 +99,49 @@ created there, and a product made for the test. A key works only in the instance Herald refuses and a product it does not have stop here too, with no ZIP left in Herald. 4. Uploads the ZIP (`POST /api/v1/zips/upload`). Herald stores it and computes its SHA-256. 5. Creates the version when it is missing (`POST /api/v1/products/{product-slug}/versions`). A new - version is a draft. + version is + [always a draft](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/docs/github-actions.md#notes). 6. Updates the version in one call, a `PATCH` on the address of step 3. It sends the ZIP, the status - and, when they need a change, the changelog and the release date. Herald writes them together, so - a refused update never leaves the version published with the old ZIP. + and, when they need a change, the changelog and the release date. Herald + [writes them together](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/crates/herald-server/src/routes/versions.rs#L316-L334), + so a refused update never leaves the version published with the old ZIP. 7. Checks that Herald's answer shows the status and the ZIP it asked for, and fails when it does not. The run log and the job summary show the ZIP id, its SHA-256 and a link to the product's versions in the Herald dashboard. Herald has no page per version; that page lists them newest first. -The version of step 2 is read where WordPress finds it. That is a `.php` right inside the top folder -with a `Plugin Name` header, or the `style.css` of a theme. When the action cannot read it, the -check falls to what Herald read from the ZIP in step 4. When neither can, the run goes on with a -warning. +The version of step 2 is read where +[WordPress finds it](https://developer.wordpress.org/plugins/plugin-basics/header-requirements/). +That is a `.php` right inside the top folder with a `Plugin Name` header, or the `style.css` of a +theme. + +When the action cannot read that version, it compares the one Herald read from the ZIP in step 4. +When Herald read none either, the run goes on with a warning. ## The changelog and the release date -Herald fills both for a new version, from the entry of that version in the ZIP. It reads the entry -in `changelog.txt` when the ZIP has one with version headers such as `= 4.17.0 =`, and in the -Changelog section of `readme.txt` otherwise. The action sends neither when it creates the version, -and then makes two corrections: +Herald +[fills both](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/crates/herald-core/src/repo/versions.rs#L694-L718) +for a new version, from the entry of that version in the ZIP. It reads the entry in `changelog.txt` +when the ZIP has one with version headers such as `= 4.17.0 =`. Otherwise it reads +[the Changelog section of `readme.txt`](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/crates/herald-core/src/zip/meta.rs#L315-L320). + +The action sends neither when it creates the version, and then makes two corrections: -- **The changelog.** Herald writes the entry with a header line above it, such as - `= 4.17.0 | 2026-11-25 =`. The changelog field takes entries only, and a header in it can break the - page the changelog appears on. The action takes the header line out and keeps the entries. An - entry with nothing under its header leaves the changelog empty. +- **The changelog.** Herald + [writes the entry with a header line above it](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/crates/herald-core/src/zip/meta.rs#L665-L687), + such as `= 4.17.0 | 2026-11-25 =`. The changelog field takes entries only: Herald's own check + [reports a version header in it as an error](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/crates/herald-core/src/changelog/validate.rs#L72-L78). + The action takes the header line out and keeps the entries. An entry with nothing under its header + leaves the changelog empty. - **The release date.** A version Herald found no date for gets today's date in UTC. A changelog with no header line, and a version that already has a date, are left as they are. To send another changelog, pass `changelog-file`: a file with the entries of this version, one per -line, with no version and no date. The action refuses a file with a line that is not an entry. +line, each starting with `* `, with no version and no date. The action refuses a file with a line +that is not an entry. ```text * Fix - Resolved an error when the fee is disabled for the gateway. @@ -174,15 +190,17 @@ A run can be repeated after a late failure, for the same version: - **The version exists.** It is updated to point at the ZIP of this run. No second version is created. -- **The build came out identical.** Herald refuses bytes it already stores and names the record in - the refusal. The action takes that id and goes on. +- **The build came out identical.** Herald + [refuses bytes it already stores](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/crates/herald-server/src/routes/zip_upload.rs#L73-L79) + and names the record in the refusal. The action takes that id and goes on. - **Another run created the version in between.** The create is refused as a duplicate. The action reads the version the other run created and goes on to the update. When a step fails, the error says what Herald holds at that point. That is nothing, the ZIP with no -version changed, or a new version left as a draft. Only a refusal from Herald (an HTTP 4xx) shows -that a write was not applied. When Herald did not answer a write, or answered with a server error, -the error says that what Herald holds is not known. +version changed, or a new version left as a draft. + +Only a refusal from Herald (an HTTP 4xx) shows that a write was not applied. When Herald did not +answer a write, or answered with a server error, the error says that what Herald holds is not known. Skip the step for a version whose GitHub release already exists, as the example at the top does with release-merge's @@ -192,16 +210,17 @@ downloading. ## The key, and who can publish -The key is a Herald API key of scope `ci`. That scope can upload ZIPs and create, read and update -versions, and nothing else: it cannot delete a version or touch products, brands or other keys. -Herald's [GitHub Actions guide](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/docs/github-actions.md#1-create-a-ci-api-key) -says how to create one. +The key is a Herald API key of scope `ci`. That scope +[can upload ZIPs and create, read and update versions](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/docs/github-actions.md#what-ci-tokens-can-do), +and nothing else: it cannot delete a version or touch products, brands or other keys. With `status: published`, the version is live in Herald when the step ends, with no second click -there. So whoever can start the deploy can publish. On GitHub, starting a workflow by hand +there. So whoever can start the deploy can publish. + +On GitHub, starting a workflow by hand [needs write access to the repository](https://docs.github.com/en/actions/how-tos/manage-workflow-runs/manually-run-a-workflow). Keep that access to the people who release and to the app that dispatches for the release dashboard. -The review and the QA approval happen there, before the deploy. +The review and the QA approval happen in the release dashboard, before the deploy. How much more to add is each repository's choice: @@ -223,9 +242,11 @@ How much more to add is each repository's choice: ## How it runs The logic is in [`herald-publish.js`](./herald-publish.js), run by `actions/github-script`, with no -dependency to install. The calls use the runtime's `fetch`. A redirect is refused rather than -followed, since it would send the key to another address. The upload is given ten minutes and every -other call thirty seconds, so a request that hangs does not hold the deploy. +dependency to install. The calls use the runtime's `fetch`. + +A redirect is refused rather than followed, since it would send the key to another address. The +upload is given ten minutes and every other call thirty seconds, so a request that hangs does not +hold the deploy. Tests are in [`tests/actions/herald-publish`](../../../tests/actions/herald-publish/herald-publish.test.js), with From 4435824bbe666b1738a4a108d22c104d79ca8654 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 13:25:14 -0300 Subject: [PATCH 23/45] herald-publish: plainer words in three error messages, the comments and the test names "The API key would travel in the clear" is now "would be sent unencrypted", "all the same" is "anyway", and the version message names the action as what takes three or four parts. Two docblocks said a version header breaks the page the changelog is shown on. They now say what Herald's own check does with it. The example in failure() used an error Herald never sends. The template's comment on the Herald step is two paragraphs: where the step goes, then the key and the condition. SOFT-5788 --- .../actions/herald-publish/herald-publish.js | 22 ++++++++++--------- templates/workflows/release.yml | 10 +++++---- .../herald-publish/herald-publish.test.js | 18 +++++++-------- 3 files changed, 27 insertions(+), 23 deletions(-) diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index e21ba1ca..487590f5 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -69,7 +69,7 @@ function validateVersion(version) { if (!STELLARWP_VERSION_PATTERN.test(trimmed)) { throw new Error( - `'${trimmed}' is not a version Herald gets from this action. It takes three or four numeric parts, ` + + `'${trimmed}' is not a version Herald gets from this action. The action takes three or four numeric parts, ` + `such as 4.17.0 or 4.17.0.1, with no pre-release suffix and no leading v. ${NOTHING}` ) } @@ -104,7 +104,7 @@ function readUrl(url) { const local = ['localhost', '127.0.0.1'].includes(parsed.hostname) if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && local)) { - throw new Error(`herald-url '${trimmed}' is not HTTPS, and the API key would travel in the clear. ${NOTHING}`) + throw new Error(`herald-url '${trimmed}' is not HTTPS, so the API key would be sent unencrypted. ${NOTHING}`) } if (parsed.username !== '' || parsed.password !== '' || parsed.search !== '' || parsed.hash !== '') { @@ -205,8 +205,9 @@ function readZip(zip, cwd) { /** * Reads the `changelog-file` input: the entries of this version, one per line. * - * Herald's changelog field takes entries only, each starting with `* `. A version header, a date or - * a blank title breaks the page the changelog is shown on, so anything else is refused. + * Herald's changelog field takes entries only, and its own check reports a version header there as + * an error. The action takes the entries in the form Herald writes them, each starting with `* `, + * and refuses a file with any other line. * * @param {string} input The input value, a path relative to the checkout. * @param {string} cwd The checkout. @@ -336,8 +337,9 @@ function zipFileStart(zip, entry) { * a `.php` right inside the top folder with a `Plugin Name` header, or the `style.css` there with * a `Theme Name` header. * - * It is what makes the version check possible before anything is sent, and for a ZIP Herald - * already holds, which Herald names without saying what is in it. + * The action compares it with the version being released before anything is sent. For a ZIP + * Herald already holds it is the only version there is to compare: Herald answers that upload + * with the id of its record and nothing about what is in it. * * @param {Buffer} zip The archive. * @@ -482,14 +484,14 @@ async function send({ fetch, url, method = 'GET', apiKey, json, form, timeout = * * @param {{status: number, reason: string}} answer What `send` returned. * - * @returns {string} `HTTP 401: invalid API key`, or `no answer: fetch failed`. + * @returns {string} `HTTP 401: unauthorized`, or `no answer: fetch failed`. */ function failure(answer) { return answer.status === 0 ? `no answer: ${answer.reason}` : `HTTP ${answer.status}: ${answer.reason}` } /** - * Whether a failed write may have been applied all the same. Only a refusal (4xx) says that Herald + * Whether a failed write may have been applied anyway. Only a refusal (4xx) says that Herald * wrote nothing. No answer, a server error, or an answer of a shape the action does not expect * leaves it unknown. * @@ -541,7 +543,7 @@ async function uploadZip({ fetch, base, apiKey, zip }) { return { id: duplicate[1], sha256: '', meta: null, reused: true } } - const left = unconfirmed(answer) ? 'Herald may have stored the ZIP all the same. No version was changed.' : NOTHING + const left = unconfirmed(answer) ? 'Herald may have stored the ZIP anyway. No version was changed.' : NOTHING throw new Error(`Uploading ${zip.name} to Herald failed (${failure(answer)}). ${left}`) } @@ -632,7 +634,7 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro const raced = answer.status === 400 && /already exists/i.test(answer.reason) if (answer.status !== 201 && !raced) { const left = unconfirmed(answer) - ? `Herald may have created the version all the same: run it again, and a version found there is updated. The ZIP is in Herald as ${uploaded.id}.` + ? `Herald may have created the version anyway: run it again, and a version found there is updated. The ZIP is in Herald as ${uploaded.id}.` : stored throw new Error(`Creating ${product} ${version} in Herald failed (${failure(answer)}). ${left}`) } diff --git a/templates/workflows/release.yml b/templates/workflows/release.yml index 6afc0ef9..0b5f33c3 100644 --- a/templates/workflows/release.yml +++ b/templates/workflows/release.yml @@ -90,10 +90,12 @@ jobs: # For a product sold through Herald: upload the build and publish the version there before the # GitHub release, so a failed upload leaves no release behind. The step goes after the one # that builds the ZIP, and `zip` is the path of that file in the checkout, the same one - # release-publish gets in `files`. The key is the HERALD_API_KEY secret, of the organization - # or of the environment above. The condition runs the step only where that secret exists, and - # skips the rerun of a version already published, which would replace a ZIP customers are - # downloading. It needs the HERALD_CONFIGURED line of the job's `env` above. + # release-publish gets in `files`. + # + # The key is the HERALD_API_KEY secret, of the organization or of the environment above. The + # condition runs the step only where that secret exists. It also skips the rerun of a version + # already published, which would replace a ZIP customers are downloading. It needs the + # HERALD_CONFIGURED line of the job's `env` above. # - uses: stellarwp/plugin-toolbox/.github/actions/herald-publish@v1 # if: env.HERALD_CONFIGURED == 'true' && steps.merge.outputs.already-published == 'no' # with: diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index f37309f4..a43f2296 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -250,8 +250,8 @@ describe('herald-publish', () => { assert.strictEqual(readUrl(' https://herald.example.com/ '), 'https://herald.example.com') }) - it('refuses an address that would send the key in the clear', () => { - assert.throws(() => readUrl('http://herald.example.com'), /not HTTPS.*Nothing was published to Herald/) + it('refuses an address that would send the key unencrypted', () => { + assert.throws(() => readUrl('http://herald.example.com'), /is not HTTPS, so the API key would be sent unencrypted\. Nothing was published to Herald/) }) it('takes plain HTTP for a Herald on the same machine', () => { @@ -263,7 +263,7 @@ describe('herald-publish', () => { assert.throws(() => readUrl('https://herald.example.com/?key=1'), /address only/) }) - it('links the versions page of the product, with a slug that needs encoding kept safe', async (t) => { + it('links the versions page of the product, and encodes a slug that needs it', async (t) => { const { core, outputs } = await coreWithOutputs(t) const product = 'gift aid'.replace(' ', '%') const base = `${BASE}/api/v1/products/${encodeURIComponent(product)}/versions` @@ -405,7 +405,7 @@ describe('herald-publish', () => { }) it('refuses a version that is not three or four numeric parts', () => { - assert.throws(() => validateVersion('2.2.2-rc.1'), /is not a version Herald gets from this action.*Nothing was published to Herald/) + assert.throws(() => validateVersion('2.2.2-rc.1'), /is not a version Herald gets from this action\. The action takes three or four numeric parts.*Nothing was published to Herald/) assert.throws(() => validateVersion(''), /No version was given/) assert.strictEqual(validateVersion(' 2.2.2.1 '), '2.2.2.1') }) @@ -689,7 +689,7 @@ describe('herald-publish', () => { runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), (error) => { assert.match(error.message, /Uploading give-gift-aid\.zip to Herald failed \(no answer: socket hang up\)/) - assert.match(error.message, /may have stored the ZIP all the same.*No version was changed/) + assert.match(error.message, /may have stored the ZIP anyway\. No version was changed/) assert.doesNotMatch(error.message, /Nothing was published/) return true @@ -705,7 +705,7 @@ describe('herald-publish', () => { runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), (error) => { assert.match(error.message, /Uploading give-gift-aid\.zip to Herald failed \(HTTP 201: \{\}\)/) - assert.match(error.message, /may have stored the ZIP all the same/) + assert.match(error.message, /may have stored the ZIP anyway/) assert.doesNotMatch(error.message, /Nothing was published/) return true @@ -713,7 +713,7 @@ describe('herald-publish', () => { ) }) - it('says so when Herald does not answer', async (t) => { + it('names the network failure when Herald does not answer', async (t) => { const { core } = await coreWithOutputs(t) const fetch = async () => { throw new TypeError('fetch failed', { cause: new Error('getaddrinfo ENOTFOUND herald.test') }) @@ -762,7 +762,7 @@ describe('herald-publish', () => { runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), (error) => { assert.match(error.message, /Creating gift-aid 2\.2\.2 in Herald failed \(no answer: socket hang up\)/) - assert.match(error.message, /may have created the version/) + assert.match(error.message, /may have created the version anyway: run it again/) assert.doesNotMatch(error.message, /no version of gift-aid was changed/) return true @@ -785,7 +785,7 @@ describe('herald-publish', () => { ) }) - it('names the product when Herald does not have it', async (t) => { + it('says where the ZIP is when the create finds no product', async (t) => { const { core } = await coreWithOutputs(t) const { fetch } = heraldFetch([ FRESH[0], From c915a212a6dc4af6964f10d37372c33b6be9b456 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 13:28:57 -0300 Subject: [PATCH 24/45] herald-publish: split the changelog file with the shared lines helper readChangelogFile split the file into trimmed, non-empty lines with the same four lines lib/inputs.js already has as lines(). It is imported under another name, since entriesOnly has a variable called lines. SOFT-5788 --- .github/actions/herald-publish/herald-publish.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index 487590f5..0b86d2b6 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -24,6 +24,7 @@ const fs = require('node:fs') const path = require('node:path') const zlib = require('node:zlib') +const { lines: nonEmptyLines } = require('../../lib/inputs.js') const { STELLARWP_VERSION_PATTERN } = require('../../lib/versions.js') /** Closes every error message raised with nothing of this run written to Herald. */ @@ -230,10 +231,7 @@ function readChangelogFile(input, cwd) { throw new Error(`changelog-file '${trimmed}' is not a file in the checkout. ${NOTHING}`) } - const entries = text - .split(/\r?\n/) - .map((line) => line.trim()) - .filter(Boolean) + const entries = nonEmptyLines(text) if (entries.length === 0) { throw new Error( From 684582b11afb9b0f36a9dab36cf2b1fd0d08ffd8 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 13:38:56 -0300 Subject: [PATCH 25/45] herald-publish: refuse . and .. as the product slug The slug is checked so that it stays one segment of the request's path. "." and ".." passed that check, and a URL reads them as the folder itself and the one above it: the read of the version went to another path, got a 404 the action took for a missing version, and the ZIP was uploaded before the create failed. SOFT-5788 --- .github/actions/herald-publish/herald-publish.js | 8 +++++++- tests/actions/herald-publish/herald-publish.test.js | 6 ++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index 0b86d2b6..f8d67453 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -120,7 +120,7 @@ function readUrl(url) { * * @param {string} slug The input value. * - * @throws {Error} When it is empty or holds whitespace or a URL delimiter. + * @throws {Error} When it is empty, holds whitespace or a URL delimiter, or is `.` or `..`. * * @returns {string} The slug, without surrounding whitespace. */ @@ -135,6 +135,12 @@ function readProductSlug(slug) { throw new Error(`product-slug '${trimmed}' is not a Herald slug: it holds a space or one of / \\ ? #. ${NOTHING}`) } + // A URL reads these two as the folder itself and the one above it, so the request would go to + // another path than the product's. + if (trimmed === '.' || trimmed === '..') { + throw new Error(`product-slug '${trimmed}' is not a Herald slug: . and .. change the path of the request. ${NOTHING}`) + } + return trimmed } diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index a43f2296..8210e1b0 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -291,6 +291,12 @@ describe('herald-publish', () => { assert.throws(() => readProductSlug('gift aid'), /product-slug 'gift aid' is not a Herald slug/) }) + it('refuses a product slug that would change the path of the request', () => { + assert.throws(() => readProductSlug('..'), /product-slug '\.\.' is not a Herald slug: \. and \.\. change the path of the request\. Nothing was published to Herald/) + assert.throws(() => readProductSlug('.'), /product-slug '\.' is not a Herald slug: \. and \.\. change the path of the request/) + assert.strictEqual(readProductSlug('gift.aid'), 'gift.aid') + }) + it('gets every input of the manifest under the name the script reads', () => { const directory = path.join(__dirname, '../../../.github/actions/herald-publish') const manifest = fs.readFileSync(path.join(directory, 'action.yml'), 'utf8') From 0dbde337c89265dee817fa6c9c60ad2745e32849 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 13:38:56 -0300 Subject: [PATCH 26/45] herald-publish: warn when the version another run created cannot be read When another run creates the version first, the action reads it to make the same changelog and date corrections. A read that failed there let the update go on with neither correction and nothing in the log, so the run ended green and the version could keep the header or have no date. The run still goes on, and now says so in a warning. SOFT-5788 --- .github/actions/herald-publish/README.md | 4 +++- .github/actions/herald-publish/herald-publish.js | 10 +++++++++- tests/actions/herald-publish/herald-publish.test.js | 8 ++++++-- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index c42cc3cd..a3ecd888 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -194,7 +194,9 @@ A run can be repeated after a late failure, for the same version: [refuses bytes it already stores](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/crates/herald-server/src/routes/zip_upload.rs#L73-L79) and names the record in the refusal. The action takes that id and goes on. - **Another run created the version in between.** The create is refused as a duplicate. The action - reads the version the other run created and goes on to the update. + reads the version the other run created and goes on to the update. When that read fails, the + update still runs, with a warning that the changelog header and the release date were not + corrected. When a step fails, the error says what Herald holds at that point. That is nothing, the ZIP with no version changed, or a new version left as a draft. diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index f8d67453..52ff1007 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -648,10 +648,18 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro // The other run may stop before its own update, so this one reads what was created and makes // the same corrections to the changelog and the release date. The update decides the outcome - // either way, so a read that fails here does not stop the run. + // either way, so a read that fails here does not stop the run: it warns that the corrections + // were not made. if (raced) { const again = await send({ fetch, url: versionUrl, apiKey }) current = again.status === 200 ? again.data : null + + if (current === null) { + core.warning( + `Another run created ${product} ${version}, and reading it failed (${failure(again)}). ` + + 'Its changelog header and release date were not corrected: check them in Herald.' + ) + } } } diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index 8210e1b0..f00324ba 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -542,8 +542,8 @@ describe('herald-publish', () => { assert.strictEqual(outputs().created, 'false') }) - it('goes on to the update when the version another run created cannot be read', async (t) => { - const { core, outputs } = await coreWithOutputs(t) + it('goes on to the update with a warning when the version another run created cannot be read', async (t) => { + const { core, outputs, logged } = await coreWithOutputs(t) const { fetch, requests } = heraldFetch([ FRESH[0], FRESH[1], @@ -555,6 +555,10 @@ describe('herald-publish', () => { assert.deepStrictEqual(requests.at(-1).body, { zip_id: ZIP_ID, status: 'published' }) assert.strictEqual(outputs().created, 'false') + assert.match( + logged(), + /::warning::Another run created gift-aid 2\.2\.2, and reading it failed \(HTTP 404: version '2\.2\.2' not found\)\. Its changelog header and release date were not corrected: check them in Herald\./ + ) }) }) From c384363ebec1db496667320a21330bea4cc9bf0e Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 14:19:50 -0300 Subject: [PATCH 27/45] herald-publish README: a failure after Herald confirmed the update does not undo it The README said that when a step fails, the error says what Herald holds. That is true of a failed call to Herald. The step can also fail after the update is confirmed, when an output or the job summary cannot be written, and that error says nothing about Herald. The README now says the log line that confirms the update is the record for that case. SOFT-5788 --- .github/actions/herald-publish/README.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index a3ecd888..c603450b 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -198,12 +198,16 @@ A run can be repeated after a late failure, for the same version: update still runs, with a warning that the changelog header and the release date were not corrected. -When a step fails, the error says what Herald holds at that point. That is nothing, the ZIP with no -version changed, or a new version left as a draft. +When a call to Herald fails, the error says what Herald holds at that point. That is nothing, the ZIP +with no version changed, or a new version left as a draft. Only a refusal from Herald (an HTTP 4xx) shows that a write was not applied. When Herald did not answer a write, or answered with a server error, the error says that what Herald holds is not known. +The log line ` is in Herald with the ZIP ` means Herald confirmed +the update. A failure after that line, such as the job summary not being written, does not undo it: +the version is in Herald as the line says. + Skip the step for a version whose GitHub release already exists, as the example at the top does with release-merge's [`already-published`](../release-merge/README.md#outputs) output. The rerun of a published version From 27fb60eccc966111720e2da0090948738c090ddc Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 15:11:21 -0300 Subject: [PATCH 28/45] herald-publish: take plain HTTP for an IPv6 localhost too http://[::1] was refused as not HTTPS, while localhost and 127.0.0.1 passed. All three are the machine itself. SOFT-5788 --- .github/actions/herald-publish/README.md | 2 +- .github/actions/herald-publish/action.yml | 2 +- .github/actions/herald-publish/herald-publish.js | 2 +- tests/actions/herald-publish/herald-publish.test.js | 2 ++ 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index c603450b..e98630c4 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -166,7 +166,7 @@ own version instead of the entries. | Input | Required | Default | What it is | |---|---|---|---| -| `herald-url` | yes | | The address of the Herald instance to publish to. HTTPS, or plain HTTP for `localhost`. | +| `herald-url` | yes | | The address of the Herald instance to publish to. HTTPS, or plain HTTP for a Herald on the same machine. | | `product-slug` | yes | | The slug of the product in Herald. | | `version` | yes | | The version being released: three or four numeric parts. | | `zip` | yes | | The build to upload, a `.zip` path relative to the checkout. A step before this one builds it. | diff --git a/.github/actions/herald-publish/action.yml b/.github/actions/herald-publish/action.yml index dc935eee..97cd1b4b 100644 --- a/.github/actions/herald-publish/action.yml +++ b/.github/actions/herald-publish/action.yml @@ -14,7 +14,7 @@ inputs: description: >- The address of the Herald instance to publish to, e.g. `https://herald.example.com`. There is no default: the caller names it. HTTPS, since the API key goes in every request; plain HTTP is - accepted for `localhost` only. + accepted for the machine itself only (`localhost`, `127.0.0.1` or `[::1]`). required: true product-slug: description: 'The slug of the product in Herald, as its Products page shows it.' diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index 52ff1007..39b1fae1 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -103,7 +103,7 @@ function readUrl(url) { throw new Error(`herald-url '${trimmed}' is not a URL. ${NOTHING}`) } - const local = ['localhost', '127.0.0.1'].includes(parsed.hostname) + const local = ['localhost', '127.0.0.1', '[::1]'].includes(parsed.hostname) if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && local)) { throw new Error(`herald-url '${trimmed}' is not HTTPS, so the API key would be sent unencrypted. ${NOTHING}`) } diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index f00324ba..0397e2b3 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -256,6 +256,8 @@ describe('herald-publish', () => { it('takes plain HTTP for a Herald on the same machine', () => { assert.strictEqual(readUrl('http://localhost:3000'), 'http://localhost:3000') + assert.strictEqual(readUrl('http://127.0.0.1:3000'), 'http://127.0.0.1:3000') + assert.strictEqual(readUrl('http://[::1]:3000'), 'http://[::1]:3000') }) it('refuses an address with credentials or a query', () => { From f873733883c94a4d7fcede8a68518a5401e070d6 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 15:11:21 -0300 Subject: [PATCH 29/45] herald-publish: find "product not found" with or without the slug in it The check that stops before the upload matched Herald's message only with the slug between the two words. A message without it, such as "Product not found", read as a missing version: the ZIP was uploaded and the create failed after it. SOFT-5788 --- .github/actions/herald-publish/herald-publish.js | 2 +- tests/actions/herald-publish/herald-publish.test.js | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index 39b1fae1..e2895a7e 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -594,7 +594,7 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro // Read before the upload: a key Herald refuses and a product it does not have stop here, with // no ZIP left behind. Herald answers 404 for both a missing product and a missing version. const found = await send({ fetch, url: versionUrl, apiKey }) - if (found.status === 404 && /product .* not found/i.test(found.reason)) { + if (found.status === 404 && /product\b.*not found/i.test(found.reason)) { throw new Error(`Herald has no product '${product}': create it there, or correct the slug. ${NOTHING}`) } diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index 0397e2b3..fe8fbdb7 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -664,6 +664,17 @@ describe('herald-publish', () => { assert.deepStrictEqual(calls(requests), ['GET /api/v1/products/gift-aid/versions/2.2.2']) }) + it('stops before the upload when Herald says the product is missing without naming it', async (t) => { + const { core } = await coreWithOutputs(t) + const { fetch, requests } = heraldFetch([FRESH[0], { method: 'GET', path: API.version, status: 404, body: { error: 'Product not found' } }]) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + /Herald has no product 'gift-aid'.*Nothing was published to Herald/ + ) + assert.deepStrictEqual(calls(requests), ['GET /api/v1/products/gift-aid/versions/2.2.2']) + }) + it('stops before the upload when Herald refuses the key', async (t) => { const { core } = await coreWithOutputs(t) const { fetch, requests } = heraldFetch([FRESH[0], { method: 'GET', path: API.version, status: 401, body: { error: 'unauthorized' } }]) From 8b3dd4e20a83e1cdcc08df7cdc69f4f47c7b9569 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 15:11:21 -0300 Subject: [PATCH 30/45] herald-publish: read the Version header the way WordPress does The version was the first word after "Version:", so a comment that closes right after it stayed in the value and a good ZIP was refused. WordPress takes the rest of the line and drops the end of a comment or a closing PHP tag, and the action now does the same. Herald gives the rest of that line as it is, so the version it reads is cleaned the same way before the comparison. Without that, the ZIP would pass the action's own check and be refused after the upload. SOFT-5788 --- .../actions/herald-publish/herald-publish.js | 28 ++++++++++++++----- .../herald-publish/herald-publish.test.js | 26 +++++++++++++++++ 2 files changed, 47 insertions(+), 7 deletions(-) diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index e2895a7e..5699ed66 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -336,6 +336,18 @@ function zipFileStart(zip, entry) { } } +/** + * Cleans the value of a header line the way WordPress does: the end of a comment or a closing PHP + * tag on the same line is not part of it, so `2.2.2 ?>` reads as `2.2.2`. + * + * @param {string} value What follows the header's name on its line. + * + * @returns {string} The value, without that closing and without surrounding whitespace. + */ +function headerValue(value) { + return value.replace(/\s*(?:\*\/|\?>).*/, '').trim() +} + /** * Reads the version in the header of the plugin or the theme inside a zip, as WordPress finds it: * a `.php` right inside the top folder with a `Plugin Name` header, or the `style.css` there with @@ -369,9 +381,10 @@ function readZipVersion(zip) { continue } - const version = /^[ \t/*#@]*Version:[ \t]*(\S+)/im.exec(start) + const version = /^[ \t/*#@]*Version:(.*)$/im.exec(start) + const value = version ? headerValue(version[1]) : '' - return version ? { file: entry.name, version: version[1] } : null + return value === '' ? null : { file: entry.name, version: value } } return null @@ -611,16 +624,17 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro ) // Herald reads the plugin header too, of a ZIP it stores for the first time. It is the check - // left when the read above found no version. - const zipVersion = uploaded.meta?.version - if (typeof zipVersion === 'string' && zipVersion.trim() !== '' && zipVersion.trim() !== version) { + // left when the read above found no version. Herald gives the rest of the header line as it + // is, so the value is cleaned the same way as the action's own read. + const zipVersion = typeof uploaded.meta?.version === 'string' ? headerValue(uploaded.meta.version) : '' + if (zipVersion !== '' && zipVersion !== version) { throw new Error( - `${zip.name} is version ${zipVersion.trim()} (${uploaded.meta.main_file ?? 'main file unknown'}), ` + + `${zip.name} is version ${zipVersion} (${uploaded.meta.main_file ?? 'main file unknown'}), ` + `not ${version}, so it was not published. ${stored}` ) } - if (inside === null && (typeof zipVersion !== 'string' || zipVersion.trim() === '')) { + if (inside === null && zipVersion === '') { core.warning(`The version inside ${zip.name} could not be read, so it was not compared with ${version}.`) } diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index fe8fbdb7..1b89ba88 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -392,6 +392,20 @@ describe('herald-publish', () => { assert.strictEqual(readZipVersion(zip64), null) }) + it('reads the version as WordPress does, without a comment that closes on the same line', () => { + const closed = zipOf({ 'my-plugin/my-plugin.php': '\n' }) + + assert.deepStrictEqual(readZipVersion(closed), { file: 'my-plugin/my-plugin.php', version: '2.2.2' }) + assert.deepStrictEqual(readZipVersion(tag), { file: 'my-plugin/my-plugin.php', version: '2.2.2' }) + }) + + it('reads everything after Version as the version, as WordPress does', () => { + const beta = zipOf({ 'my-plugin/my-plugin.php': ' { const theme = zipOf({ 'my-theme/functions.php': ' { assert.deepStrictEqual(calls(requests), ['GET /api/v1/products/gift-aid/versions/2.2.2', 'POST /api/v1/zips/upload']) }) + it('takes the version Herald read without a comment that closes on the same line', async (t) => { + const { core, outputs } = await coreWithOutputs(t) + // Herald gives the rest of the header line as it is, the closing of the comment included. + const closed = { ...ZIP_RECORD, meta: { ...ZIP_RECORD.meta, version: '2.2.2*/' } } + const { fetch } = heraldFetch([{ method: 'POST', path: API.upload, status: 201, body: closed }, ...FRESH.slice(1)]) + const cwd = checkoutWith({ 'give-gift-aid.zip': 'PK\u0003\u0004 not a zip the action can read' }) + + await runHeraldPublish({ core, env: publishEnv(), fetch, cwd, now: NOW }) + + assert.strictEqual(outputs().status, 'published') + }) + it('warns when neither the action nor Herald could read the version of the ZIP', async (t) => { const { core, logged } = await coreWithOutputs(t) const { fetch } = heraldFetch([ From 9e0a71e68b61943d20d5876b93a529954757eb4d Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 15:11:21 -0300 Subject: [PATCH 31/45] Deploy summary: one list, with links in place of code spans The three actions of a deploy each wrote a loose line to the job summary, with the branches, the commit, the product and the ids in code spans and the addresses written out. Each one now writes an item of the same list. A branch, a commit, the release and the product's versions in Herald are links, and the ZIP id and its hash are two lines under the Herald item. release-merge and release-publish get the address of the repository from a helper in lib/github.js. SOFT-5788 --- .../actions/herald-publish/herald-publish.js | 15 +++---- .../actions/release-merge/release-merge.js | 9 +++-- .../release-publish/release-publish.js | 15 ++++--- .github/lib/github.js | 40 ++++++++++++++++++- .../herald-publish/herald-publish.test.js | 13 ++++-- .../release-merge/release-merge.test.js | 7 +++- .../release-publish/release-publish.test.js | 6 +-- tests/lib/github.test.js | 33 +++++++++++++++ 8 files changed, 114 insertions(+), 24 deletions(-) create mode 100644 tests/lib/github.test.js diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index 5699ed66..912703c4 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -729,13 +729,14 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro core.setOutput('status', status) core.setOutput('created', created ? 'true' : 'false') core.setOutput('versions-url', versionsUrl) - await core.summary - .addRaw( - `Herald: \`${product}\` ${version} is ${status}, ${created ? 'created' : 'updated'} with the ZIP \`${uploaded.id}\`` + - `${uploaded.sha256 === '' ? '' : ` (sha256 \`${uploaded.sha256}\`)`}: ${versionsUrl}`, - true - ) - .write() + // One item of the list the deploy's actions write to the job summary. Herald computes the hash + // of a ZIP it stores, so there is none to show for one it already held. + const lines = [ + `- **Herald:** [${product} ${version}](${versionsUrl}) is ${status}, version ${created ? 'created' : 'updated'}.`, + ` - ZIP: ${uploaded.id}`, + ...(uploaded.sha256 === '' ? [] : [` - SHA-256: ${uploaded.sha256}`]), + ] + await core.summary.addRaw(lines.join('\n'), true).write() } module.exports = { diff --git a/.github/actions/release-merge/release-merge.js b/.github/actions/release-merge/release-merge.js index 71831d01..a10b8e58 100644 --- a/.github/actions/release-merge/release-merge.js +++ b/.github/actions/release-merge/release-merge.js @@ -14,7 +14,7 @@ */ const { validateVersion: validateReleaseVersion } = require('../../lib/versions.js') -const { readRepository, isNotFound, readTag } = require('../../lib/github.js') +const { readRepository, isNotFound, readTag, repositoryUrl, branchLink } = require('../../lib/github.js') const { readVersionFiles, versionIn } = require('../../lib/puprc.js') /** @@ -529,9 +529,12 @@ async function runMerge({ github, core, env }) { ).merged } - const did = (merged, from, into) => (merged ? `merged \`${from}\` into \`${into}\`` : `\`${into}\` already had \`${from}\``) + // One item of the list the deploy's actions write to the job summary, with each branch as a link. + const url = repositoryUrl(env, { owner, repo }) + const link = (name) => branchLink(url, name) + const did = (merged, from, into) => (merged ? `merged ${link(from)} into ${link(into)}` : `${link(into)} already had ${link(from)}`) const developPart = develop === null ? 'no develop branch to merge back into' : did(mergedDevelop, base, develop) - await core.summary.addRaw(`Release ${version}: ${did(mergedBase, branch, base)}, ${developPart}.`, true).write() + await core.summary.addRaw(`- **Release ${version}:** ${did(mergedBase, branch, base)}, ${developPart}.`, true).write() // These outputs are the last thing the step writes: a step that failed, on the summary above or // anywhere before, leaves them empty, so a caller that reads `already-published == 'no'` under diff --git a/.github/actions/release-publish/release-publish.js b/.github/actions/release-publish/release-publish.js index 44f763d7..5057b3cb 100644 --- a/.github/actions/release-publish/release-publish.js +++ b/.github/actions/release-publish/release-publish.js @@ -21,7 +21,7 @@ const fs = require('node:fs') const path = require('node:path') const { STELLARWP_VERSION_PATTERN, compareVersions, validateVersion: validateReleaseVersion } = require('../../lib/versions.js') -const { readRepository, isNotFound, readTag, tagExists } = require('../../lib/github.js') +const { readRepository, isNotFound, readTag, tagExists, repositoryUrl, commitLink } = require('../../lib/github.js') /** Closes every error message: nothing of this action's was done. */ const NOTHING = 'Nothing was published.' @@ -319,6 +319,7 @@ async function runPublish({ github, core, env, cwd = process.cwd() }) { const notes = readNotesFile(env.INPUT_NOTES_FILE, cwd) const files = readFiles(env.INPUT_FILES, cwd) const { owner, repo } = readRepository(env, NOTHING) + const url = repositoryUrl(env, { owner, repo }) let existing = null try { @@ -334,7 +335,7 @@ async function runPublish({ github, core, env, cwd = process.cwd() }) { core.setOutput('published', 'skipped') core.setOutput('release-url', existing.html_url) core.setOutput('sha', '') - await core.summary.addRaw(`Release ${version} was already published: ${existing.html_url}`, true).write() + await core.summary.addRaw(`- **GitHub release:** [${version}](${existing.html_url}) was already published.`, true).write() return } @@ -411,7 +412,9 @@ async function runPublish({ github, core, env, cwd = process.cwd() }) { const tagSha = await readTag({ github, owner, repo, version, what: `The release is public at ${release.html_url}.` }) if (tagSha !== null && tagSha !== sha) { - await core.summary.addRaw(`Release ${version} was published at \`${tagSha.slice(0, 7)}\`, not at \`${sha.slice(0, 7)}\`: ${release.html_url}`, true).write() + await core.summary + .addRaw(`- **GitHub release:** [${version}](${release.html_url}) was published at ${commitLink(url, tagSha)}, not at ${commitLink(url, sha)}.`, true) + .write() throw new Error( `The tag ${version} was created at ${tagSha} between the check and the publish, and the release is ` + `attached to it, not to ${sha}. The release is public at ${release.html_url}: delete it and the tag, or ` + @@ -484,8 +487,10 @@ async function runPublish({ github, core, env, cwd = process.cwd() }) { core.setOutput('published', 'true') core.setOutput('release-url', release.html_url) core.setOutput('sha', sha) - const attached = files.length === 0 ? '' : ` with ${files.map((asset) => `\`${asset.name}\``).join(', ')}` - await core.summary.addRaw(`Published release ${version} at \`${sha.slice(0, 7)}\`${attached}: ${release.html_url}`, true).write() + const attached = files.length === 0 ? '' : `, with ${files.map((asset) => asset.name).join(', ')}` + await core.summary + .addRaw(`- **GitHub release:** [${version}](${release.html_url}) published at ${commitLink(url, sha)}${attached}.`, true) + .write() } module.exports = { diff --git a/.github/lib/github.js b/.github/lib/github.js index b6eaad66..c5b49fce 100644 --- a/.github/lib/github.js +++ b/.github/lib/github.js @@ -89,4 +89,42 @@ async function tagExists(options) { return (await readTag(options)) !== null } -module.exports = { readRepository, isNotFound, readTag, tagExists } +/** + * The address of the repository on GitHub, for the links of a job summary. + * + * @param {object} env The environment. `GITHUB_SERVER_URL` is where GitHub answers. + * @param {{owner: string, repo: string}} repository What `readRepository` returned. + * + * @returns {string} The address, without a trailing slash. + */ +function repositoryUrl(env, { owner, repo }) { + const server = String(env.GITHUB_SERVER_URL || 'https://github.com').replace(/\/+$/, '') + + return `${server}/${owner}/${repo}` +} + +/** + * A branch as a Markdown link to its page, for a job summary. + * + * @param {string} url What `repositoryUrl` returned. + * @param {string} branch The branch name. Its slashes stay slashes in the address. + * + * @returns {string} The link, with the branch name as its text. + */ +function branchLink(url, branch) { + return `[${branch}](${url}/tree/${branch.split('/').map(encodeURIComponent).join('/')})` +} + +/** + * A commit as a Markdown link to its page, for a job summary. + * + * @param {string} url What `repositoryUrl` returned. + * @param {string} sha The full commit SHA. + * + * @returns {string} The link, with the first seven characters of the SHA as its text. + */ +function commitLink(url, sha) { + return `[${sha.slice(0, 7)}](${url}/commit/${sha})` +} + +module.exports = { readRepository, isNotFound, readTag, tagExists, repositoryUrl, branchLink, commitLink } diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index 1b89ba88..479a5b1b 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -475,7 +475,12 @@ describe('herald-publish', () => { assert.ok(sent.every((options) => options.redirect === 'error')) assert.ok(sent.every((options) => options.signal instanceof AbortSignal)) assert.deepStrictEqual(outputs(), { 'zip-id': ZIP_ID, sha256: SHA256, status: 'published', created: 'true', 'versions-url': VERSIONS_URL }) - assert.match(summary(), /`gift-aid` 2\.2\.2 is published, created with the ZIP.*: https:\/\/herald\.test\/admin\/products\/gift-aid\/versions/) + assert.strictEqual( + summary(), + '- **Herald:** [gift-aid 2.2.2](https://herald.test/admin/products/gift-aid/versions) is published, version created.\n' + + ` - ZIP: ${ZIP_ID}\n` + + ` - SHA-256: ${SHA256}\n` + ) assert.match(logged(), /gift-aid 2\.2\.2 is published in Herald with the ZIP 11111111.*: https:\/\/herald\.test\/admin\/products\/gift-aid\/versions/) assert.match(logged(), /Uploaded give-gift-aid\.zip as 11111111/) assert.match(logged(), /Took the version header out of the changelog/) @@ -596,11 +601,11 @@ describe('herald-publish', () => { ]) assert.deepStrictEqual(requests[2].body, { zip_id: ZIP_ID, status: 'published' }) assert.strictEqual(outputs().created, 'false') - assert.match(summary(), /is published, updated with the ZIP/) + assert.match(summary(), /\) is published, version updated\.\n {2}- ZIP: 11111111/) }) it('reuses a ZIP Herald already holds', async (t) => { - const { core, outputs, logged } = await coreWithOutputs(t) + const { core, outputs, logged, summary } = await coreWithOutputs(t) const { fetch, requests } = heraldFetch([ { method: 'POST', path: API.upload, status: 400, body: { error: `a ZIP with this content already exists (id: ${ZIP_ID})` } }, { method: 'GET', path: API.version, body: CREATED }, @@ -617,6 +622,8 @@ describe('herald-publish', () => { }) assert.deepStrictEqual(outputs(), { 'zip-id': ZIP_ID, sha256: '', status: 'published', created: 'false', 'versions-url': VERSIONS_URL }) assert.match(logged(), /already holds give-gift-aid\.zip as 11111111.*reusing it/) + // Herald computes the hash of a ZIP it stores, and this one it already held. + assert.doesNotMatch(summary(), /SHA-256/) }) }) diff --git a/tests/actions/release-merge/release-merge.test.js b/tests/actions/release-merge/release-merge.test.js index a6a08026..f4804339 100644 --- a/tests/actions/release-merge/release-merge.test.js +++ b/tests/actions/release-merge/release-merge.test.js @@ -359,7 +359,10 @@ describe('release-merge', () => { // A first release of the version: the caller's deploy and publish have everything to do. 'already-published': 'no', }) - assert.match(summary(), /merged `release\/M26\.test` into `main`, merged `main` into `develop`/) + assert.match( + summary(), + /^- \*\*Release 4\.17\.0:\*\* merged \[release\/M26\.test\]\(https:\/\/github\.com\/stellarwp\/plugin\/tree\/release\/M26\.test\) into \[main\]\(https:\/\/github\.com\/stellarwp\/plugin\/tree\/main\), merged \[main\]\(https:\/\/github\.com\/stellarwp\/plugin\/tree\/main\) into \[develop\]\(https:\/\/github\.com\/stellarwp\/plugin\/tree\/develop\)\.$/m + ) }) it('checks, compares and merges the tip it read, so a commit pushed to the branch meanwhile is not merged', async (t) => { @@ -452,7 +455,7 @@ describe('release-merge', () => { assert.strictEqual(outputs()['develop-branch'], '') assert.strictEqual(outputs().conflict, '') assert.match(logged(), /develop-branch is empty/) - assert.match(summary(), /no develop branch/) + assert.match(summary(), /^- \*\*Release 4\.17\.0:\*\* merged \[release\/M26\.test\]\(.*\) into \[main\]\(.*\), no develop branch to merge back into\.$/m) }) it('does nothing on a retry after a late failure: both merges answer already merged', async (t) => { diff --git a/tests/actions/release-publish/release-publish.test.js b/tests/actions/release-publish/release-publish.test.js index 383df603..87da93b6 100644 --- a/tests/actions/release-publish/release-publish.test.js +++ b/tests/actions/release-publish/release-publish.test.js @@ -238,7 +238,7 @@ describe('release-publish', () => { make_latest: 'true', }) assert.deepStrictEqual(outputs(), { published: 'true', 'release-url': RELEASE_URL, sha: SHA }) - assert.match(summary(), /Published release 4\.17\.0 at `0123456`/) + assert.match(summary(), /^- \*\*GitHub release:\*\* \[4\.17\.0\]\(https:\/\/github\.com\/stellarwp\/plugin\/releases\/tag\/4\.17\.0\) published at \[0123456\]\(https:\/\/github\.com\/stellarwp\/plugin\/commit\/0123456789abcdef0123456789abcdef01234567\)\.$/m) }) it('leaves the start of the notes to GitHub when no published release is below the version', async (t) => { @@ -364,7 +364,7 @@ describe('release-publish', () => { assert.deepStrictEqual(requests[9].body, { draft: false, name: '4.17.0', make_latest: 'true' }) assert.deepStrictEqual(outputs(), { published: 'true', 'release-url': RELEASE_URL, sha: SHA }) assert.match(logged(), /Attached plugin\.zip.*Attached plugin\.pot/s) - assert.match(summary(), /with `plugin\.zip`, `plugin\.pot`/) + assert.match(summary(), /published at \[0123456\]\(.*\), with plugin\.zip, plugin\.pot\.$/m) }) it('deletes the draft when an upload fails, leaving no release and no tag', async (t) => { @@ -439,7 +439,7 @@ describe('release-publish', () => { assert.strictEqual(requested(requests).at(-1), `GET ${API.tag}`) assert.deepStrictEqual(outputs(), {}) - assert.match(summary(), /published at `abcabca`, not at `0123456`/) + assert.match(summary(), /^- \*\*GitHub release:\*\* \[4\.17\.0\]\(.*\) was published at \[abcabca\]\(https:\/\/github\.com\/stellarwp\/plugin\/commit\/abcabcabcabcabcabcabcabcabcabcabcabcabca\), not at \[0123456\]\(.*\)\.$/m) }) it('deletes the draft when publishing it fails, as when a tag ruleset refuses the tag', async (t) => { diff --git a/tests/lib/github.test.js b/tests/lib/github.test.js new file mode 100644 index 00000000..67858f8d --- /dev/null +++ b/tests/lib/github.test.js @@ -0,0 +1,33 @@ +'use strict' + +const { describe, it } = require('node:test') +const assert = require('node:assert') + +const { repositoryUrl, branchLink, commitLink } = require('../../.github/lib/github.js') + +describe('github', () => { + describe('links for a job summary', () => { + it('builds the address of the repository from the server the run is on', () => { + assert.strictEqual(repositoryUrl({}, { owner: 'stellarwp', repo: 'plugin' }), 'https://github.com/stellarwp/plugin') + assert.strictEqual( + repositoryUrl({ GITHUB_SERVER_URL: 'https://github.example.com/' }, { owner: 'stellarwp', repo: 'plugin' }), + 'https://github.example.com/stellarwp/plugin' + ) + }) + + it('links a branch by its name, keeping the slashes of the name in the address', () => { + assert.strictEqual( + branchLink('https://github.com/stellarwp/plugin', 'release/M26.test'), + '[release/M26.test](https://github.com/stellarwp/plugin/tree/release/M26.test)' + ) + assert.strictEqual(branchLink('https://github.com/o/r', 'fix/a b'), '[fix/a b](https://github.com/o/r/tree/fix/a%20b)') + }) + + it('links a commit by its first seven characters', () => { + assert.strictEqual( + commitLink('https://github.com/stellarwp/plugin', '0123456789abcdef0123456789abcdef01234567'), + '[0123456](https://github.com/stellarwp/plugin/commit/0123456789abcdef0123456789abcdef01234567)' + ) + }) + }) +}) From d17a3086b28d1b3463e0e78b565b432e0be0fa32 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 15:11:22 -0300 Subject: [PATCH 32/45] herald-publish README: a rerun keeps the changelog and the date of a version that exists Herald reads the changelog and the release date from the ZIP only when it creates the version. A rerun after a fix to readme.txt therefore keeps the old changelog, unless changelog-file is passed. SOFT-5788 --- .github/actions/herald-publish/README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index e98630c4..3b256226 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -189,7 +189,9 @@ own version instead of the entries. A run can be repeated after a late failure, for the same version: - **The version exists.** It is updated to point at the ZIP of this run. No second version is - created. + created. Its changelog and release date stay as they are: Herald reads them from the ZIP + [only when it creates the version](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/crates/herald-server/src/routes/versions.rs#L198-L218). + To change the changelog of a version that exists, pass `changelog-file`. - **The build came out identical.** Herald [refuses bytes it already stores](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/crates/herald-server/src/routes/zip_upload.rs#L73-L79) and names the record in the refusal. The action takes that id and goes on. From 1c535610c59326419cf1c306ab899abc08fbe090 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 15:11:22 -0300 Subject: [PATCH 33/45] herald-publish: say that already-published is about the GitHub release only When the Herald step passed and a later step failed, the rerun runs the Herald step again, since no GitHub release exists yet. A build that is not identical then replaces the ZIP of a version Herald already serves. The README and the template's comment now say so. SOFT-5788 --- .github/actions/herald-publish/README.md | 4 ++++ templates/workflows/release.yml | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index 3b256226..89a41e43 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -216,6 +216,10 @@ release-merge's builds the ZIP again, and without the condition it would replace a ZIP customers are already downloading. +`already-published` is about the GitHub release only. When the Herald step passed and a later step +failed, the rerun runs the Herald step again. A build that comes out identical reuses the ZIP. Any +other build replaces the ZIP of the version, which is published in Herald by then. + ## The key, and who can publish The key is a Herald API key of scope `ci`. That scope diff --git a/templates/workflows/release.yml b/templates/workflows/release.yml index 0b5f33c3..375af327 100644 --- a/templates/workflows/release.yml +++ b/templates/workflows/release.yml @@ -96,6 +96,10 @@ jobs: # condition runs the step only where that secret exists. It also skips the rerun of a version # already published, which would replace a ZIP customers are downloading. It needs the # HERALD_CONFIGURED line of the job's `env` above. + # + # `already-published` is about the GitHub release only. When this step passed and a later + # one failed, the rerun runs it again: the same ZIP when the build comes out identical, + # another ZIP for the version when it does not. # - uses: stellarwp/plugin-toolbox/.github/actions/herald-publish@v1 # if: env.HERALD_CONFIGURED == 'true' && steps.merge.outputs.already-published == 'no' # with: From 8ff94274729c5ed0a7c431a474da012c16699324 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 15:33:26 -0300 Subject: [PATCH 34/45] release-publish: file names in the summary are code spans again The summary in a list took the code spans off the names of the attached files, together with the ones around branches and commits. A file name is not a link, and without the code span a name with Markdown in it, such as plugin-**debug**.zip, is shown formatted. SOFT-5788 --- .github/actions/release-publish/release-publish.js | 3 ++- tests/actions/release-publish/release-publish.test.js | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/actions/release-publish/release-publish.js b/.github/actions/release-publish/release-publish.js index 5057b3cb..5fb25e07 100644 --- a/.github/actions/release-publish/release-publish.js +++ b/.github/actions/release-publish/release-publish.js @@ -487,7 +487,8 @@ async function runPublish({ github, core, env, cwd = process.cwd() }) { core.setOutput('published', 'true') core.setOutput('release-url', release.html_url) core.setOutput('sha', sha) - const attached = files.length === 0 ? '' : `, with ${files.map((asset) => asset.name).join(', ')}` + // A file name is a code span: it is not a link, and one with Markdown in it shows as it is. + const attached = files.length === 0 ? '' : `, with ${files.map((asset) => `\`${asset.name}\``).join(', ')}` await core.summary .addRaw(`- **GitHub release:** [${version}](${release.html_url}) published at ${commitLink(url, sha)}${attached}.`, true) .write() diff --git a/tests/actions/release-publish/release-publish.test.js b/tests/actions/release-publish/release-publish.test.js index 87da93b6..e1085631 100644 --- a/tests/actions/release-publish/release-publish.test.js +++ b/tests/actions/release-publish/release-publish.test.js @@ -364,7 +364,8 @@ describe('release-publish', () => { assert.deepStrictEqual(requests[9].body, { draft: false, name: '4.17.0', make_latest: 'true' }) assert.deepStrictEqual(outputs(), { published: 'true', 'release-url': RELEASE_URL, sha: SHA }) assert.match(logged(), /Attached plugin\.zip.*Attached plugin\.pot/s) - assert.match(summary(), /published at \[0123456\]\(.*\), with plugin\.zip, plugin\.pot\.$/m) + // File names are code spans, so one with Markdown in it shows as it is. + assert.match(summary(), /published at \[0123456\]\(.*\), with `plugin\.zip`, `plugin\.pot`\.$/m) }) it('deletes the draft when an upload fails, leaving no release and no tag', async (t) => { From 1eec53c3d1c5d994b11e7f6a89b1f254a287e8e9 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 15:33:26 -0300 Subject: [PATCH 35/45] Summary links: a branch name or a slug cannot end its link early Git takes a branch named release/M26.test), and encodeURIComponent leaves the parenthesis as it is, so Markdown closed the address of the link there and the link opened another branch. A ] in the name closed the text of the link the same way. One helper now writes the links of the job summary: it encodes the parentheses of the address and puts a backslash before the characters Markdown reads in the text. The branch and commit links use it, and so does the link of the Herald item, whose text holds the product's slug. SOFT-5788 --- .../actions/herald-publish/herald-publish.js | 3 ++- .github/lib/github.js | 25 ++++++++++++++++--- .../herald-publish/herald-publish.test.js | 16 ++++++++++++ tests/lib/github.test.js | 20 ++++++++++++++- 4 files changed, 59 insertions(+), 5 deletions(-) diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index 912703c4..90637536 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -24,6 +24,7 @@ const fs = require('node:fs') const path = require('node:path') const zlib = require('node:zlib') +const { markdownLink } = require('../../lib/github.js') const { lines: nonEmptyLines } = require('../../lib/inputs.js') const { STELLARWP_VERSION_PATTERN } = require('../../lib/versions.js') @@ -732,7 +733,7 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro // One item of the list the deploy's actions write to the job summary. Herald computes the hash // of a ZIP it stores, so there is none to show for one it already held. const lines = [ - `- **Herald:** [${product} ${version}](${versionsUrl}) is ${status}, version ${created ? 'created' : 'updated'}.`, + `- **Herald:** ${markdownLink(`${product} ${version}`, versionsUrl)} is ${status}, version ${created ? 'created' : 'updated'}.`, ` - ZIP: ${uploaded.id}`, ...(uploaded.sha256 === '' ? [] : [` - SHA-256: ${uploaded.sha256}`]), ] diff --git a/.github/lib/github.js b/.github/lib/github.js index c5b49fce..57b5a094 100644 --- a/.github/lib/github.js +++ b/.github/lib/github.js @@ -103,6 +103,25 @@ function repositoryUrl(env, { owner, repo }) { return `${server}/${owner}/${repo}` } +/** + * A Markdown link that shows its text as it is written and opens the whole address. + * + * A branch name or a slug can hold characters Markdown reads as formatting or as the end of the + * link: a `]` in the text and a `)` in the address both close it early. The text gets a + * backslash before each of those characters, and the parentheses of the address are encoded. + * + * @param {string} text The text of the link. + * @param {string} href The address it opens. + * + * @returns {string} The link. + */ +function markdownLink(text, href) { + const shown = String(text).replace(/[\\`*_[\]<]/g, '\\$&') + const address = String(href).replace(/\(/g, '%28').replace(/\)/g, '%29') + + return `[${shown}](${address})` +} + /** * A branch as a Markdown link to its page, for a job summary. * @@ -112,7 +131,7 @@ function repositoryUrl(env, { owner, repo }) { * @returns {string} The link, with the branch name as its text. */ function branchLink(url, branch) { - return `[${branch}](${url}/tree/${branch.split('/').map(encodeURIComponent).join('/')})` + return markdownLink(branch, `${url}/tree/${branch.split('/').map(encodeURIComponent).join('/')}`) } /** @@ -124,7 +143,7 @@ function branchLink(url, branch) { * @returns {string} The link, with the first seven characters of the SHA as its text. */ function commitLink(url, sha) { - return `[${sha.slice(0, 7)}](${url}/commit/${sha})` + return markdownLink(sha.slice(0, 7), `${url}/commit/${sha}`) } -module.exports = { readRepository, isNotFound, readTag, tagExists, repositoryUrl, branchLink, commitLink } +module.exports = { readRepository, isNotFound, readTag, tagExists, repositoryUrl, markdownLink, branchLink, commitLink } diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index 479a5b1b..043e2c47 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -281,6 +281,22 @@ describe('herald-publish', () => { assert.strictEqual(outputs()['versions-url'], `${BASE}/admin/products/gift%25aid/versions`) }) + it('shows a slug with Markdown in it as it is written in the summary link', async (t) => { + const { core, summary } = await coreWithOutputs(t) + const product = 'gift_aid]' + const base = `${BASE}/api/v1/products/${encodeURIComponent(product)}/versions` + const { fetch } = heraldFetch([ + FRESH[0], + { method: 'GET', path: `${base}/2.2.2`, status: 404, body: { error: "version '2.2.2' not found" } }, + { method: 'POST', path: base, status: 201, body: CREATED }, + { method: 'PATCH', path: `${base}/2.2.2`, body: { version: '2.2.2', status: 'published', zip_id: ZIP_ID } }, + ]) + + await runHeraldPublish({ core, env: publishEnv({ INPUT_PRODUCT_SLUG: product }), fetch, cwd: checkoutWith(), now: NOW }) + + assert.match(summary(), /^- \*\*Herald:\*\* \[gift\\_aid\\\] 2\.2\.2\]\(https:\/\/herald\.test\/admin\/products\/gift_aid%5D\/versions\) is published/) + }) + it('refuses an empty address and one that is not a URL', () => { assert.throws(() => readUrl(''), /No herald-url was given: pass the address of the Herald instance to publish to/) assert.throws(() => readUrl('herald'), /is not a URL/) diff --git a/tests/lib/github.test.js b/tests/lib/github.test.js index 67858f8d..8946192c 100644 --- a/tests/lib/github.test.js +++ b/tests/lib/github.test.js @@ -3,7 +3,7 @@ const { describe, it } = require('node:test') const assert = require('node:assert') -const { repositoryUrl, branchLink, commitLink } = require('../../.github/lib/github.js') +const { repositoryUrl, markdownLink, branchLink, commitLink } = require('../../.github/lib/github.js') describe('github', () => { describe('links for a job summary', () => { @@ -23,6 +23,24 @@ describe('github', () => { assert.strictEqual(branchLink('https://github.com/o/r', 'fix/a b'), '[fix/a b](https://github.com/o/r/tree/fix/a%20b)') }) + it('keeps a parenthesis of the branch name from closing the address of the link', () => { + assert.strictEqual( + branchLink('https://github.com/o/r', 'release/M26.test)'), + '[release/M26.test)](https://github.com/o/r/tree/release/M26.test%29)' + ) + assert.strictEqual(branchLink('https://github.com/o/r', 'fix/(scope)'), '[fix/(scope)](https://github.com/o/r/tree/fix/%28scope%29)') + }) + + it('shows a branch name with Markdown in it as it is written', () => { + assert.strictEqual(branchLink('https://github.com/o/r', 'fix/a]b'), '[fix/a\\]b](https://github.com/o/r/tree/fix/a%5Db)') + assert.strictEqual(branchLink('https://github.com/o/r', 'feature/_wip_'), '[feature/\\_wip\\_](https://github.com/o/r/tree/feature/_wip_)') + }) + + it('writes a link whose text and address cannot end it early', () => { + assert.strictEqual(markdownLink('a*b [c]', 'https://example.com/x(1)'), '[a\\*b \\[c\\]](https://example.com/x%281%29)') + assert.strictEqual(markdownLink('plain 1.2.3', 'https://example.com/v'), '[plain 1.2.3](https://example.com/v)') + }) + it('links a commit by its first seven characters', () => { assert.strictEqual( commitLink('https://github.com/stellarwp/plugin', '0123456789abcdef0123456789abcdef01234567'), From 9dd8a0f808f5c6fec3ac5a86df917c5cf0309012 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 15:39:33 -0300 Subject: [PATCH 36/45] Summary links: escape an entity and a strikethrough in the text too MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A branch named fix/© showed as fix/© in the summary: Markdown reads an entity in the text of a link, and the & was not among the characters the helper escapes. The ~ of a GFM strikethrough was missing as well. The set is now every character CommonMark and GFM read in the middle of a line, and the helper's comment says so. SOFT-5788 --- .github/lib/github.js | 9 ++++++--- tests/lib/github.test.js | 5 +++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.github/lib/github.js b/.github/lib/github.js index 57b5a094..f6e64517 100644 --- a/.github/lib/github.js +++ b/.github/lib/github.js @@ -107,8 +107,11 @@ function repositoryUrl(env, { owner, repo }) { * A Markdown link that shows its text as it is written and opens the whole address. * * A branch name or a slug can hold characters Markdown reads as formatting or as the end of the - * link: a `]` in the text and a `)` in the address both close it early. The text gets a - * backslash before each of those characters, and the parentheses of the address are encoded. + * link: a `]` in the text and a `)` in the address both close it early. The parentheses of the + * address are encoded. The text gets a backslash before every character CommonMark and GFM read + * in the middle of a line: the backslash, the backtick, `*`, `_`, `[`, `]`, `<`, `&` (an entity) + * and `~` (a strikethrough). The others only count at the start of a line or in a table, where + * the text of a link never is. * * @param {string} text The text of the link. * @param {string} href The address it opens. @@ -116,7 +119,7 @@ function repositoryUrl(env, { owner, repo }) { * @returns {string} The link. */ function markdownLink(text, href) { - const shown = String(text).replace(/[\\`*_[\]<]/g, '\\$&') + const shown = String(text).replace(/[\\`*_[\]<&~]/g, '\\$&') const address = String(href).replace(/\(/g, '%28').replace(/\)/g, '%29') return `[${shown}](${address})` diff --git a/tests/lib/github.test.js b/tests/lib/github.test.js index 8946192c..80ba06fa 100644 --- a/tests/lib/github.test.js +++ b/tests/lib/github.test.js @@ -41,6 +41,11 @@ describe('github', () => { assert.strictEqual(markdownLink('plain 1.2.3', 'https://example.com/v'), '[plain 1.2.3](https://example.com/v)') }) + it('shows an entity and a strikethrough in the text as they are written', () => { + assert.strictEqual(branchLink('https://github.com/o/r', 'fix/©'), '[fix/\\©](https://github.com/o/r/tree/fix/%26copy%3B)') + assert.strictEqual(markdownLink('a~~b~~', 'https://example.com/v'), '[a\\~\\~b\\~\\~](https://example.com/v)') + }) + it('links a commit by its first seven characters', () => { assert.strictEqual( commitLink('https://github.com/stellarwp/plugin', '0123456789abcdef0123456789abcdef01234567'), From e4335eb8a230c1fda7632d80a861f466e175e334 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 15:45:45 -0300 Subject: [PATCH 37/45] Summary file names: keep the backticks of a name in its code span A file name with a backtick in it closed its code span early, and the summary of release-publish showed the name in pieces. The delimiter is now one backtick longer than the longest run in the name. SOFT-5788 --- .../release-publish/release-publish.js | 4 ++-- .github/lib/github.js | 22 ++++++++++++++++++- .../release-publish/release-publish.test.js | 15 +++++++++++++ tests/lib/github.test.js | 13 ++++++++++- 4 files changed, 50 insertions(+), 4 deletions(-) diff --git a/.github/actions/release-publish/release-publish.js b/.github/actions/release-publish/release-publish.js index 5fb25e07..1c1ae90b 100644 --- a/.github/actions/release-publish/release-publish.js +++ b/.github/actions/release-publish/release-publish.js @@ -21,7 +21,7 @@ const fs = require('node:fs') const path = require('node:path') const { STELLARWP_VERSION_PATTERN, compareVersions, validateVersion: validateReleaseVersion } = require('../../lib/versions.js') -const { readRepository, isNotFound, readTag, tagExists, repositoryUrl, commitLink } = require('../../lib/github.js') +const { readRepository, isNotFound, readTag, tagExists, repositoryUrl, codeSpan, commitLink } = require('../../lib/github.js') /** Closes every error message: nothing of this action's was done. */ const NOTHING = 'Nothing was published.' @@ -488,7 +488,7 @@ async function runPublish({ github, core, env, cwd = process.cwd() }) { core.setOutput('release-url', release.html_url) core.setOutput('sha', sha) // A file name is a code span: it is not a link, and one with Markdown in it shows as it is. - const attached = files.length === 0 ? '' : `, with ${files.map((asset) => `\`${asset.name}\``).join(', ')}` + const attached = files.length === 0 ? '' : `, with ${files.map((asset) => codeSpan(asset.name)).join(', ')}` await core.summary .addRaw(`- **GitHub release:** [${version}](${release.html_url}) published at ${commitLink(url, sha)}${attached}.`, true) .write() diff --git a/.github/lib/github.js b/.github/lib/github.js index f6e64517..29d62390 100644 --- a/.github/lib/github.js +++ b/.github/lib/github.js @@ -125,6 +125,26 @@ function markdownLink(text, href) { return `[${shown}](${address})` } +/** + * A Markdown code span that shows its text as it is written, backticks included. + * + * A code span ends at the first run of backticks as long as the one that opened it, so the + * delimiter is one backtick longer than the longest run in the text. A text that starts or ends + * with a backtick gets a space on each side, which Markdown drops. + * + * @param {string} text The text to show, a file name for instance. + * + * @returns {string} The code span. + */ +function codeSpan(text) { + const shown = String(text) + const longest = Math.max(0, ...(shown.match(/`+/g) ?? []).map((run) => run.length)) + const delimiter = '`'.repeat(longest + 1) + const space = shown.startsWith('`') || shown.endsWith('`') ? ' ' : '' + + return `${delimiter}${space}${shown}${space}${delimiter}` +} + /** * A branch as a Markdown link to its page, for a job summary. * @@ -149,4 +169,4 @@ function commitLink(url, sha) { return markdownLink(sha.slice(0, 7), `${url}/commit/${sha}`) } -module.exports = { readRepository, isNotFound, readTag, tagExists, repositoryUrl, markdownLink, branchLink, commitLink } +module.exports = { readRepository, isNotFound, readTag, tagExists, repositoryUrl, markdownLink, codeSpan, branchLink, commitLink } diff --git a/tests/actions/release-publish/release-publish.test.js b/tests/actions/release-publish/release-publish.test.js index e1085631..73b301a5 100644 --- a/tests/actions/release-publish/release-publish.test.js +++ b/tests/actions/release-publish/release-publish.test.js @@ -368,6 +368,21 @@ describe('release-publish', () => { assert.match(summary(), /published at \[0123456\]\(.*\), with `plugin\.zip`, `plugin\.pot`\.$/m) }) + it('shows a file name with a backtick in it whole in the summary', async (t) => { + const cwd = checkoutWith({ 'build/plugin-`debug`.zip': 'zip' }) + const { github } = await octokitFor([ + ...FRESH, + { method: 'POST', path: API.releases, status: 201, body: { id: 77, html_url: RELEASE_URL, upload_url: 'https://uploads.github.com/repos/stellarwp/plugin/releases/77/assets{?name,label}' } }, + { method: 'POST', path: API.assets, status: 201, body: { id: 1 } }, + { method: 'PATCH', path: API.release, body: { id: 77, html_url: RELEASE_URL } }, + ]) + const { core, summary } = await coreWithOutputs(t) + + await runPublish({ github, core, env: publishEnv({ INPUT_FILES: 'build/plugin-`debug`.zip\n' }), cwd }) + + assert.match(summary(), /, with ``plugin-`debug`\.zip``\.$/m) + }) + it('deletes the draft when an upload fails, leaving no release and no tag', async (t) => { const cwd = checkoutWith({ 'build/plugin.zip': 'zip' }) const { github, requests } = await octokitFor([ diff --git a/tests/lib/github.test.js b/tests/lib/github.test.js index 80ba06fa..5a522200 100644 --- a/tests/lib/github.test.js +++ b/tests/lib/github.test.js @@ -3,7 +3,7 @@ const { describe, it } = require('node:test') const assert = require('node:assert') -const { repositoryUrl, markdownLink, branchLink, commitLink } = require('../../.github/lib/github.js') +const { repositoryUrl, markdownLink, codeSpan, branchLink, commitLink } = require('../../.github/lib/github.js') describe('github', () => { describe('links for a job summary', () => { @@ -46,6 +46,17 @@ describe('github', () => { assert.strictEqual(markdownLink('a~~b~~', 'https://example.com/v'), '[a\\~\\~b\\~\\~](https://example.com/v)') }) + it('writes a code span that shows the backticks of its text', () => { + assert.strictEqual(codeSpan('plugin.zip'), '`plugin.zip`') + assert.strictEqual(codeSpan('plugin-**debug**.zip'), '`plugin-**debug**.zip`') + assert.strictEqual(codeSpan('plugin-`debug`.zip'), '``plugin-`debug`.zip``') + assert.strictEqual(codeSpan('a``b.zip'), '```a``b.zip```') + // A backtick at either end would join the delimiter: a space on each side keeps it apart, + // and Markdown drops the pair. + assert.strictEqual(codeSpan('`a`.zip'), '`` `a`.zip ``') + assert.strictEqual(codeSpan('a`'), '`` a` ``') + }) + it('links a commit by its first seven characters', () => { assert.strictEqual( commitLink('https://github.com/stellarwp/plugin', '0123456789abcdef0123456789abcdef01234567'), From fac5b911beec58d8284b0f321b7650bca216b111 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 16:59:16 -0300 Subject: [PATCH 38/45] Tests: a create Herald refuses for another reason is not taken for a race Only a 400 that says the version already exists means another run created it. No test sent a 400 with another reason, so the check on the reason could be dropped and every test still passed. SOFT-5788 --- .../herald-publish/herald-publish.test.js | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index 043e2c47..333df061 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -871,6 +871,27 @@ describe('herald-publish', () => { ) }) + it('gives the reason Herald refused the create with when it is not that the version exists', async (t) => { + const { core } = await coreWithOutputs(t) + const { fetch, requests } = heraldFetch([ + FRESH[0], + FRESH[1], + { method: 'POST', path: API.versions, status: 400, body: { error: 'zip not found' } }, + FRESH[3], + ]) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + /Creating gift-aid 2\.2\.2 in Herald failed \(HTTP 400: zip not found\)\. The ZIP is in Herald as 11111111/ + ) + // Not taken for a version another run created: the version is not read again, nor updated. + assert.deepStrictEqual(calls(requests), [ + 'GET /api/v1/products/gift-aid/versions/2.2.2', + 'POST /api/v1/zips/upload', + 'POST /api/v1/products/gift-aid/versions', + ]) + }) + it('does not say what the version holds when the update gets a server error', async (t) => { const { core, outputs } = await coreWithOutputs(t) const { fetch } = heraldFetch([ From 132ca14b1e928444687b79d0d065458224c1c556 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 16:59:16 -0300 Subject: [PATCH 39/45] Tests: the update fails when Herald answers with another ZIP The check of Herald's answer to the update compares the status and the ZIP. Only the status had a test. SOFT-5788 --- .../actions/herald-publish/herald-publish.test.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index 333df061..91122352 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -957,6 +957,21 @@ describe('herald-publish', () => { assert.deepStrictEqual(outputs(), {}) }) + it('fails when Herald answers the update with another ZIP', async (t) => { + const { core, outputs } = await coreWithOutputs(t) + const other = '99999999-2222-4333-8444-555555555555' + const { fetch } = heraldFetch([ + ...FRESH.slice(0, 3), + { method: 'PATCH', path: API.version, body: { version: '2.2.2', status: 'published', zip_id: other } }, + ]) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + /Herald answered the update of gift-aid 2\.2\.2 with status 'published' and the ZIP 99999999.*not 'published' and 11111111/ + ) + assert.deepStrictEqual(outputs(), {}) + }) + it('says an existing version is as it was when the update is refused', async (t) => { const { core } = await coreWithOutputs(t) const { fetch } = heraldFetch([ From 097109c935aabec14541e55083054299e78b78cf Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 17:00:04 -0300 Subject: [PATCH 40/45] herald-publish: show the SHA-256 of a ZIP Herald already held A rerun whose build came out identical reuses the ZIP, and Herald names the record without its hash. The log, the sha256 output and the summary were left without one, while the README said they always show it. Herald finds the record by the SHA-256 of the bytes it is sent, so the action now computes the hash of the file for that case. SOFT-5788 --- .github/actions/herald-publish/README.md | 7 +++++-- .github/actions/herald-publish/action.yml | 2 +- .github/actions/herald-publish/herald-publish.js | 15 ++++++++++----- .../actions/herald-publish/herald-publish.test.js | 14 +++++++++----- 4 files changed, 25 insertions(+), 13 deletions(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index 89a41e43..21916042 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -179,7 +179,7 @@ own version instead of the entries. | Output | What it is | |---|---| | `zip-id` | The id of the ZIP record in Herald. | -| `sha256` | The SHA-256 Herald computed for the ZIP. Empty when Herald already held the same bytes. | +| `sha256` | The SHA-256 of the ZIP. Herald computes it for a ZIP it stores. For a ZIP Herald already held, the action computes it from the file. | | `status` | The status the version was left in. | | `created` | `true` when the version was created, `false` when it existed and was updated. | | `versions-url` | The page of the Herald dashboard that lists the product's versions, newest first. | @@ -194,7 +194,10 @@ A run can be repeated after a late failure, for the same version: To change the changelog of a version that exists, pass `changelog-file`. - **The build came out identical.** Herald [refuses bytes it already stores](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/crates/herald-server/src/routes/zip_upload.rs#L73-L79) - and names the record in the refusal. The action takes that id and goes on. + and names the record in the refusal. The action takes that id and goes on. The refusal has no + hash, so the action shows the SHA-256 of the file. Herald found the record by that hash, so it is + the same one, unless the ZIP has macOS files (`__MACOSX/`, `.DS_Store`): Herald removes those + before it computes the hash. - **Another run created the version in between.** The create is refused as a duplicate. The action reads the version the other run created and goes on to the update. When that read fails, the update still runs, with a warning that the changelog header and the release date were not diff --git a/.github/actions/herald-publish/action.yml b/.github/actions/herald-publish/action.yml index 97cd1b4b..a0db7b28 100644 --- a/.github/actions/herald-publish/action.yml +++ b/.github/actions/herald-publish/action.yml @@ -55,7 +55,7 @@ outputs: description: 'The id of the ZIP record in Herald.' value: ${{ steps.publish.outputs.zip-id }} sha256: - description: 'The SHA-256 Herald computed for the ZIP. Empty when Herald already held the same bytes.' + description: 'The SHA-256 of the ZIP. Herald computes it for a ZIP it stores. For a ZIP Herald already held, it is the hash of the file.' value: ${{ steps.publish.outputs.sha256 }} status: description: 'The status the version was left in.' diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index 90637536..fa7996e5 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -20,6 +20,7 @@ * upload ZIPs and create, read and update versions. */ +const crypto = require('node:crypto') const fs = require('node:fs') const path = require('node:path') const zlib = require('node:zlib') @@ -537,7 +538,7 @@ function unconfirmed(answer) { * nothing; any other failure may have left the ZIP in Herald, and the error says so. * * @returns {Promise<{id: string, sha256: string, meta: object|null, reused: boolean}>} The ZIP - * record. `sha256` is empty and `meta` null for a reused record. + * record. For a reused record, `sha256` is the hash of the file and `meta` is null. */ async function uploadZip({ fetch, base, apiKey, zip }) { const form = new FormData() @@ -558,7 +559,12 @@ async function uploadZip({ fetch, base, apiKey, zip }) { const duplicate = answer.status === 400 ? DUPLICATE_ZIP.exec(answer.reason) : null if (duplicate) { - return { id: duplicate[1], sha256: '', meta: null, reused: true } + // The refusal names the record and gives no hash. Herald found the record by the SHA-256 of + // the bytes it was sent, so the hash of the file is the hash of the record. They differ only + // for a ZIP with macOS files (`__MACOSX/`, `.DS_Store`), which Herald removes before hashing. + const sha256 = crypto.createHash('sha256').update(zip.data).digest('hex') + + return { id: duplicate[1], sha256, meta: null, reused: true } } const left = unconfirmed(answer) ? 'Herald may have stored the ZIP anyway. No version was changed.' : NOTHING @@ -620,7 +626,7 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro const stored = `The ZIP is in Herald as ${uploaded.id}, and no version of ${product} was changed.` core.info( uploaded.reused - ? `Herald already holds ${zip.name} as ${uploaded.id}: reusing it.` + ? `Herald already holds ${zip.name} as ${uploaded.id} (sha256 ${uploaded.sha256}): reusing it.` : `Uploaded ${zip.name} as ${uploaded.id} (sha256 ${uploaded.sha256}).` ) @@ -730,8 +736,7 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro core.setOutput('status', status) core.setOutput('created', created ? 'true' : 'false') core.setOutput('versions-url', versionsUrl) - // One item of the list the deploy's actions write to the job summary. Herald computes the hash - // of a ZIP it stores, so there is none to show for one it already held. + // One item of the list the deploy's actions write to the job summary. const lines = [ `- **Herald:** ${markdownLink(`${product} ${version}`, versionsUrl)} is ${status}, version ${created ? 'created' : 'updated'}.`, ` - ZIP: ${uploaded.id}`, diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index 91122352..360b9c76 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -2,6 +2,7 @@ const { describe, it } = require('node:test') const assert = require('node:assert') +const crypto = require('node:crypto') const fs = require('node:fs') const os = require('node:os') const path = require('node:path') @@ -627,8 +628,9 @@ describe('herald-publish', () => { { method: 'GET', path: API.version, body: CREATED }, FRESH[3], ]) + const cwd = checkoutWith() - await runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }) + await runHeraldPublish({ core, env: publishEnv(), fetch, cwd, now: NOW }) // The draft a failed run left behind still has the header Herald wrote: it goes now. assert.deepStrictEqual(requests[2].body, { @@ -636,10 +638,12 @@ describe('herald-publish', () => { status: 'published', changelog: '* Fix - One thing.\n* New - Another thing.', }) - assert.deepStrictEqual(outputs(), { 'zip-id': ZIP_ID, sha256: '', status: 'published', created: 'false', 'versions-url': VERSIONS_URL }) - assert.match(logged(), /already holds give-gift-aid\.zip as 11111111.*reusing it/) - // Herald computes the hash of a ZIP it stores, and this one it already held. - assert.doesNotMatch(summary(), /SHA-256/) + // Herald answers with the id of the record and no hash. It found the record by the SHA-256 + // of the bytes, so the action shows the hash of the file it sent. + const sha256 = crypto.createHash('sha256').update(fs.readFileSync(path.join(cwd, 'give-gift-aid.zip'))).digest('hex') + assert.deepStrictEqual(outputs(), { 'zip-id': ZIP_ID, sha256, status: 'published', created: 'false', 'versions-url': VERSIONS_URL }) + assert.ok(logged().includes(`Herald already holds give-gift-aid.zip as ${ZIP_ID} (sha256 ${sha256}): reusing it.`)) + assert.ok(summary().includes(` - ZIP: ${ZIP_ID}\n - SHA-256: ${sha256}\n`)) }) }) From d7d6ffac85b7c12f9464b7745d67170ade04dd35 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 17:00:41 -0300 Subject: [PATCH 41/45] herald-publish: read the version with the shared rule The action had its own copy of the check in lib/versions.js: the same trim, the same test for an empty value and the same pattern. It now calls the shared function with its own closing line, as release-merge and release-publish do. The shared message gave the tag of the GitHub release as the reason for the shape. It now gives a reason that holds for Herald too. SOFT-5788 --- .../actions/herald-publish/herald-publish.js | 19 +++---------------- .github/lib/versions.js | 11 ++++++----- .../herald-publish/herald-publish.test.js | 14 ++++++++++++-- 3 files changed, 21 insertions(+), 23 deletions(-) diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index fa7996e5..6366e42e 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -27,7 +27,7 @@ const zlib = require('node:zlib') const { markdownLink } = require('../../lib/github.js') const { lines: nonEmptyLines } = require('../../lib/inputs.js') -const { STELLARWP_VERSION_PATTERN } = require('../../lib/versions.js') +const { validateVersion: validateReleaseVersion } = require('../../lib/versions.js') /** Closes every error message raised with nothing of this run written to Herald. */ const NOTHING = 'Nothing was published to Herald.' @@ -55,7 +55,7 @@ const HEADER_BYTES = 8192 const MAIN_FILE_LIMIT = 5 * 1024 * 1024 /** - * Reads the version to publish: three or four numeric parts, the shape every release has. + * Reads the version to publish: the shared rule, with this action's closing line. * * @param {string} version The `version` input. * @@ -64,20 +64,7 @@ const MAIN_FILE_LIMIT = 5 * 1024 * 1024 * @returns {string} The version, without surrounding whitespace. */ function validateVersion(version) { - const trimmed = String(version ?? '').trim() - - if (trimmed === '') { - throw new Error(`No version was given: pass the version being released. ${NOTHING}`) - } - - if (!STELLARWP_VERSION_PATTERN.test(trimmed)) { - throw new Error( - `'${trimmed}' is not a version Herald gets from this action. The action takes three or four numeric parts, ` + - `such as 4.17.0 or 4.17.0.1, with no pre-release suffix and no leading v. ${NOTHING}` - ) - } - - return trimmed + return validateReleaseVersion(version, NOTHING) } /** diff --git a/.github/lib/versions.js b/.github/lib/versions.js index 5780ee9c..a4e1a64b 100644 --- a/.github/lib/versions.js +++ b/.github/lib/versions.js @@ -65,9 +65,10 @@ function compareVersions(a, b) { /** * Reads a version to release, refusing anything but three or four numeric parts. * - * A pre-release is refused: the version becomes the tag and the title of a published release, and a - * beta or RC is not released this way. The release dashboard validates versions with this rule, and - * release-prep does under the stellarwp changelog versioning. + * A pre-release is refused: the release is published under the version as it is written (the tag + * and the title of the GitHub release, the version in Herald), and a beta or RC is not released + * this way. The release dashboard validates versions with this rule, and release-prep does under + * the stellarwp changelog versioning. * * @param {string} version The `version` input. * @param {string} what What was not done, to close the message, e.g. `Nothing was merged.` @@ -89,8 +90,8 @@ function validateVersion(version, what) { if (!STELLARWP_VERSION_PATTERN.test(trimmed)) { throw new Error( `'${trimmed}' is not a version this action can release. It takes three or four numeric parts, ` + - 'such as 4.17.0 or 4.17.0.1: no pre-release suffix and no leading v, because the version ' + - `becomes the tag and the title of the published release. ${what}` + 'such as 4.17.0 or 4.17.0.1, with no pre-release suffix and no leading v: the release is ' + + `published under the version as it is written. ${what}` ) } diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index 360b9c76..217b6afd 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -444,8 +444,18 @@ describe('herald-publish', () => { }) it('refuses a version that is not three or four numeric parts', () => { - assert.throws(() => validateVersion('2.2.2-rc.1'), /is not a version Herald gets from this action\. The action takes three or four numeric parts.*Nothing was published to Herald/) - assert.throws(() => validateVersion(''), /No version was given/) + // The rule and its messages are the ones release-merge and release-publish use, closed by + // this action's own line. Nothing in them is about a tag: Herald has none. + assert.throws( + () => validateVersion('2.2.2-rc.1'), + (error) => { + assert.match(error.message, /'2\.2\.2-rc\.1' is not a version this action can release\. It takes three or four numeric parts.*Nothing was published to Herald\.$/) + assert.doesNotMatch(error.message, /\btag\b/) + + return true + } + ) + assert.throws(() => validateVersion(''), /No version was given.*Nothing was published to Herald\.$/) assert.strictEqual(validateVersion(' 2.2.2.1 '), '2.2.2.1') }) From 947f13de18624d47bec612011577031c23715f68 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 17:01:38 -0300 Subject: [PATCH 42/45] herald-publish: the create, the corrections and the update are functions of their own runHeraldPublish held every step of the run. Three of them move out: creating the version, with the read after another run created it first, the corrections to the changelog and the release date, and the update with the check of Herald's answer. No message and no call changes: the tests run as they were. SOFT-5788 --- .../actions/herald-publish/herald-publish.js | 236 ++++++++++++------ 1 file changed, 154 insertions(+), 82 deletions(-) diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index 6366e42e..c07dfc8a 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -559,6 +559,151 @@ async function uploadZip({ fetch, base, apiKey, zip }) { throw new Error(`Uploading ${zip.name} to Herald failed (${failure(answer)}). ${left}`) } +/** + * Closes the error of a run that left the ZIP in Herald and changed no version. + * + * @param {string} id The id of the ZIP record. + * @param {string} product The product's slug. + * + * @returns {string} The sentence. + */ +function stored(id, product) { + return `The ZIP is in Herald as ${id}, and no version of ${product} was changed.` +} + +/** + * Creates the version, pointing at the ZIP. Herald creates it as a draft. + * + * Two runs for one version can both find it missing. The create of the second is refused, and + * that run reads the version the first one created. + * + * @param {object} options + * @param {object} options.core The @actions/core toolkit, for the warning. + * @param {Function} options.fetch The fetch to use. + * @param {string} options.apiKey The Herald key. + * @param {string} options.versions The address of the product's versions. + * @param {string} options.versionUrl The address of this version. + * @param {string} options.product The product's slug. + * @param {string} options.version The version. + * @param {object} options.uploaded What `uploadZip` returned. + * + * @throws {Error} When Herald does not create the version, for any reason but that it exists. + * + * @returns {Promise<{current: object|null, created: boolean}>} What Herald holds for the version, + * and whether this run created it. `current` is null when another run created the version + * and reading it failed. + */ +async function createVersion({ core, fetch, apiKey, versions, versionUrl, product, version, uploaded }) { + // Only the version and the ZIP: Herald fills the changelog and the release date from the entry + // of this version in the ZIP's changelog.txt or readme.txt, and a date sent here would replace + // that one. + const answer = await send({ fetch, url: versions, method: 'POST', apiKey, json: { version, zip_id: uploaded.id } }) + + if (answer.status === 201) { + return { current: answer.data, created: true } + } + + // Two runs for one version: the other created it between the read and this call. + const raced = answer.status === 400 && /already exists/i.test(answer.reason) + if (!raced) { + const left = unconfirmed(answer) + ? `Herald may have created the version anyway: run it again, and a version found there is updated. The ZIP is in Herald as ${uploaded.id}.` + : stored(uploaded.id, product) + throw new Error(`Creating ${product} ${version} in Herald failed (${failure(answer)}). ${left}`) + } + + // The other run may stop before its own update, so this one reads what was created and makes + // the same corrections to the changelog and the release date. The update decides the outcome + // either way, so a read that fails here does not stop the run: it warns that the corrections + // were not made. + const again = await send({ fetch, url: versionUrl, apiKey }) + if (again.status === 200) { + return { current: again.data, created: false } + } + + core.warning( + `Another run created ${product} ${version}, and reading it failed (${failure(again)}). ` + + 'Its changelog header and release date were not corrected: check them in Herald.' + ) + + return { current: null, created: false } +} + +/** + * The changelog and the release date to send with the update, when either needs a change. + * + * The changelog field takes entries only. Without a file, the header Herald wrote above the + * entries it read from the ZIP goes; a changelog with no header is left alone. A version with no + * release date gets today's, in UTC. + * + * @param {object} options + * @param {object} options.core The @actions/core toolkit, for the log. + * @param {string|null} options.changelog What `readChangelogFile` returned. + * @param {object|null} options.current What Herald holds for the version, or null when unknown. + * @param {Date} options.now The current time. + * + * @returns {{changelog?: string, release_date?: string}} The fields to change. Empty when neither + * needs a change. + */ +function corrections({ core, changelog, current, now }) { + const entries = changelog ?? entriesOnly(current?.changelog) + if (changelog === null && entries !== null) { + core.info('Took the version header out of the changelog Herald read from the ZIP.') + } + const undated = current !== null && !current?.release_date + + return { + ...(entries === null ? {} : { changelog: entries }), + ...(undated ? { release_date: `${now.toISOString().slice(0, 10)}T00:00:00Z` } : {}), + } +} + +/** + * Updates the version in one call and checks what Herald answers. + * + * One call for the ZIP, the status and the rest: Herald writes them together, so a refused update + * never leaves the version published with the old ZIP. + * + * @param {object} options + * @param {Function} options.fetch The fetch to use. + * @param {string} options.apiKey The Herald key. + * @param {string} options.versionUrl The address of this version. + * @param {string} options.product The product's slug. + * @param {string} options.version The version. + * @param {object} options.fields What to send: the ZIP, the status and the corrections. + * @param {object} options.uploaded What `uploadZip` returned. + * @param {boolean} options.created Whether this run created the version. + * + * @throws {Error} When Herald does not apply the update, or its answer shows another status or + * another ZIP. The message says what Herald holds. + * + * @returns {Promise} Resolves once Herald's answer shows the status and the ZIP sent. + */ +async function updateVersion({ fetch, apiKey, versionUrl, product, version, fields, uploaded, created }) { + const { status } = fields + const answer = await send({ fetch, url: versionUrl, method: 'PATCH', apiKey, json: fields }) + + if (answer.status !== 200) { + // A ZIP Herald already held may have a version pointing at it, this one included. + let left = `The version is as it was. The ZIP ${uploaded.id} is in Herald${uploaded.reused ? '' : ', with no version pointing at it'}.` + if (unconfirmed(answer)) { + left = `Herald did not confirm the update, so the version may or may not be ${status} with the ZIP ${uploaded.id}. Run it again: the version is updated, not created twice.` + } else if (created) { + left = `The version was created as a draft with the ZIP ${uploaded.id} and is still that draft: the update was not applied.` + } + + throw new Error(`Updating ${product} ${version} in Herald failed (${failure(answer)}). ${left}`) + } + + // A 200 is not the proof: the answer has to show the status and the ZIP that were asked for. + if (answer.data?.status !== status || answer.data?.zip_id !== uploaded.id) { + throw new Error( + `Herald answered the update of ${product} ${version} with status '${answer.data?.status}' and the ZIP ` + + `${answer.data?.zip_id}, not '${status}' and ${uploaded.id}. Check the version in Herald before running it again.` + ) + } +} + /** * Publishes the ZIP as a version of the product. * @@ -610,7 +755,6 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro } const uploaded = await uploadZip({ fetch, base, apiKey, zip }) - const stored = `The ZIP is in Herald as ${uploaded.id}, and no version of ${product} was changed.` core.info( uploaded.reused ? `Herald already holds ${zip.name} as ${uploaded.id} (sha256 ${uploaded.sha256}): reusing it.` @@ -624,7 +768,7 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro if (zipVersion !== '' && zipVersion !== version) { throw new Error( `${zip.name} is version ${zipVersion} (${uploaded.meta.main_file ?? 'main file unknown'}), ` + - `not ${version}, so it was not published. ${stored}` + `not ${version}, so it was not published. ${stored(uploaded.id, product)}` ) } @@ -632,87 +776,15 @@ async function runHeraldPublish({ core, env, fetch = globalThis.fetch, cwd = pro core.warning(`The version inside ${zip.name} could not be read, so it was not compared with ${version}.`) } - // What Herald holds for the version: read above, answered by the create below, or read again - // after another run created it. Null only when that last read fails. - let current = found.status === 200 ? found.data : null - let created = false - if (found.status === 404) { - // Only the version and the ZIP: Herald fills the changelog and the release date from the entry - // of this version in the ZIP's changelog.txt or readme.txt, and a date sent here would replace - // that one. - const answer = await send({ fetch, url: versions, method: 'POST', apiKey, json: { version, zip_id: uploaded.id } }) - - // Two runs for one version: the other created it between the read and this call. - const raced = answer.status === 400 && /already exists/i.test(answer.reason) - if (answer.status !== 201 && !raced) { - const left = unconfirmed(answer) - ? `Herald may have created the version anyway: run it again, and a version found there is updated. The ZIP is in Herald as ${uploaded.id}.` - : stored - throw new Error(`Creating ${product} ${version} in Herald failed (${failure(answer)}). ${left}`) - } - - created = answer.status === 201 - current = created ? answer.data : null - - // The other run may stop before its own update, so this one reads what was created and makes - // the same corrections to the changelog and the release date. The update decides the outcome - // either way, so a read that fails here does not stop the run: it warns that the corrections - // were not made. - if (raced) { - const again = await send({ fetch, url: versionUrl, apiKey }) - current = again.status === 200 ? again.data : null - - if (current === null) { - core.warning( - `Another run created ${product} ${version}, and reading it failed (${failure(again)}). ` + - 'Its changelog header and release date were not corrected: check them in Herald.' - ) - } - } - } - - // The changelog field takes entries only. Without a file, the header Herald wrote above the - // entries it read from the ZIP goes; a changelog with no header is left alone. - const entries = changelog ?? entriesOnly(current?.changelog) - if (changelog === null && entries !== null) { - core.info('Took the version header out of the changelog Herald read from the ZIP.') - } - const undated = current !== null && !current?.release_date - - // One call for the ZIP, the status and the rest: Herald writes them together, so a refused - // update never leaves the version published with the old ZIP. - const answer = await send({ - fetch, - url: versionUrl, - method: 'PATCH', - apiKey, - json: { - zip_id: uploaded.id, - status, - ...(entries === null ? {} : { changelog: entries }), - ...(undated ? { release_date: `${now.toISOString().slice(0, 10)}T00:00:00Z` } : {}), - }, - }) - - if (answer.status !== 200) { - // A ZIP Herald already held may have a version pointing at it, this one included. - let left = `The version is as it was. The ZIP ${uploaded.id} is in Herald${uploaded.reused ? '' : ', with no version pointing at it'}.` - if (unconfirmed(answer)) { - left = `Herald did not confirm the update, so the version may or may not be ${status} with the ZIP ${uploaded.id}. Run it again: the version is updated, not created twice.` - } else if (created) { - left = `The version was created as a draft with the ZIP ${uploaded.id} and is still that draft: the update was not applied.` - } - - throw new Error(`Updating ${product} ${version} in Herald failed (${failure(answer)}). ${left}`) - } + // What Herald holds for the version, and whether this run created it. `current` is null only + // when another run created the version and reading it failed. + const { current, created } = + found.status === 200 + ? { current: found.data, created: false } + : await createVersion({ core, fetch, apiKey, versions, versionUrl, product, version, uploaded }) - // A 200 is not the proof: the answer has to show the status and the ZIP that were asked for. - if (answer.data?.status !== status || answer.data?.zip_id !== uploaded.id) { - throw new Error( - `Herald answered the update of ${product} ${version} with status '${answer.data?.status}' and the ZIP ` + - `${answer.data?.zip_id}, not '${status}' and ${uploaded.id}. Check the version in Herald before running it again.` - ) - } + const fields = { zip_id: uploaded.id, status, ...corrections({ core, changelog, current, now }) } + await updateVersion({ fetch, apiKey, versionUrl, product, version, fields, uploaded, created }) // Herald has no page per version. The product's versions page lists them newest first. const versionsUrl = `${base}/admin/products/${encodeURIComponent(product)}/versions` From 435df23cf4f4a5a7c2f23da2a01e35ae6d1e3e43 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 17:03:09 -0300 Subject: [PATCH 43/45] The zip reader moves to lib/zip.js herald-publish.js held the code that walks a zip: the central directory, the local headers and the inflate. It is now lib/zip.js, with tests of its own, and the action keeps the rule for finding the main file and its version. The reader is the same code. zipFileStart takes the number of bytes to return, which was the action's constant. The tests of the zip shapes (an archive comment, sizes after the data, zip64) moved with it, and the zip writer of the tests is tests/support/zip.js. SOFT-5788 --- .../actions/herald-publish/herald-publish.js | 92 +--------------- .github/lib/zip.js | 103 ++++++++++++++++++ .../herald-publish/herald-publish.test.js | 91 +--------------- tests/lib/zip.test.js | 82 ++++++++++++++ tests/support/zip.js | 77 +++++++++++++ 5 files changed, 266 insertions(+), 179 deletions(-) create mode 100644 .github/lib/zip.js create mode 100644 tests/lib/zip.test.js create mode 100644 tests/support/zip.js diff --git a/.github/actions/herald-publish/herald-publish.js b/.github/actions/herald-publish/herald-publish.js index c07dfc8a..960411aa 100644 --- a/.github/actions/herald-publish/herald-publish.js +++ b/.github/actions/herald-publish/herald-publish.js @@ -23,11 +23,11 @@ const crypto = require('node:crypto') const fs = require('node:fs') const path = require('node:path') -const zlib = require('node:zlib') const { markdownLink } = require('../../lib/github.js') const { lines: nonEmptyLines } = require('../../lib/inputs.js') const { validateVersion: validateReleaseVersion } = require('../../lib/versions.js') +const { zipEntries, zipFileStart } = require('../../lib/zip.js') /** Closes every error message raised with nothing of this run written to Herald. */ const NOTHING = 'Nothing was published to Herald.' @@ -45,14 +45,8 @@ const REQUEST_TIMEOUT_MS = 30 * 1000 */ const DUPLICATE_ZIP = /a ZIP with this content already exists \(id: ([0-9a-f-]{36})\)/i -/** The signatures of the zip records the reader below walks. */ -const ZIP_END_OF_DIRECTORY = 0x06054b50 -const ZIP_DIRECTORY_ENTRY = 0x02014b50 -const ZIP_LOCAL_HEADER = 0x04034b50 - -/** How much of a file WordPress reads to find its header, and the most a main file may inflate to. */ +/** How much of a file WordPress reads to find its header. */ const HEADER_BYTES = 8192 -const MAIN_FILE_LIMIT = 5 * 1024 * 1024 /** * Reads the version to publish: the shared rule, with this action's closing line. @@ -245,86 +239,6 @@ function readChangelogFile(input, cwd) { return entries.join('\n') } -/** - * Lists the files of a zip from its central directory, the index at the end of the archive. - * - * @param {Buffer} zip The archive. - * - * @returns {Array<{name: string, method: number, size: number, offset: number}>|null} Each file's - * name, compression method, compressed size and the offset of its local header. Null when - * the bytes are not a zip this reader walks: no directory, or a zip64 archive. - */ -function zipEntries(zip) { - // The end record is the last 22 bytes, or sits before a comment of at most 65535. - let end = -1 - for (let at = zip.length - 22; at >= Math.max(0, zip.length - 22 - 0xffff); at--) { - if (zip.readUInt32LE(at) === ZIP_END_OF_DIRECTORY) { - end = at - break - } - } - - if (end === -1) { - return null - } - - const count = zip.readUInt16LE(end + 10) - let at = zip.readUInt32LE(end + 16) - if (count === 0xffff || at === 0xffffffff) { - return null - } - - const entries = [] - for (let index = 0; index < count; index++) { - if (at + 46 > zip.length || zip.readUInt32LE(at) !== ZIP_DIRECTORY_ENTRY) { - return null - } - - const nameLength = zip.readUInt16LE(at + 28) - entries.push({ - name: zip.toString('utf8', at + 46, at + 46 + nameLength), - method: zip.readUInt16LE(at + 10), - size: zip.readUInt32LE(at + 20), - offset: zip.readUInt32LE(at + 42), - }) - at += 46 + nameLength + zip.readUInt16LE(at + 30) + zip.readUInt16LE(at + 32) - } - - return entries -} - -/** - * Reads the first bytes of one file of a zip. - * - * @param {Buffer} zip The archive. - * @param {object} entry One of `zipEntries`. - * - * @returns {string|null} The start of the file as text, or null when it cannot be read: a method - * other than stored or deflated, or data that does not inflate. - */ -function zipFileStart(zip, entry) { - const at = entry.offset - if (at + 30 > zip.length || zip.readUInt32LE(at) !== ZIP_LOCAL_HEADER) { - return null - } - - const start = at + 30 + zip.readUInt16LE(at + 26) + zip.readUInt16LE(at + 28) - const data = zip.subarray(start, start + entry.size) - - // Stored (0) and deflated (8) are the two methods this reads. - if (entry.method !== 0 && entry.method !== 8) { - return null - } - - try { - const file = entry.method === 0 ? data : zlib.inflateRawSync(data, { maxOutputLength: MAIN_FILE_LIMIT }) - - return file.subarray(0, HEADER_BYTES).toString('utf8') - } catch { - return null - } -} - /** * Cleans the value of a header line the way WordPress does: the end of a comment or a closing PHP * tag on the same line is not part of it, so `2.2.2 ?>` reads as `2.2.2`. @@ -364,7 +278,7 @@ function readZipVersion(zip) { continue } - const start = zipFileStart(zip, entry) + const start = zipFileStart(zip, entry, HEADER_BYTES) const named = plugin ? /^[ \t/*#@]*Plugin Name:/im : /^[ \t/*#@]*Theme Name:/im if (start === null || !named.test(start)) { continue diff --git a/.github/lib/zip.js b/.github/lib/zip.js new file mode 100644 index 00000000..8066c8b2 --- /dev/null +++ b/.github/lib/zip.js @@ -0,0 +1,103 @@ +'use strict' + +/** + * Reading a zip from its bytes, shared by the toolbox actions. Loaded by a path relative to each + * action's directory, like versions.js. + * + * It reads what an action needs to look inside a build: the names of the files and the start of one + * of them. It does not read every zip. A zip64 archive and a file compressed with a method other + * than stored or deflated return null, and the caller decides what that means. + */ + +const zlib = require('node:zlib') + +/** The signatures of the zip records the reader walks. */ +const END_OF_DIRECTORY = 0x06054b50 +const DIRECTORY_ENTRY = 0x02014b50 +const LOCAL_HEADER = 0x04034b50 + +/** The most a file may inflate to before its start is taken. */ +const INFLATE_LIMIT = 5 * 1024 * 1024 + +/** + * Lists the files of a zip from its central directory, the index at the end of the archive. + * + * @param {Buffer} zip The archive. + * + * @returns {Array<{name: string, method: number, size: number, offset: number}>|null} Each file's + * name, compression method, compressed size and the offset of its local header. Null when + * the bytes are not a zip this reader walks: no directory, or a zip64 archive. + */ +function zipEntries(zip) { + // The end record is the last 22 bytes, or sits before a comment of at most 65535. + let end = -1 + for (let at = zip.length - 22; at >= Math.max(0, zip.length - 22 - 0xffff); at--) { + if (zip.readUInt32LE(at) === END_OF_DIRECTORY) { + end = at + break + } + } + + if (end === -1) { + return null + } + + const count = zip.readUInt16LE(end + 10) + let at = zip.readUInt32LE(end + 16) + if (count === 0xffff || at === 0xffffffff) { + return null + } + + const entries = [] + for (let index = 0; index < count; index++) { + if (at + 46 > zip.length || zip.readUInt32LE(at) !== DIRECTORY_ENTRY) { + return null + } + + const nameLength = zip.readUInt16LE(at + 28) + entries.push({ + name: zip.toString('utf8', at + 46, at + 46 + nameLength), + method: zip.readUInt16LE(at + 10), + size: zip.readUInt32LE(at + 20), + offset: zip.readUInt32LE(at + 42), + }) + at += 46 + nameLength + zip.readUInt16LE(at + 30) + zip.readUInt16LE(at + 32) + } + + return entries +} + +/** + * Reads the first bytes of one file of a zip. + * + * @param {Buffer} zip The archive. + * @param {object} entry One of `zipEntries`. + * @param {number} length How many bytes of the file to return. + * + * @returns {string|null} The start of the file as text, or null when it cannot be read: a method + * other than stored or deflated, or data that does not inflate. + */ +function zipFileStart(zip, entry, length) { + const at = entry.offset + if (at + 30 > zip.length || zip.readUInt32LE(at) !== LOCAL_HEADER) { + return null + } + + const start = at + 30 + zip.readUInt16LE(at + 26) + zip.readUInt16LE(at + 28) + const data = zip.subarray(start, start + entry.size) + + // Stored (0) and deflated (8) are the two methods this reads. + if (entry.method !== 0 && entry.method !== 8) { + return null + } + + try { + const file = entry.method === 0 ? data : zlib.inflateRawSync(data, { maxOutputLength: INFLATE_LIMIT }) + + return file.subarray(0, length).toString('utf8') + } catch { + return null + } +} + +module.exports = { zipEntries, zipFileStart } diff --git a/tests/actions/herald-publish/herald-publish.test.js b/tests/actions/herald-publish/herald-publish.test.js index 217b6afd..7a4d5b5b 100644 --- a/tests/actions/herald-publish/herald-publish.test.js +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -6,7 +6,6 @@ const crypto = require('node:crypto') const fs = require('node:fs') const os = require('node:os') const path = require('node:path') -const zlib = require('node:zlib') const { runHeraldPublish, @@ -21,6 +20,7 @@ const { readApiKey, } = require('../../../.github/actions/herald-publish/herald-publish.js') const { coreWithOutputs, recordingFetch } = require('../../support/actions.js') +const { zipOf } = require('../../support/zip.js') const BASE = 'https://herald.test' @@ -88,74 +88,6 @@ function publishEnv(overrides = {}) { } } -/** - * Builds a zip in memory, as `zip` writes it: a local header and the data per file, then the - * central directory and its end record. - * - * @param {object} files File contents by path inside the zip. - * @param {object} options - * @param {boolean} options.deflate Whether the files are compressed (method 8) or stored (method 0). - * @param {boolean} options.descriptors Whether the sizes come after the data, as a tool that writes - * to a stream leaves them: the local header holds zeros. - * @param {string} options.comment The archive comment, written after the end record. - * @param {number} options.method The compression method the headers name, when it is not the - * one the data was written with. - * - * @returns {Buffer} The zip. - */ -function zipOf(files, { deflate = true, descriptors = false, comment = '', method = deflate ? 8 : 0 } = {}) { - const locals = [] - const directory = [] - let offset = 0 - - for (const [name, contents] of Object.entries(files)) { - const raw = Buffer.from(contents) - const data = deflate ? zlib.deflateRawSync(raw) : raw - const file = Buffer.from(name) - - const local = Buffer.alloc(30) - local.writeUInt32LE(0x04034b50, 0) - local.writeUInt16LE(descriptors ? 8 : 0, 6) - local.writeUInt16LE(method, 8) - local.writeUInt32LE(descriptors ? 0 : data.length, 18) - local.writeUInt32LE(descriptors ? 0 : raw.length, 22) - local.writeUInt16LE(file.length, 26) - locals.push(local, file, data) - - const descriptor = Buffer.alloc(descriptors ? 16 : 0) - if (descriptors) { - descriptor.writeUInt32LE(0x08074b50, 0) - descriptor.writeUInt32LE(data.length, 8) - descriptor.writeUInt32LE(raw.length, 12) - locals.push(descriptor) - } - - const entry = Buffer.alloc(46) - entry.writeUInt32LE(0x02014b50, 0) - entry.writeUInt16LE(descriptors ? 8 : 0, 8) - entry.writeUInt16LE(method, 10) - entry.writeUInt32LE(data.length, 20) - entry.writeUInt32LE(raw.length, 24) - entry.writeUInt16LE(file.length, 28) - entry.writeUInt32LE(offset, 42) - directory.push(entry, file) - - offset += 30 + file.length + data.length + descriptor.length - } - - const central = Buffer.concat(directory) - const note = Buffer.from(comment) - const end = Buffer.alloc(22) - end.writeUInt32LE(0x06054b50, 0) - end.writeUInt16LE(Object.keys(files).length, 8) - end.writeUInt16LE(Object.keys(files).length, 10) - end.writeUInt32LE(central.length, 12) - end.writeUInt32LE(offset, 16) - end.writeUInt16LE(note.length, 20) - - return Buffer.concat([...locals, central, end, note]) -} - /** * The files of the plugin at a version: a readme, a `.php` beside the main file and one in a * folder, neither of them the plugin's, and the main file with its header. @@ -388,27 +320,6 @@ describe('herald-publish', () => { assert.deepStrictEqual(readZipVersion(stored), { file: 'my-plugin/my-plugin.php', version: '4.17.0.1' }) }) - it('reads the version of a zip with an archive comment, as git archive writes it', () => { - const commented = zipOf(pluginFiles('2.2.2'), { comment: '3870a4f0d1c2b3a4958677665544332211009988' }) - - assert.deepStrictEqual(readZipVersion(commented), { file: 'give-gift-aid/give-gift-aid.php', version: '2.2.2' }) - }) - - it('reads the version of a zip whose sizes come after the data, as a streamed zip has them', () => { - const streamed = zipOf(pluginFiles('2.2.2'), { descriptors: true }) - - assert.deepStrictEqual(readZipVersion(streamed), { file: 'give-gift-aid/give-gift-aid.php', version: '2.2.2' }) - }) - - it('reads no version from a zip64 archive', () => { - const zip64 = pluginZip('2.2.2') - // What `zip -fz` writes: the offset of the directory is in another record, and this marker - // takes its place in the end record. - zip64.writeUInt32LE(0xffffffff, zip64.length - 22 + 16) - - assert.strictEqual(readZipVersion(zip64), null) - }) - it('reads the version as WordPress does, without a comment that closes on the same line', () => { const closed = zipOf({ 'my-plugin/my-plugin.php': '\n' }) diff --git a/tests/lib/zip.test.js b/tests/lib/zip.test.js new file mode 100644 index 00000000..8b9f9e5b --- /dev/null +++ b/tests/lib/zip.test.js @@ -0,0 +1,82 @@ +'use strict' + +const { describe, it } = require('node:test') +const assert = require('node:assert') + +const { zipEntries, zipFileStart } = require('../../.github/lib/zip.js') +const { zipOf } = require('../support/zip.js') + +/** Two files, the second long enough to show where a read stops. */ +const FILES = { 'my-plugin/readme.txt': 'Stable tag: 4.17.0\n', 'my-plugin/my-plugin.php': ` [entry.name, zipFileStart(zip, entry, length)])) +} + +describe('zip', () => { + describe('zipEntries', () => { + it('lists the files in the order of the archive', () => { + assert.deepStrictEqual( + zipEntries(zipOf(FILES)).map((entry) => entry.name), + ['my-plugin/readme.txt', 'my-plugin/my-plugin.php'] + ) + }) + + it('finds the directory of a zip with an archive comment, as git archive writes it', () => { + const commented = zipOf(FILES, { comment: '3870a4f0d1c2b3a4958677665544332211009988' }) + + assert.deepStrictEqual(starts(commented), FILES) + }) + + it('lists nothing for bytes that are not a zip', () => { + assert.strictEqual(zipEntries(Buffer.from('PK\u0003\u0004 not a zip')), null) + assert.strictEqual(zipEntries(Buffer.alloc(0)), null) + }) + + it('lists nothing for a zip64 archive', () => { + const zip64 = zipOf(FILES) + // What `zip -fz` writes: the offset of the directory is in another record, and this marker + // takes its place in the end record. + zip64.writeUInt32LE(0xffffffff, zip64.length - 22 + 16) + + assert.strictEqual(zipEntries(zip64), null) + }) + }) + + describe('zipFileStart', () => { + it('reads a file that is compressed and one that is stored', () => { + assert.deepStrictEqual(starts(zipOf(FILES)), FILES) + assert.deepStrictEqual(starts(zipOf(FILES, { deflate: false })), FILES) + }) + + it('reads a file whose sizes come after the data, as a streamed zip has them', () => { + assert.deepStrictEqual(starts(zipOf(FILES, { descriptors: true })), FILES) + }) + + it('returns no more than the length asked for', () => { + assert.strictEqual(starts(zipOf(FILES), 5)['my-plugin/my-plugin.php'], ' { + // Under the method number of bzip2, neither the file as it is nor its deflated bytes are + // read: taking them as stored or as deflated would return the file. + assert.deepStrictEqual(Object.values(starts(zipOf(FILES, { deflate: false, method: 12 }))), [null, null]) + assert.deepStrictEqual(Object.values(starts(zipOf(FILES, { deflate: true, method: 12 }))), [null, null]) + }) + + it('reads nothing from data that does not inflate', () => { + // Stored bytes under the method number of deflate. + const broken = zipOf(FILES, { deflate: false, method: 8 }) + + assert.deepStrictEqual(Object.values(starts(broken)), [null, null]) + }) + }) +}) diff --git a/tests/support/zip.js b/tests/support/zip.js new file mode 100644 index 00000000..a9c7032b --- /dev/null +++ b/tests/support/zip.js @@ -0,0 +1,77 @@ +'use strict' + +/** + * Builds zips in memory for the tests of the actions that read one. + */ + +const zlib = require('node:zlib') + +/** + * Builds a zip in memory, as `zip` writes it: a local header and the data per file, then the + * central directory and its end record. + * + * @param {object} files File contents by path inside the zip. + * @param {object} options + * @param {boolean} options.deflate Whether the files are compressed (method 8) or stored (method 0). + * @param {boolean} options.descriptors Whether the sizes come after the data, as a tool that writes + * to a stream leaves them: the local header holds zeros. + * @param {string} options.comment The archive comment, written after the end record. + * @param {number} options.method The compression method the headers name, when it is not the + * one the data was written with. + * + * @returns {Buffer} The zip. + */ +function zipOf(files, { deflate = true, descriptors = false, comment = '', method = deflate ? 8 : 0 } = {}) { + const locals = [] + const directory = [] + let offset = 0 + + for (const [name, contents] of Object.entries(files)) { + const raw = Buffer.from(contents) + const data = deflate ? zlib.deflateRawSync(raw) : raw + const file = Buffer.from(name) + + const local = Buffer.alloc(30) + local.writeUInt32LE(0x04034b50, 0) + local.writeUInt16LE(descriptors ? 8 : 0, 6) + local.writeUInt16LE(method, 8) + local.writeUInt32LE(descriptors ? 0 : data.length, 18) + local.writeUInt32LE(descriptors ? 0 : raw.length, 22) + local.writeUInt16LE(file.length, 26) + locals.push(local, file, data) + + const descriptor = Buffer.alloc(descriptors ? 16 : 0) + if (descriptors) { + descriptor.writeUInt32LE(0x08074b50, 0) + descriptor.writeUInt32LE(data.length, 8) + descriptor.writeUInt32LE(raw.length, 12) + locals.push(descriptor) + } + + const entry = Buffer.alloc(46) + entry.writeUInt32LE(0x02014b50, 0) + entry.writeUInt16LE(descriptors ? 8 : 0, 8) + entry.writeUInt16LE(method, 10) + entry.writeUInt32LE(data.length, 20) + entry.writeUInt32LE(raw.length, 24) + entry.writeUInt16LE(file.length, 28) + entry.writeUInt32LE(offset, 42) + directory.push(entry, file) + + offset += 30 + file.length + data.length + descriptor.length + } + + const central = Buffer.concat(directory) + const note = Buffer.from(comment) + const end = Buffer.alloc(22) + end.writeUInt32LE(0x06054b50, 0) + end.writeUInt16LE(Object.keys(files).length, 8) + end.writeUInt16LE(Object.keys(files).length, 10) + end.writeUInt32LE(central.length, 12) + end.writeUInt32LE(offset, 16) + end.writeUInt16LE(note.length, 20) + + return Buffer.concat([...locals, central, end, note]) +} + +module.exports = { zipOf } From 1347af2c06c92ce1aaff73ae33c34e9edabefe32 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 17:08:12 -0300 Subject: [PATCH 44/45] herald-publish: a missing key fails the step in the example and the template The example of the README and the template skipped the Herald step when the HERALD_API_KEY secret was missing. A repository that added the step before it got the secret deployed with no error, published the GitHub release, and never reached Herald. A rerun did not fix it: the release existed by then, so the step was skipped again. The step now runs without that condition, and the action fails on the missing key before anything is sent. The condition stays in the README for a workflow shared by repositories that do and do not release to Herald. SOFT-5788 --- .github/actions/herald-publish/README.md | 40 ++++++++++++++++-------- templates/workflows/release.yml | 26 +++++++-------- 2 files changed, 38 insertions(+), 28 deletions(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index 21916042..726e4e35 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -25,7 +25,7 @@ In a deploy, the action runs after the build and before # build/my-plugin.zip. - uses: stellarwp/plugin-toolbox/.github/actions/herald-publish@v1 - if: env.HERALD_CONFIGURED == 'true' && steps.merge.outputs.already-published == 'no' + if: steps.merge.outputs.already-published == 'no' with: herald-url: https://herald.example.com product-slug: my-plugin @@ -74,22 +74,36 @@ Herald is set up once, and then each workflow gets the step. `gh secret set HERALD_API_KEY -R /`. 4. **Add the step to the deploy workflow,** as in the example above, with `herald-url`, `product-slug` and `zip`. -5. **Say in the job whether the key exists.** A step's `if` - [cannot read a secret](https://docs.github.com/en/actions/how-tos/write-workflows/choose-what-workflows-do/use-secrets#using-secrets-in-a-workflow), - so the job sets a value the step's `if` reads: - - ```yaml - jobs: - release: - env: - HERALD_CONFIGURED: ${{ secrets.HERALD_API_KEY != '' }} - ``` - -A repository the secret does not reach skips the step, and the rest of the deploy runs. +If the repository does not have the secret, the step fails with `No api-key was given`. It fails +before anything is sent to Herald and before the GitHub release is published. Add the secret and +run the deploy again. To try the step out before a real release, use a staging Herald: its address in `herald-url`, a key created there, and a product made for the test. A key works only in the instance that created it. +### A workflow shared by several repositories + +A reusable workflow can serve repositories that release to Herald and repositories that do not. +In such a workflow, the step has to be skipped in a repository that has no secret. A step's `if` +[cannot read a secret](https://docs.github.com/en/actions/how-tos/write-workflows/choose-what-workflows-do/use-secrets#using-secrets-in-a-workflow), +so the job sets a value that the step's `if` reads: + +```yaml +jobs: + release: + env: + HERALD_CONFIGURED: ${{ secrets.HERALD_API_KEY != '' }} + steps: + - uses: stellarwp/plugin-toolbox/.github/actions/herald-publish@v1 + if: env.HERALD_CONFIGURED == 'true' && steps.merge.outputs.already-published == 'no' +``` + +Use `HERALD_CONFIGURED` only in a shared workflow, and check that every repository that releases +to Herald has the secret. With it, a repository without the secret deploys with no error and its +release never reaches Herald. Adding the secret and running the deploy again does not send it +either: the GitHub release exists by then, so `already-published == 'no'` is false and the step is +skipped. Someone then has to upload the ZIP in the Herald dashboard. + ## What it does 1. Checks every input before any call. diff --git a/templates/workflows/release.yml b/templates/workflows/release.yml index 375af327..352ab0fa 100644 --- a/templates/workflows/release.yml +++ b/templates/workflows/release.yml @@ -50,10 +50,6 @@ jobs: environment: live permissions: contents: write # release-merge writes the merges, release-publish creates the tag and the release - # For the herald-publish step below: the secrets context is not available in a step's `if`, so - # whether the Herald key exists is decided here. - # env: - # HERALD_CONFIGURED: ${{ secrets.HERALD_API_KEY != '' }} steps: # The environment's branch policy protects the branch the run was started on, not the input. # The two have to be the same branch, so the policy covers what is actually merged and @@ -88,20 +84,20 @@ jobs: persist-credentials: false # For a product sold through Herald: upload the build and publish the version there before the - # GitHub release, so a failed upload leaves no release behind. The step goes after the one - # that builds the ZIP, and `zip` is the path of that file in the checkout, the same one - # release-publish gets in `files`. + # GitHub release. If the upload fails, the deploy stops and no GitHub release is published. + # Put the step after the one that builds the ZIP. `zip` is the path of that file in the + # checkout, the same file that release-publish gets in `files`. # - # The key is the HERALD_API_KEY secret, of the organization or of the environment above. The - # condition runs the step only where that secret exists. It also skips the rerun of a version - # already published, which would replace a ZIP customers are downloading. It needs the - # HERALD_CONFIGURED line of the job's `env` above. + # The key is the HERALD_API_KEY secret, of the organization or of the environment above. + # Without the secret, the step fails before anything is sent to Herald. # - # `already-published` is about the GitHub release only. When this step passed and a later - # one failed, the rerun runs it again: the same ZIP when the build comes out identical, - # another ZIP for the version when it does not. + # The condition skips the rerun of a version whose GitHub release is already published. That + # rerun would replace a ZIP that customers are downloading. `already-published` is about the + # GitHub release only: if this step passed and a later step failed, the rerun runs this step + # again. It uploads the same ZIP if the build comes out identical, and another ZIP for the + # version if it does not. # - uses: stellarwp/plugin-toolbox/.github/actions/herald-publish@v1 - # if: env.HERALD_CONFIGURED == 'true' && steps.merge.outputs.already-published == 'no' + # if: steps.merge.outputs.already-published == 'no' # with: # herald-url: https://herald.example.com # product-slug: my-plugin From c8fb53ff3a75cddeccf5a0321166f949ba2ed0a7 Mon Sep 17 00:00:00 2001 From: Glauber Silva Date: Tue, 1 Dec 2026 17:08:12 -0300 Subject: [PATCH 45/45] herald-publish README: plainer steps, links by branch, the Portal refresh What it does is rewritten step by step: each step says who acts and what fails, and "version" says which one it is (the input, the header in the ZIP or the version in Herald). The rest of the README follows the same rules. The links to Herald and the Portal point at the default branch and name the function, instead of a commit and a line range. The Portal step now refreshes one product instead of Sync All. Sync All fills the Portal's five-minute cache of every product's versions, so a release that reaches Herald inside that time is read from the cache. SOFT-5788 --- .github/actions/herald-publish/README.md | 302 +++++++++++++---------- 1 file changed, 165 insertions(+), 137 deletions(-) diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md index 726e4e35..da020657 100644 --- a/.github/actions/herald-publish/README.md +++ b/.github/actions/herald-publish/README.md @@ -1,14 +1,15 @@ # herald-publish Publishes a plugin ZIP to [Herald](https://github.com/stellarwp/herald), the service customers -download paid plugins from. It uploads the ZIP and creates the version when the product does not -have it yet. It then points the version at the ZIP and sets its status. +download paid plugins from. The action uploads the ZIP. If the product does not have the version +yet, the action creates the version. Then it sets the ZIP and the status of the version. -It is what a person does by hand in the Herald dashboard for a paid release. They click New Version, +A person does the same by hand in the Herald dashboard for a paid release. They click New Version, upload the ZIP, check the changelog and the release date, create the version and publish it. -In a deploy, the action runs after the build and before -[release-publish](../release-publish/README.md), so a failed upload leaves no GitHub release behind: +In a deploy (the workflow run that releases a version), run the action after the build and before +[release-publish](../release-publish/README.md). If the upload to Herald fails, the deploy stops +before the GitHub release is published: ```yaml - uses: stellarwp/plugin-toolbox/.github/actions/release-merge@v1 @@ -41,45 +42,47 @@ In a deploy, the action runs after the build and before build/my-plugin.zip ``` -Each workflow sets three of these values for itself: +Three of the inputs are different in each workflow: - `herald-url` is the address of the Herald instance. The action has no default for it: the workflow says where the release goes. -- `product-slug` is the slug of the product in Herald, which is not always the repository's name. - The product has to exist: the action creates versions, never products. -- `zip` is the path of the ZIP the build step wrote, from the root of the checkout. The action - builds nothing and looks for no file. `build/my-plugin.zip` is the path of this example: pass the - one your build writes, the same file release-publish gets in `files`. +- `product-slug` is the slug of the product in Herald. It is not always the repository's name. The + product must already exist: the action creates versions, never products. +- `zip` is the path of the ZIP that the build step wrote, from the root of the checkout. The action + builds nothing and searches for no file. `build/my-plugin.zip` is only the path in this example. + Pass the path your build writes, which is the same file that release-publish gets in `files`. ## Setting it up -Herald is set up once, and then each workflow gets the step. +Herald needs the product and a key before the step can run. -1. **The product exists in Herald.** On the Products page, check the slug under the product's name, - or create the product. That slug is the `product-slug` input. Creating a product - [needs the contributor role](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/crates/herald-server/src/routes/products.rs#L118-L123) - or above. +1. **Check that the product exists in Herald.** On the Products page, the slug is under the + product's name. That slug is the `product-slug` input. If the product is missing, create it. + Creating a product needs the contributor role or above (`create_product` in + [`products.rs`](https://github.com/stellarwp/herald/blob/main/crates/herald-server/src/routes/products.rs)). 2. **Create a key of scope `ci`.** In Herald, open API Keys, click New API Key and choose the CI scope. Copy the key: Herald - [shows it once](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/docs/github-actions.md#1-create-a-ci-api-key). - Only an administrator of the Herald instance - [sees API Keys](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/dashboard/components/layout/sidebar.tsx#L51). + [shows it only once](https://github.com/stellarwp/herald/blob/main/docs/github-actions.md#1-create-a-ci-api-key). + Only an administrator of the Herald instance sees API Keys + ([`sidebar.tsx`](https://github.com/stellarwp/herald/blob/main/dashboard/components/layout/sidebar.tsx)). 3. **Store the key as the `HERALD_API_KEY` secret.** - - **For an organization,** which is how a production key is meant to be kept. An organization + - **For an organization**, which is how a production key is meant to be kept. An organization owner opens the organization's Settings → Secrets and variables → Actions → New organization - secret, and chooses the repositories that release to Herald. With the CLI: + secret, and selects the repositories that release to Herald. With the CLI: `gh secret set HERALD_API_KEY --org --visibility selected --repos ,`. - - **For one repository,** to try the step out. Open its Settings → Secrets and variables → + - **For one repository**, to try the step out. Open its Settings → Secrets and variables → Actions → New repository secret. With the CLI: `gh secret set HERALD_API_KEY -R /`. -4. **Add the step to the deploy workflow,** as in the example above, with `herald-url`, +4. **Add the step to the deploy workflow**, as in the example above, with `herald-url`, `product-slug` and `zip`. + If the repository does not have the secret, the step fails with `No api-key was given`. It fails before anything is sent to Herald and before the GitHub release is published. Add the secret and run the deploy again. -To try the step out before a real release, use a staging Herald: its address in `herald-url`, a key -created there, and a product made for the test. A key works only in the instance that created it. +To try the step before a real release, use a staging Herald. Put its address in `herald-url`, +create a key there, and create a product for the test. A key works only in the Herald instance that +created it. ### A workflow shared by several repositories @@ -106,56 +109,70 @@ skipped. Someone then has to upload the ZIP in the Herald dashboard. ## What it does -1. Checks every input before any call. -2. Reads the version in the plugin header inside the ZIP and compares it with `version`. A ZIP of - another version, or of another plugin on another version, stops here, before anything is sent. -3. Reads the version of the product (`GET /api/v1/products/{product-slug}/versions/{version}`). A key - Herald refuses and a product it does not have stop here too, with no ZIP left in Herald. -4. Uploads the ZIP (`POST /api/v1/zips/upload`). Herald stores it and computes its SHA-256. -5. Creates the version when it is missing (`POST /api/v1/products/{product-slug}/versions`). A new - version is - [always a draft](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/docs/github-actions.md#notes). -6. Updates the version in one call, a `PATCH` on the address of step 3. It sends the ZIP, the status - and, when they need a change, the changelog and the release date. Herald - [writes them together](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/crates/herald-server/src/routes/versions.rs#L316-L334), - so a refused update never leaves the version published with the old ZIP. -7. Checks that Herald's answer shows the status and the ZIP it asked for, and fails when it does - not. - -The run log and the job summary show the ZIP id, its SHA-256 and a link to the product's versions in -the Herald dashboard. Herald has no page per version; that page lists them newest first. - -The version of step 2 is read where -[WordPress finds it](https://developer.wordpress.org/plugins/plugin-basics/header-requirements/). -That is a `.php` right inside the top folder with a `Plugin Name` header, or the `style.css` of a -theme. - -When the action cannot read that version, it compares the one Herald read from the ZIP in step 4. -When Herald read none either, the run goes on with a warning. +1. Checks the inputs. A missing or malformed input fails the step before anything is sent to + Herald. +2. Opens the ZIP and reads the `Version:` header of the plugin's main file. If the header does not + match the `version` input, the step fails before anything is sent to Herald. +3. Looks up the version in Herald (`GET /api/v1/products/{product-slug}/versions/{version}`). A bad + API key or an unknown product slug fails here, before the ZIP is uploaded. +4. Uploads the ZIP (`POST /api/v1/zips/upload`). If Herald already has a ZIP with the same + contents, Herald refuses the upload and names that ZIP, and the step uses it. +5. Creates the version in Herald if it does not exist yet + (`POST /api/v1/products/{product-slug}/versions`). Herald + [creates new versions as drafts](https://github.com/stellarwp/herald/blob/main/docs/github-actions.md#notes). +6. Updates the version with one `PATCH` to the address from step 3. The `PATCH` sends the ZIP id, + the status and, when needed, the changelog and the release date. Herald saves these fields + together (`update_version` in + [`routes/versions.rs`](https://github.com/stellarwp/herald/blob/main/crates/herald-server/src/routes/versions.rs)). + So when Herald refuses the update, nothing in the version changes: an existing version keeps its + ZIP and status, and a new version stays a draft. +7. Checks Herald's response to the `PATCH`. If the response shows another status or another ZIP, + the step fails. + +The run log and the job summary show the ZIP id, the SHA-256 of the ZIP and a link to the product's +versions page in the Herald dashboard. Herald has no page for a single version. The versions page +lists the versions of the product, newest first. + +In step 2, the main file is the file +[WordPress reads the header from](https://developer.wordpress.org/plugins/plugin-basics/header-requirements/): +a `.php` file directly inside the top folder that has a `Plugin Name` header. For a theme, it is +the `style.css` in the top folder. + +If the action cannot read the `Version:` header in step 2, it compares the `version` input with +the `Version:` header that Herald read from the ZIP in step 4. If they differ, the step fails. The +ZIP is in Herald by then, and no version was changed. If Herald read no `Version:` header either, +the run continues with a warning. ## The changelog and the release date -Herald -[fills both](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/crates/herald-core/src/repo/versions.rs#L694-L718) -for a new version, from the entry of that version in the ZIP. It reads the entry in `changelog.txt` -when the ZIP has one with version headers such as `= 4.17.0 =`. Otherwise it reads -[the Changelog section of `readme.txt`](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/crates/herald-core/src/zip/meta.rs#L315-L320). - -The action sends neither when it creates the version, and then makes two corrections: - -- **The changelog.** Herald - [writes the entry with a header line above it](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/crates/herald-core/src/zip/meta.rs#L665-L687), - such as `= 4.17.0 | 2026-11-25 =`. The changelog field takes entries only: Herald's own check - [reports a version header in it as an error](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/crates/herald-core/src/changelog/validate.rs#L72-L78). - The action takes the header line out and keeps the entries. An entry with nothing under its header - leaves the changelog empty. -- **The release date.** A version Herald found no date for gets today's date in UTC. - -A changelog with no header line, and a version that already has a date, are left as they are. - -To send another changelog, pass `changelog-file`: a file with the entries of this version, one per -line, each starting with `* `, with no version and no date. The action refuses a file with a line -that is not an entry. +When Herald creates a version, it fills the changelog and the release date from the ZIP +(`fill_from_zip_meta` in +[`repo/versions.rs`](https://github.com/stellarwp/herald/blob/main/crates/herald-core/src/repo/versions.rs)). +Herald takes them from the block of that version in `changelog.txt`, if the ZIP has that file with +version lines such as `= 4.17.0 =`. Otherwise Herald takes them from the Changelog section of +`readme.txt` (`enrich_with_readme` in +[`zip/meta.rs`](https://github.com/stellarwp/herald/blob/main/crates/herald-core/src/zip/meta.rs)). + +So the action sends no changelog and no release date when it creates the version. In the update of +step 6, the action corrects two things in what Herald filled: + +- **The changelog.** Herald writes a version line above the entries, such as + `= 4.17.0 | 2026-11-25 =` (`format_changelog_entries` in + [`zip/meta.rs`](https://github.com/stellarwp/herald/blob/main/crates/herald-core/src/zip/meta.rs)). + The changelog field is meant to hold entries only: Herald's own check reports a version line in + it as an error (`validate` in + [`changelog/validate.rs`](https://github.com/stellarwp/herald/blob/main/crates/herald-core/src/changelog/validate.rs)). + The action removes the version line and keeps the entries. If nothing is under the version line, + the action leaves the changelog empty. +- **The release date.** If Herald found no release date for the version, the action sets today's + date in UTC. + +A changelog with no version line stays as it is. So does a release date that the version already +has. + +To send a different changelog, pass `changelog-file`: a file with the entries of this version, one +per line. Each line starts with `* `, and the file has no version line and no date. If a line of +the file is not an entry, the step fails before anything is sent to Herald. ```text * Fix - Resolved an error when the fee is disabled for the gateway. @@ -163,8 +180,8 @@ that is not an entry. ``` A repository that writes its changelog with the -[changelogger](https://github.com/stellarwp/changelogger) can get that file from it. The command -prints the entries of one version, without the header: +[changelogger](https://github.com/stellarwp/changelogger) can get that file from it. This command +prints the entries of one version, without the version line: ```yaml - name: Write the changelog entries of this version to a file @@ -173,26 +190,26 @@ prints the entries of one version, without the header: run: npx @stellarwp/changelogger get-changelog-contents --version="$VERSION" > herald-changelog.txt ``` -Write the version with `=`. With a space (`--version 4.17.0`), the command prints the changelogger's -own version instead of the entries. +Write the option with `=`, as `--version=4.17.0`. With a space (`--version 4.17.0`), the command +prints the version of the changelogger itself instead of the entries. ## Inputs | Input | Required | Default | What it is | |---|---|---|---| -| `herald-url` | yes | | The address of the Herald instance to publish to. HTTPS, or plain HTTP for a Herald on the same machine. | +| `herald-url` | yes | | The address of the Herald instance to publish to. HTTPS, or plain HTTP for a Herald that runs on the runner itself (`localhost`). | | `product-slug` | yes | | The slug of the product in Herald. | -| `version` | yes | | The version being released: three or four numeric parts. | +| `version` | yes | | The version being released: three or four numeric parts, such as `4.17.0` or `4.17.0.1`, with no pre-release suffix. | | `zip` | yes | | The build to upload, a `.zip` path relative to the checkout. A step before this one builds it. | -| `status` | no | `published` | `draft`, `review` or `published`. Only a published version is served to customers. | -| `changelog-file` | no | | A file with the entries of this version. Empty keeps what Herald read from the ZIP, without the header. | +| `status` | no | `published` | The status to leave the version in: `draft`, `review` or `published`. Herald serves only a published version to customers. | +| `changelog-file` | no | | A file with the entries of this version. When empty, the version keeps the entries Herald read from the ZIP, without the version line. | | `api-key` | yes | | A Herald API key of scope `ci`, from a secret. | ## Outputs | Output | What it is | |---|---| -| `zip-id` | The id of the ZIP record in Herald. | +| `zip-id` | The id of the ZIP in Herald. | | `sha256` | The SHA-256 of the ZIP. Herald computes it for a ZIP it stores. For a ZIP Herald already held, the action computes it from the file. | | `status` | The status the version was left in. | | `created` | `true` when the version was created, `false` when it existed and was updated. | @@ -200,83 +217,94 @@ own version instead of the entries. ## Running it again -A run can be repeated after a late failure, for the same version: - -- **The version exists.** It is updated to point at the ZIP of this run. No second version is - created. Its changelog and release date stay as they are: Herald reads them from the ZIP - [only when it creates the version](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/crates/herald-server/src/routes/versions.rs#L198-L218). - To change the changelog of a version that exists, pass `changelog-file`. -- **The build came out identical.** Herald - [refuses bytes it already stores](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/crates/herald-server/src/routes/zip_upload.rs#L73-L79) - and names the record in the refusal. The action takes that id and goes on. The refusal has no - hash, so the action shows the SHA-256 of the file. Herald found the record by that hash, so it is - the same one, unless the ZIP has macOS files (`__MACOSX/`, `.DS_Store`): Herald removes those - before it computes the hash. -- **Another run created the version in between.** The create is refused as a duplicate. The action - reads the version the other run created and goes on to the update. When that read fails, the - update still runs, with a warning that the changelog header and the release date were not - corrected. - -When a call to Herald fails, the error says what Herald holds at that point. That is nothing, the ZIP -with no version changed, or a new version left as a draft. - -Only a refusal from Herald (an HTTP 4xx) shows that a write was not applied. When Herald did not -answer a write, or answered with a server error, the error says that what Herald holds is not known. +The action can run again for the same version, for example after a later step of the deploy +failed: + +- **If the version exists in Herald**, the action updates it to use the ZIP of this run. It does + not create a second version. Herald does not read the changelog and the release date from the ZIP + again: it does that only when it creates the version (`create_version` in + [`routes/versions.rs`](https://github.com/stellarwp/herald/blob/main/crates/herald-server/src/routes/versions.rs)). + The action's two corrections still apply. To change the changelog of an existing version, pass + `changelog-file`. +- **If the build came out identical**, Herald already stores those bytes. Herald refuses the + upload, and its refusal names the ZIP id (`upload_zip` in + [`zip_upload.rs`](https://github.com/stellarwp/herald/blob/main/crates/herald-server/src/routes/zip_upload.rs)). + The action uses that id and continues. The refusal has no hash, so the action shows the SHA-256 + of the file. Herald found the ZIP by that hash, so the hash in Herald is the same. The exception + is a ZIP with macOS files (`__MACOSX/`, `.DS_Store`): Herald removes those files before it + computes the hash, so the hash in Herald differs from the hash of the file. +- **If another run created the version** after this run looked it up (step 3) and before this run + tried to create it (step 5), Herald refuses the create as a duplicate. The action reads the + version that the other run created and continues to the update. If that read fails, the action + still runs the update, and warns that the version line of the changelog and the release date were + not corrected. + +When Herald refuses a call (an HTTP 4xx), the call changed nothing, and the error says what Herald +holds at that point: nothing, the ZIP with no version changed, or a new version that is still a +draft. + +When Herald does not answer a write, or answers with a server error, the action cannot tell whether +the write was applied. The error says so. The log line ` is in Herald with the ZIP ` means Herald confirmed -the update. A failure after that line, such as the job summary not being written, does not undo it: -the version is in Herald as the line says. +the update. A failure after that line, such as the job summary not being written, does not undo the +update. -Skip the step for a version whose GitHub release already exists, as the example at the top does with -release-merge's -[`already-published`](../release-merge/README.md#outputs) output. The rerun of a published version -builds the ZIP again, and without the condition it would replace a ZIP customers are already -downloading. +Skip the Herald step when the GitHub release of the version already exists, as the example at the +top does with release-merge's [`already-published`](../release-merge/README.md#outputs) output. A +rerun of that deploy builds the ZIP again. Without `already-published == 'no'`, the Herald step +would replace a ZIP that customers are already downloading. -`already-published` is about the GitHub release only. When the Herald step passed and a later step -failed, the rerun runs the Herald step again. A build that comes out identical reuses the ZIP. Any -other build replaces the ZIP of the version, which is published in Herald by then. +`already-published` is about the GitHub release only. If the Herald step passed and a later step +failed, the GitHub release does not exist yet, so the rerun runs the Herald step again. If the +build comes out identical, the Herald step reuses the ZIP. If the build differs, the Herald step +replaces the ZIP of the version, which is already published in Herald. ## The key, and who can publish The key is a Herald API key of scope `ci`. That scope -[can upload ZIPs and create, read and update versions](https://github.com/stellarwp/herald/blob/e324034b3f18acc4c2ea806ac7d5ee2fdd6f0870/docs/github-actions.md#what-ci-tokens-can-do), -and nothing else: it cannot delete a version or touch products, brands or other keys. +[can upload ZIPs and create, read and update versions](https://github.com/stellarwp/herald/blob/main/docs/github-actions.md#what-ci-tokens-can-do), +and nothing else. It cannot delete a version or change products, brands or other keys. -With `status: published`, the version is live in Herald when the step ends, with no second click -there. So whoever can start the deploy can publish. +With `status: published`, the version is live in Herald when the step ends. So whoever can start +the deploy can publish. On GitHub, starting a workflow by hand [needs write access to the repository](https://docs.github.com/en/actions/how-tos/manage-workflow-runs/manually-run-a-workflow). -Keep that access to the people who release and to the app that dispatches for the release dashboard. -The review and the QA approval happen in the release dashboard, before the deploy. +Give that access only to the people who release and to the app that dispatches for the release +dashboard. The review and the QA approval happen in the release dashboard, before the deploy. -How much more to add is each repository's choice: +Each repository chooses how much more to add: -- Keep the key as a secret of an environment whose branch policy accepts only release branches, so - no run on another branch can read it. -- Give that environment required reviewers, for an approval on GitHub before the job starts. -- Pass `status: review`, to leave the last click in Herald. +- Keep the key as a secret of an environment whose branch policy accepts only release branches. + Then no run on another branch can read the key. +- Give that environment required reviewers, so that someone approves on GitHub before the job + starts. +- Pass `status: review`, so that someone publishes the version in Herald by hand. ## What it leaves to do -- **The Portal's catalogue.** `software.liquidweb.com` copies the latest published version from - Herald once a day - ([`SyncService.php`](https://github.com/stellarwp/software.liquidweb.com/blob/82dd6de40ec9253afef2cf227ba250f7d961829f/content/themes/commerce-portal-theme/src/SLW/CommercePortal/CatalogFeature/SyncService.php#L18-L53)). - To show a release there at once, an administrator clicks **Sync All From Herald** and then - **Flush Catalog Cache** under Products → Catalog Features. -- **Customers on legacy licenses.** They do not get updates through Herald. The release to the - brand's own licensing site stays a step of its own. +- **The catalogue of the Portal (`software.liquidweb.com`).** The Portal copies the latest + published version from Herald once a day (`SyncService` in + [`SyncService.php`](https://github.com/stellarwp/software.liquidweb.com/blob/develop/content/themes/commerce-portal-theme/src/SLW/CommercePortal/CatalogFeature/SyncService.php)). + To show a release in the Portal sooner, a Portal administrator opens the product under + Products → Catalog Features, clicks **Refresh from Herald** and then **Update**. After that, the + administrator clicks **Flush Catalog Cache** on the Catalog Features list. The Portal keeps each + product's list of versions for 5 minutes. If the Portal still shows the previous version, wait 5 + minutes and refresh again. +- **Customers on legacy licenses.** They do not get updates through Herald. Releasing to the + brand's own licensing site is still a separate step. ## How it runs -The logic is in [`herald-publish.js`](./herald-publish.js), run by `actions/github-script`, with no -dependency to install. The calls use the runtime's `fetch`. +The logic is in [`herald-publish.js`](./herald-publish.js), run by `actions/github-script`. It has +no dependency to install. The calls to Herald use the runtime's `fetch`, and +[`lib/zip.js`](../../lib/zip.js) reads the ZIP. -A redirect is refused rather than followed, since it would send the key to another address. The -upload is given ten minutes and every other call thirty seconds, so a request that hangs does not -hold the deploy. +The action fails on a redirect instead of following it, because a redirect would send the key to +another address. The upload may take up to ten minutes, and every other call up to thirty seconds. +A request that takes longer fails the step. Tests are in [`tests/actions/herald-publish`](../../../tests/actions/herald-publish/herald-publish.test.js), with -Herald's answers recorded: `npm test`. +Herald's answers recorded. Run them with `npm test`.