diff --git a/.github/actions/herald-publish/README.md b/.github/actions/herald-publish/README.md new file mode 100644 index 00000000..da020657 --- /dev/null +++ b/.github/actions/herald-publish/README.md @@ -0,0 +1,310 @@ +# herald-publish + +Publishes a plugin ZIP to [Herald](https://github.com/stellarwp/herald), the service customers +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. + +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 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 + 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. In this example the build writes +# build/my-plugin.zip. + +- uses: stellarwp/plugin-toolbox/.github/actions/herald-publish@v1 + if: steps.merge.outputs.already-published == 'no' + with: + herald-url: https://herald.example.com + product-slug: 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 +``` + +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. 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 needs the product and a key before the step can run. + +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 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 + owner opens the organization's Settings → Secrets and variables → Actions → New organization + 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 → + 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`. + +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 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 + +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 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 + +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. +* New - Added a setting for the maximum fee. +``` + +A repository that writes its changelog with the +[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 + env: + VERSION: ${{ inputs.version }} + run: npx @stellarwp/changelogger get-changelog-contents --version="$VERSION" > herald-changelog.txt +``` + +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 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, 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` | 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 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. | +| `versions-url` | The page of the Herald dashboard that lists the product's versions, newest first. | + +## Running it again + +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 the +update. + +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. 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/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. 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). +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. + +Each repository chooses how much more to add: + +- 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 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`. 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. + +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. Run them with `npm test`. diff --git a/.github/actions/herald-publish/action.yml b/.github/actions/herald-publish/action.yml new file mode 100644 index 00000000..a0db7b28 --- /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. 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 +# 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 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 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.' + 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. A step before this one + builds it. The action builds nothing and looks for no file on its own. + 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 version + 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: + 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 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.' + 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 }} + 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' + 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_SLUG: ${{ inputs.product-slug }} + INPUT_VERSION: ${{ inputs.version }} + INPUT_ZIP: ${{ inputs.zip }} + INPUT_STATUS: ${{ inputs.status }} + INPUT_CHANGELOG_FILE: ${{ inputs.changelog-file }} + 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..960411aa --- /dev/null +++ b/.github/actions/herald-publish/herald-publish.js @@ -0,0 +1,732 @@ +'use strict' + +/** + * 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, 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 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. + * + * 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 crypto = require('node:crypto') +const fs = require('node:fs') +const path = require('node:path') + +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.' + +/** 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 + +/** How much of a file WordPress reads to find its header. */ +const HEADER_BYTES = 8192 + +/** + * 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. There is no + * default: the caller names the instance, so a run never reaches one nobody chose. + * + * @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 to publish to. ${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', '[::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}`) + } + + 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-slug` input: the slug of the product in Herald, as its Products page shows it. + * + * @param {string} slug The input value. + * + * @throws {Error} When it is empty, holds whitespace or a URL delimiter, or is `.` or `..`. + * + * @returns {string} The slug, without surrounding whitespace. + */ +function readProductSlug(slug) { + const trimmed = String(slug ?? '').trim() + + if (trimmed === '') { + 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-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 +} + +/** + * 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, data: Buffer}} The file's name and its bytes. + */ +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), data: fs.readFileSync(file) } +} + +/** + * Reads the `changelog-file` input: the entries of this version, one per line. + * + * 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. + * + * @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 = nonEmptyLines(text) + + 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') +} + +/** + * 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 + * a `Theme Name` header. + * + * 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. + * + * @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, HEADER_BYTES) + const named = plugin ? /^[ \t/*#@]*Plugin Name:/im : /^[ \t/*#@]*Theme Name:/im + if (start === null || !named.test(start)) { + continue + } + + const version = /^[ \t/*#@]*Version:(.*)$/im.exec(start) + const value = version ? headerValue(version[1]) : '' + + return value === '' ? null : { file: entry.name, version: value } + } + + return null +} + +/** + * 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, 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 lines = changelog.split(/\r?\n/) + const kept = lines.filter((line) => !/^=.*=$/.test(line.trim())) + + return kept.length === lines.length ? null : kept.join('\n').trim() +} + +/** + * 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, + * 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. + * + * @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 } + } + + 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) + } catch { + data = null + } + + // 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) } +} + +/** + * Says how a request failed, for an error message. + * + * @param {{status: number, reason: string}} answer What `send` returned. + * + * @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 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. + * + * @param {{status: number}} answer What `send` returned. + * + * @returns {boolean} True when what Herald holds is not known. + */ +function unconfirmed(answer) { + return answer.status < 400 || answer.status >= 500 +} + +/** + * 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. 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. 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() + form.append('file', new Blob([zip.data], { 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) { + // 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 + + 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. + * + * @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 version with none. + * + * @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. + */ +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 = 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) + 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) + 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\b.*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 }) + core.info( + uploaded.reused + ? `Herald already holds ${zip.name} as ${uploaded.id} (sha256 ${uploaded.sha256}): reusing it.` + : `Uploaded ${zip.name} as ${uploaded.id} (sha256 ${uploaded.sha256}).` + ) + + // 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. 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} (${uploaded.meta.main_file ?? 'main file unknown'}), ` + + `not ${version}, so it was not published. ${stored(uploaded.id, product)}` + ) + } + + if (inside === null && zipVersion === '') { + core.warning(`The version inside ${zip.name} could not be read, so it was not compared with ${version}.`) + } + + // 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 }) + + 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` + + 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) + // 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}`, + ...(uploaded.sha256 === '' ? [] : [` - SHA-256: ${uploaded.sha256}`]), + ] + await core.summary.addRaw(lines.join('\n'), true).write() +} + +module.exports = { + runHeraldPublish, + validateVersion, + readUrl, + readProductSlug, + readStatus, + readZip, + readChangelogFile, + entriesOnly, + readZipVersion, + readApiKey, +} 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..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 } = 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.' @@ -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,11 @@ 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() + // 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) => codeSpan(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..29d62390 100644 --- a/.github/lib/github.js +++ b/.github/lib/github.js @@ -89,4 +89,84 @@ 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 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 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. + * + * @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 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. + * + * @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 markdownLink(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 markdownLink(sha.slice(0, 7), `${url}/commit/${sha}`) +} + +module.exports = { readRepository, isNotFound, readTag, tagExists, repositoryUrl, markdownLink, codeSpan, branchLink, commitLink } 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/.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/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..352ab0fa 100644 --- a/templates/workflows/release.yml +++ b/templates/workflows/release.yml @@ -83,6 +83,28 @@ 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. 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. + # Without the secret, the step fails before anything is sent to Herald. + # + # 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: steps.merge.outputs.already-published == 'no' + # with: + # herald-url: https://herald.example.com + # product-slug: 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..7a4d5b5b --- /dev/null +++ b/tests/actions/herald-publish/herald-publish.test.js @@ -0,0 +1,934 @@ +'use strict' + +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') + +const { + runHeraldPublish, + validateVersion, + readUrl, + readProductSlug, + readStatus, + readZip, + readChangelogFile, + entriesOnly, + readZipVersion, + 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' + +/** 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' + +/** 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. */ +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 version Herald answers a create with. It fills the changelog and the release date from the + * 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', + 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: CREATED }, + { 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_SLUG: 'gift-aid', + INPUT_VERSION: '2.2.2', + INPUT_ZIP: 'give-gift-aid.zip', + INPUT_STATUS: '', + INPUT_CHANGELOG_FILE: '', + INPUT_API_KEY: 'herald-ci-key', + ...overrides, + } +} + +/** + * 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 {object} File contents by path inside the zip. + */ +function pluginFiles(version = '2.2.2') { + return { + 'give-gift-aid/readme.txt': `=== Gift Aid ===\nStable tag: ${version}\n`, + 'give-gift-aid/includes/version.php': " { + sent.push(options) + + return fetch(url, options) + }, + requests, + 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. + * + * @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 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', () => { + 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', () => { + assert.throws(() => readUrl('https://user:pass@herald.example.com'), /address only/) + assert.throws(() => readUrl('https://herald.example.com/?key=1'), /address only/) + }) + + 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` + 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.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/) + }) + + 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('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') + 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', () => { + assert.strictEqual(readStatus(''), 'published') + assert.strictEqual(readStatus('Review'), 'review') + assert.throws(() => readStatus('live'), /is not one of draft, review, published/) + }) + + 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.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/) + 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('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 or with no text', () => { + assert.strictEqual(entriesOnly('* Fix - One thing.'), 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' }) + + const stored = zipOf({ 'my-plugin/my-plugin.php': ' { + 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.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': ' { + // 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': ' { + // 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') + }) + + 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, sent } = heraldFetch(FRESH) + + 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', + '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, + 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.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.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/) + 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) => { + 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_STATUS: 'review' }), + fetch, + cwd, + now: NOW, + }) + + 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('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" } } + 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 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], + { 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(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\./ + ) + }) + }) + + describe('a version the product already has', () => { + 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: { ...CREATED, status: 'published', zip_id: 'older-zip', changelog: '* Fix - One thing.' } }, + 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', + '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, version updated\.\n {2}- ZIP: 11111111/) + }) + + it('reuses a ZIP Herald already holds', async (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 }, + FRESH[3], + ]) + const cwd = checkoutWith() + + 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, { + zip_id: ZIP_ID, + status: 'published', + changelog: '* Fix - One thing.\n* New - Another thing.', + }) + // 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`)) + }) + }) + + describe('what stops it', () => { + 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, 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), ['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([ + { 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 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' } }]) + + 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([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 400: ZIP security check failed: too many entries\)\. Nothing was published to Herald/ + ) + 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 anyway\. 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 anyway/) + assert.doesNotMatch(error.message, /Nothing was published/) + + return true + } + ) + }) + + 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') }) + } + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + /failed \(no answer: getaddrinfo ENOTFOUND herald\.test\)/ + ) + }) + + 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\)\. Nothing was published to Herald/ + ) + 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)) + 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 anyway: run it again/) + 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 }), + /Reading gift-aid 2\.2\.2 in Herald failed \(no answer: terminated\)\. Nothing was published to Herald/ + ) + }) + + it('says where the ZIP is when the create finds no product', 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('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([ + ...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 }), + (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 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 + } + ) + }) + + 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(), {}) + }) + + 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([ + FRESH[0], + { 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' } }, + ]) + + await assert.rejects( + runHeraldPublish({ core, env: publishEnv(), fetch, cwd: checkoutWith(), now: NOW }), + /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 + } + ) + }) + }) +}) 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..73b301a5 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,23 @@ 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`/) + // 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('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) => { @@ -439,7 +455,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..5a522200 --- /dev/null +++ b/tests/lib/github.test.js @@ -0,0 +1,67 @@ +'use strict' + +const { describe, it } = require('node:test') +const assert = require('node:assert') + +const { repositoryUrl, markdownLink, codeSpan, 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('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('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('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'), + '[0123456](https://github.com/stellarwp/plugin/commit/0123456789abcdef0123456789abcdef01234567)' + ) + }) + }) +}) 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 }