diff --git a/.github/actions/push-translations/README.md b/.github/actions/push-translations/README.md new file mode 100644 index 00000000..14a54800 --- /dev/null +++ b/.github/actions/push-translations/README.md @@ -0,0 +1,186 @@ +# push-translations + +Pushes a plugin's POT file to the shared GlotPress site, translations.stellarwp.com, and imports +its strings into a project. What the import printed comes back as an output. + +A project at the top level of the site: + +```yaml +- uses: stellarwp/plugin-toolbox/.github/actions/push-translations@v1 + id: translations + with: + project: my-plugin + remote-folder: my-brand + host: ${{ secrets.TRANSLATIONS_DEPLOY_HOST }} + user: ${{ secrets.TRANSLATIONS_DEPLOY_USER }} + ssh-key: ${{ secrets.TRANSLATIONS_DEPLOY_SSH_KEY }} + pot-location: ${{ secrets.TRANSLATIONS_DEPLOY_POT_LOCATION }} + +- run: echo "$RESULT" + env: + RESULT: ${{ steps.translations.outputs.glotpress-result }} +``` + +A project under a parent project: + +```yaml +- uses: stellarwp/plugin-toolbox/.github/actions/push-translations@v1 + with: + project: my-brand/my-plugin + remote-folder: my-brand + host: ${{ secrets.TRANSLATIONS_DEPLOY_HOST }} + user: ${{ secrets.TRANSLATIONS_DEPLOY_USER }} + ssh-key: ${{ secrets.TRANSLATIONS_DEPLOY_SSH_KEY }} + pot-location: ${{ secrets.TRANSLATIONS_DEPLOY_POT_LOCATION }} +``` + +A composite action cannot read secrets, so the caller passes them. Generate the POT before this +step: the action only sends the file. + +With `pot-path` empty, the POT is `/.pot`, read from the header of the +plugin file: the first PHP file at the top of the checkout with a `Plugin Name` header in its first +8 KiB. Leading and trailing slashes on `Domain Path` are dropped, so `/languages/` gives +`languages/my-plugin.pot` for a `my-plugin` Text Domain. Pass `pot-path` for a POT that is somewhere else or named differently. + +## After generate-pot + +[generate-pot](../generate-pot) reports the POT it wrote as its `pot-path` output, relative to its +`working-directory`. Pass both on, so this action sends that file: + +```yaml +- id: pot + uses: stellarwp/plugin-toolbox/.github/actions/generate-pot@v1 + with: + working-directory: plugin + +- if: steps.pot.outputs.changed == 'yes' + uses: stellarwp/plugin-toolbox/.github/actions/push-translations@v1 + with: + working-directory: plugin + pot-path: ${{ steps.pot.outputs.pot-path }} + project: my-plugin + remote-folder: my-brand + host: ${{ secrets.TRANSLATIONS_DEPLOY_HOST }} + user: ${{ secrets.TRANSLATIONS_DEPLOY_USER }} + ssh-key: ${{ secrets.TRANSLATIONS_DEPLOY_SSH_KEY }} + pot-location: ${{ secrets.TRANSLATIONS_DEPLOY_POT_LOCATION }} +``` + +An empty `pot-path` here names the same file only when generate-pot ran with its `domain` and +`source-path` inputs unset: this action reads the `Text Domain` of the plugin file at the top of the +checkout, and takes no such inputs. + +`working-directory` is a directory inside the workspace, relative to it or absolute. `pot-path` and +the plugin file are read there. The copy step runs in a container that sees only the workspace, so a +checkout outside it is refused. + +## One run at a time per project + +Every run copies the POT to the same path on the server, `//.pot`, +and imports that path into the same project. Two runs at once can import each other's file, or +import an older POT after a newer one. A composite action cannot set `concurrency`, so the job that +uses it does, with a group named after the project: + +```yaml +jobs: + translations: + runs-on: ubuntu-latest + concurrency: + group: push-translations-my-plugin + cancel-in-progress: false +``` + +GitHub runs the jobs of a group one at a time, so two imports never overlap. It does not order them +by commit: a job that reaches the group later runs later, even when it holds an older POT, and of +the jobs waiting only the one that arrived last is kept. Run the push from the commit you release, +after the steps that generate the POT, so the last job to reach the group holds the newest POT. A +group holds jobs of one repository only, so push a project from one repository. + +## What it does + +1. Checks every input and names the build: a random id of 32 hex characters. +2. Copies the POT to `//` with rsync, under the name it has in the + repository. +3. Over ssh, in `site-directory`, runs + `wp glotpress import-originals //.pot` and writes + what it prints to `bot-output/-`. +4. Reads that file back from `result-url` over https, sets it as `glotpress-result` and adds it to + the job summary. +5. Deletes the file from the server. This runs even when the import or the read failed. + +The file is public while it exists, between steps 3 and 5. Its name ends in a random build id, +which the action masks before any step uses it, so the run log shows `***` in its place and the +job summary does not name the file. It holds only what the import printed: counts of the strings +added, updated, fuzzied and obsoleted. + +## What the server needs + +- The `user` can log in with `ssh-key`, and its public key is in `authorized_keys`. +- `rsync` on the server, and `` existing and writable. rsync creates + `` when it is missing, not the directories above it. +- WP-CLI as `wp` on the path of a non-interactive shell, and the GlotPress site in + `site-directory`, with the `glotpress import-originals` command. +- The project exists in GlotPress. The import does not create one. +- `site-directory/bot-output/` is served at `result-url`. The action creates the directory. + +## What it refuses + +Before anything is sent, with the input named in the message: + +- An empty `project`, `remote-folder`, `host`, `user`, `ssh-key` or `pot-location`. A + secret the repository does not have arrives empty, so this is how a missing secret shows. +- Any path whose parts are not letters, digits, `.`, `_` and `-`, or that has a part starting with + `.` or `-`. That rules out spaces, quotes, `;`, `|`, `$`, backticks, `..`, `~` and a value that + would be read as a command option. +- `project` or `remote-folder` that starts with `/`. +- `pot-path` that is absolute or does not end in `.pot`, given or read from the plugin header. +- `working-directory` that is not a directory, or is outside the workspace. +- An empty `pot-path` when no plugin file is found, or its header has no `Text Domain` or no + `Domain Path`. +- `pot-location` that is not absolute. +- `host` that is not a host name or an IPv4 address, and `user` that is not a plain user name. +- `result-url` that is not `https://`, or that has a query, a port or credentials. + +A refused `host`, `user` or `pot-location` is named without its value, since it comes from a +secret. + +## Inputs + +| Input | Required | Default | What it does | +|---|---|---|---| +| `project` | yes | | The GlotPress project path: `my-plugin`, or `my-brand/my-plugin` under a parent | +| `pot-path` | no | `/.pot` from the plugin header | The POT file, relative to the checkout | +| `working-directory` | no | the workspace | Where the repository is checked out: a directory inside the workspace, relative to it or absolute, e.g. `plugin` | +| `remote-folder` | yes | | The folder under `pot-location` the POT is copied to, e.g. `my-brand` | +| `host` | yes | | The server to connect to | +| `user` | yes | | The user to connect as | +| `ssh-key` | yes | | The private key of `user` | +| `pot-location` | yes | | The directory on the server that holds the POT folders, absolute | +| `site-directory` | no | `translations.stellarwp.com/html/` | The GlotPress site on the server, absolute or relative to the home of `user` | +| `result-url` | no | `https://translations.stellarwp.com/bot-output/` | The public URL of `bot-output/` in `site-directory` | + +A trailing `/` on a folder, a directory or the URL is optional. + +## Outputs + +| Output | Example | What it is | +|---|---|---| +| `glotpress-result` | `1 new strings added, 0 updated, 0 fuzzied, and 0 obsoleted.` | What `wp glotpress import-originals` printed. Text from the server: pass it to a script through `env`, never inside `run:` | +| `project` | `my-brand/my-plugin` | The project the strings were imported into | + +## How it runs + +Two [actions/github-script](https://github.com/actions/github-script) steps run +[`push-translations.js`](./push-translations.js). The first checks the inputs and sets the values +the later steps use. The second reads the import output back over https and sets it as the +`glotpress-result` output. Inputs reach both through `process.env`, never by being interpolated. + +The copy and the two ssh steps are third-party actions, +[burnett01/rsync-deployments](https://github.com/Burnett01/rsync-deployments) and +[appleboy/ssh-action](https://github.com/appleboy/ssh-action), pinned to a full commit SHA because +they receive the deploy key. The rsync action builds a shell command from the paths, the host and +the user, which is why all of them are checked. The remote script holds no value: the checked +values reach the remote shell as environment variables, through the ssh action's `envs`. + +`tests/actions/push-translations/push-translations.test.js` covers the check, with the two shapes +above and the refusals, and the read of the import output. Run `npm install` once, then `node --test`. diff --git a/.github/actions/push-translations/action.yml b/.github/actions/push-translations/action.yml new file mode 100644 index 00000000..16fb352b --- /dev/null +++ b/.github/actions/push-translations/action.yml @@ -0,0 +1,157 @@ +# Pushes a plugin's POT file to the shared GlotPress site, translations.stellarwp.com: rsync copies +# the POT to the server, `wp glotpress import-originals` imports it over ssh, and what the import +# printed comes back as an output. +# +# This action handles a deploy key and builds remote shell commands. The first step checks every +# input against an allow-list, in push-translations.js run by actions/github-script, and fails +# before anything is sent. The later steps use the values it checked. No input is interpolated into +# a script: the remote `script:` reads its values from the environment. +# +# Every run copies the POT to the same path on the server, so the calling job sets a `concurrency` +# group for the project; the README shows one. +name: Push translations +description: Pushes a POT file to the GlotPress site and imports its strings into a project + +inputs: + project: + description: >- + The GlotPress project the strings are imported into, as its path on the site: + `my-plugin`, or `my-brand/my-plugin` for a project under a parent. + required: true + pot-path: + description: >- + The POT file, relative to the checkout, e.g. `languages/my-plugin.pot`. Its name is the name it + has on the server. Empty means `/.pot` from the header of the plugin + file at the top of the checkout. + required: false + default: '' + working-directory: + description: >- + Where the repository is checked out: a directory inside the workspace, relative to it or + absolute, e.g. `plugin`. Empty is the workspace. + required: false + default: '' + remote-folder: + description: >- + The folder under `pot-location` the POT is copied to, one per product line, e.g. `my-brand`. + required: true + host: + description: 'The server to connect to. Pass a secret.' + required: true + user: + description: 'The user to connect as. Pass a secret.' + required: true + ssh-key: + description: 'The private key of `user`. Pass a secret.' + required: true + pot-location: + description: >- + The directory on the server that holds the POT folders, as an absolute path, e.g. + `/home/user/pots/`. Pass a secret. + required: true + site-directory: + description: >- + The directory of the GlotPress site on the server, where `wp` runs: absolute, or relative to + the home of `user`. + required: false + default: 'translations.stellarwp.com/html/' + result-url: + description: >- + The public https URL of the `bot-output/` folder in `site-directory`, where the import output + is read back from. + required: false + default: 'https://translations.stellarwp.com/bot-output/' + +outputs: + glotpress-result: + description: 'What `wp glotpress import-originals` printed.' + value: ${{ steps.fetch.outputs.glotpress-result }} + project: + description: 'The GlotPress project the strings were imported into.' + value: ${{ steps.check.outputs.project }} + +runs: + using: 'composite' + steps: + - name: Check the inputs and name the build + id: check + uses: actions/github-script@v9 + env: + # github-script's require() resolves against the workspace of the repository being built, + # not this action's directory, so the path has to be passed in. github.action_path is the + # documented expression for it. + ACTION_PATH: ${{ github.action_path }} + # Read from process.env rather than interpolated into the script, so an input is data and + # never part of the program. + INPUT_PROJECT: ${{ inputs.project }} + INPUT_POT_PATH: ${{ inputs.pot-path }} + INPUT_WORKING_DIRECTORY: ${{ inputs.working-directory }} + INPUT_REMOTE_FOLDER: ${{ inputs.remote-folder }} + INPUT_HOST: ${{ inputs.host }} + INPUT_USER: ${{ inputs.user }} + INPUT_SSH_KEY: ${{ inputs.ssh-key }} + INPUT_POT_LOCATION: ${{ inputs.pot-location }} + INPUT_SITE_DIRECTORY: ${{ inputs.site-directory }} + INPUT_RESULT_URL: ${{ inputs.result-url }} + with: + script: | + const { runPushTranslations } = require(`${process.env.ACTION_PATH}/push-translations.js`) + await runPushTranslations({ core, env: process.env }) + + # SHA-pinned: these two actions receive the deploy key. Bump the SHA to pick up a new release. + # The rsync action builds a shell command from path, remote_path, remote_host and remote_user, + # which is why the first step checks all four. + - name: Copy the POT file to the server + uses: burnett01/rsync-deployments@796cf0d5e4b535745ce49d7429f77cf39e25ef39 # 7.0.1 + with: + switches: -avz --omit-dir-times --no-perms + path: ${{ steps.check.outputs.pot-path }} + remote_path: ${{ steps.check.outputs.remote-path }} + remote_host: ${{ steps.check.outputs.host }} + remote_user: ${{ steps.check.outputs.user }} + remote_key: ${{ inputs.ssh-key }} + + - name: Import the strings into GlotPress + uses: appleboy/ssh-action@25ce8cbbcb08177468c7ff7ec5cbfa236f9341e1 # v1.1.0 + env: + SITE_DIRECTORY: ${{ steps.check.outputs.site-directory }} + PROJECT: ${{ steps.check.outputs.project }} + REMOTE_POT: ${{ steps.check.outputs.remote-pot }} + RESULT_FILE: ${{ steps.check.outputs.result-file }} + with: + host: ${{ steps.check.outputs.host }} + username: ${{ steps.check.outputs.user }} + key: ${{ inputs.ssh-key }} + # The checked values reach the remote shell as variables, not as text of the script. + envs: SITE_DIRECTORY,PROJECT,REMOTE_POT,RESULT_FILE + script: | + set -e + cd "$SITE_DIRECTORY" + mkdir -p bot-output + wp glotpress import-originals "$PROJECT" "$REMOTE_POT" > "bot-output/$RESULT_FILE" + + - name: Read the import output + id: fetch + uses: actions/github-script@v9 + env: + ACTION_PATH: ${{ github.action_path }} + RESULT_URL: ${{ steps.check.outputs.result-url }} + with: + script: | + const { runReadResult } = require(`${process.env.ACTION_PATH}/push-translations.js`) + await runReadResult({ core, env: process.env }) + + # Also when the import or the read failed, so the output file does not stay on the server. + - name: Delete the import output from the server + if: ${{ always() && steps.check.outcome == 'success' }} + uses: appleboy/ssh-action@25ce8cbbcb08177468c7ff7ec5cbfa236f9341e1 # v1.1.0 + env: + SITE_DIRECTORY: ${{ steps.check.outputs.site-directory }} + RESULT_FILE: ${{ steps.check.outputs.result-file }} + with: + host: ${{ steps.check.outputs.host }} + username: ${{ steps.check.outputs.user }} + key: ${{ inputs.ssh-key }} + envs: SITE_DIRECTORY,RESULT_FILE + script: | + rm -f -- "$SITE_DIRECTORY/bot-output/$RESULT_FILE" diff --git a/.github/actions/push-translations/push-translations.js b/.github/actions/push-translations/push-translations.js new file mode 100644 index 00000000..a43dc585 --- /dev/null +++ b/.github/actions/push-translations/push-translations.js @@ -0,0 +1,273 @@ +'use strict' + +/** + * Checks what the push-translations action was given, before anything is sent to the translations + * server, and names the file the import output is written to. + * + * The later steps of action.yml copy the POT with rsync and run `wp glotpress import-originals` + * over ssh. The rsync action builds a shell command from its inputs, and the import is a remote + * shell command, so every value that reaches either one has to match an allow-list first. Those + * steps use the outputs set here, never the raw inputs, except ssh-key, which is only ever a key. + * + * readInputs is pure, so a test can call it with an environment. + */ + +const crypto = require('node:crypto') +const path = require('node:path') + +const { readPluginHeader } = require('../../lib/plugin-header.js') +const { readWorkingDirectory } = require('../../lib/workspace.js') + +/** What was not done, to close every error message. */ +const WHAT = 'Nothing was sent to the translations server.' + +/** + * One part of a path: letters, digits, `.`, `_` and `-`, not starting with `.` or `-`. So no part + * is `..`, a hidden file or a command option, and none holds a space or a shell metacharacter. + */ +const PART = '[A-Za-z0-9_][A-Za-z0-9._-]*' + +/** One or more parts joined by `/`. */ +const PARTS = `${PART}(?:/${PART})*` + +/** + * What each input has to match, and how to say what it is. The first capture group is the value + * the action uses, so a trailing `/` is dropped. `secret` keeps the value out of the message. + */ +const RULES = { + project: { + pattern: new RegExp(`^(${PARTS})$`), + shape: 'a GlotPress project path, such as my-plugin or my-brand/my-plugin', + }, + 'pot-path': { + pattern: new RegExp(`^((?:${PART}/)*${PART}\\.pot)$`), + shape: 'the path of a .pot file relative to the checkout, such as languages/my-plugin.pot', + }, + 'remote-folder': { + pattern: new RegExp(`^(${PARTS})/?$`), + shape: 'a folder name under pot-location, such as my-brand', + }, + 'site-directory': { + pattern: new RegExp(`^(/?${PARTS})/?$`), + shape: 'a directory on the server, absolute or relative to the home of user, such as translations.stellarwp.com/html/', + }, + 'result-url': { + pattern: new RegExp(`^(https://[A-Za-z0-9][A-Za-z0-9.-]*(?:/${PART})*)/?$`), + shape: 'an https URL of a folder, with no query, such as https://translations.stellarwp.com/bot-output/', + }, + host: { + pattern: /^([A-Za-z0-9][A-Za-z0-9.-]*)$/, + shape: 'a host name or an IPv4 address', + secret: true, + }, + user: { + pattern: new RegExp(`^(${PART})$`), + shape: 'a user name', + secret: true, + }, + 'pot-location': { + pattern: new RegExp(`^(/${PARTS})/?$`), + shape: 'an absolute directory on the server, such as /home/user/pots/', + secret: true, + }, + // Only handed to the rsync and ssh actions as a key, never part of a command: any text will do. + 'ssh-key': { pattern: /^([\s\S]+)$/, shape: 'a private key', secret: true }, +} + +/** A build id: 32 lowercase hex characters. */ +const BUILD_ID = /^[a-f0-9]{32}$/ + +/** + * Reads one input and checks it against its rule. + * + * @param {object} env The environment, holding the inputs as `INPUT_*`. + * @param {string} name The input's name, as action.yml spells it. + * + * @throws {Error} When the value is empty or does not match. + * + * @returns {string} The value the action uses. + */ +function readInput(env, name) { + const { pattern, shape, secret } = RULES[name] + const value = String(env[`INPUT_${name.toUpperCase().replace(/-/g, '_')}`] ?? '').trim() + + if (value === '') { + throw new Error(`${name} is empty. Pass ${shape}. ${WHAT}`) + } + + const match = pattern.exec(value) + if (!match) { + // A value from a secret is masked in the log anyway, but is not repeated here either. + throw new Error(`${name} ${secret ? '' : `'${value}' `}is not ${shape}. ${WHAT}`) + } + + return match[1] +} + +/** + * Reads `working-directory`: where the repository is checked out. Empty is the workspace. + * + * The copy step runs in a container that sees only the workspace, and builds a shell command from + * the POT's path. So the checkout has to be inside the workspace, and its path from there is + * checked like the other paths. + * + * @param {object} env The environment, holding `INPUT_WORKING_DIRECTORY` and `GITHUB_WORKSPACE`. + * + * @throws {Error} When it is not a directory, is outside the workspace, or is not plain names. + * + * @returns {{dir: string|undefined, prefix: string}} The checkout, and what goes before a path + * relative to it to make the path relative to the workspace: empty, or ending in `/`. + */ +function readCheckout(env) { + const given = String(env.INPUT_WORKING_DIRECTORY ?? '').trim() + if (given === '') { + return { dir: env.GITHUB_WORKSPACE, prefix: '' } + } + + // The step runs in the workspace, like every step of a composite action. + const workspace = env.GITHUB_WORKSPACE || process.cwd() + const dir = readWorkingDirectory(given, { base: workspace, what: WHAT }) + const relative = path.relative(workspace, dir).split(path.sep).join('/') + + if (relative !== '' && !new RegExp(`^${PARTS}$`).test(relative)) { + throw new Error( + `working-directory '${given}' is not a directory inside the workspace, such as plugin: each part of its ` + + `path takes letters, digits, ., _ and -, and does not start with . or -. ${WHAT}` + ) + } + + return { dir, prefix: relative === '' ? '' : `${relative}/` } +} + +/** + * Where the POT is when `pot-path` is empty: `/.pot`, from the header of + * the plugin file at the top of the checkout. The result is checked like a given `pot-path`. + * + * @param {string|undefined} dir The checkout; undefined when `GITHUB_WORKSPACE` is not set. + * + * @throws {Error} When no plugin file is found, or its header has no Text Domain or Domain Path. + * + * @returns {string} The POT's path, relative to the checkout. + */ +function defaultPotPath(dir) { + const pass = `Pass pot-path. ${WHAT}` + if (!dir) { + throw new Error(`pot-path is empty and GITHUB_WORKSPACE is not set, so no plugin header can be read. ${pass}`) + } + const header = readPluginHeader(dir) + + if (header === null) { + throw new Error(`pot-path is empty and no PHP file at the top of the checkout has a Plugin Name header. ${pass}`) + } + if (!header.textDomain) { + throw new Error(`pot-path is empty and ${header.file} has no Text Domain header. ${pass}`) + } + // `Domain Path: /` names the plugin's root, which comes back empty once its slashes are dropped. + if (!header.domainPath) { + throw new Error(`pot-path is empty and ${header.file} has no Domain Path header, or it names the plugin's root. ${pass}`) + } + + return `${header.domainPath}/${header.textDomain}.pot` +} + +/** + * Checks every input and builds the values the later steps use. + * + * @param {object} env The environment, holding the inputs as `INPUT_*`. + * @param {string} buildId What makes the output file's name unique. Random by default; a test + * passes its own. + * + * @throws {Error} When an input, or the build id, is refused. + * + * @returns {Object} The step's outputs, by name. + */ +function readInputs(env, buildId = crypto.randomBytes(16).toString('hex')) { + const { dir, prefix } = readCheckout(env) + const withPot = { ...env, INPUT_POT_PATH: String(env.INPUT_POT_PATH ?? '').trim() || defaultPotPath(dir) } + const read = Object.fromEntries(Object.keys(RULES).map((name) => [name, readInput(withPot, name)])) + + if (!BUILD_ID.test(buildId)) { + throw new Error(`The build id is not 32 hex characters. ${WHAT}`) + } + + const potFile = read['pot-path'].split('/').pop() + const remotePath = `${read['pot-location']}/${read['remote-folder']}/` + const resultFile = `${potFile.slice(0, -'.pot'.length)}-${buildId}` + + // The later steps connect with host and user as checked here, trimmed. ssh-key is not returned: + // it is handed to those steps as a key, never placed in a command. + return { + project: read.project, + // Relative to the workspace, which is where the copy step reads it from. + 'pot-path': `${prefix}${read['pot-path']}`, + host: read.host, + user: read.user, + 'remote-path': remotePath, + 'remote-pot': `${remotePath}${potFile}`, + 'site-directory': read['site-directory'], + 'result-file': resultFile, + 'result-url': `${read['result-url']}/${resultFile}`, + } +} + +/** + * Runs the check and sets the outputs. + * + * @param {object} options + * @param {object} options.core The @actions/core toolkit, for the mask and the outputs. + * @param {object} options.env The environment, holding the inputs as `INPUT_*`. + * + * @throws {Error} When an input is refused. + * + * @returns {Promise} + */ +async function runPushTranslations({ core, env }) { + const outputs = readInputs(env) + + // The build id makes the import output's public address. Masked before any output carries it, + // so the runner prints *** in its place in every later log line, the env of the ssh steps + // included. It is not written to the job summary either. + core.setSecret(outputs['result-file'].slice(-32)) + + for (const [name, value] of Object.entries(outputs)) { + core.setOutput(name, value) + } +} + +/** + * Reads what the import printed back from the site, and sets it as the `glotpress-result` output. + * + * The URL was built by the check step from checked values. It is checked again for https here, + * since the request is made with whatever this step is handed. + * + * @param {object} options + * @param {object} options.core The @actions/core toolkit, for the output and the summary. + * @param {object} options.env The environment, holding `RESULT_URL`. + * @param {Function} options.fetchImpl The fetch to use, the runtime's by default. + * + * @throws {Error} When the URL is not https, or the site does not answer 200. + * + * @returns {Promise} + */ +async function runReadResult({ core, env, fetchImpl = globalThis.fetch }) { + const url = String(env.RESULT_URL ?? '') + + if (!url.startsWith('https://')) { + throw new Error('The import output has no https URL to be read from. The import ran, and its output was not read.') + } + + const response = await fetchImpl(url, { redirect: 'error', signal: AbortSignal.timeout(60000) }) + + if (!response.ok) { + throw new Error( + `Reading the import output answered ${response.status}. The import ran, and its output was not read.` + ) + } + + const result = (await response.text()).trim() + + core.setOutput('glotpress-result', result) + await core.summary.addHeading('Results from GlotPress', 2).addCodeBlock(result).write() +} + +module.exports = { runPushTranslations, runReadResult, readInputs } diff --git a/.github/lib/plugin-header.js b/.github/lib/plugin-header.js new file mode 100644 index 00000000..adbcbfae --- /dev/null +++ b/.github/lib/plugin-header.js @@ -0,0 +1,99 @@ +'use strict' + +/** + * The header of a plugin's main file, shared by the toolbox actions. Loaded by a path relative to + * each action's directory, like workspace.js. + * + * The main file is the first PHP file at the top of the directory, in name order, with a + * `Plugin Name` header in its first 8 KiB. + */ + +const fs = require('node:fs') +const path = require('node:path') + +/** How much of a file make-pot reads for its header, and so how much this reads. */ +const HEADER_BYTES = 8192 + +/** + * Reads one header field the way WordPress does: the line may start with spaces, tabs, `/`, `*`, + * `#` or `@`, the name matches in any case, and the value ends before a `*\/` or `?>`. + * + * @param {string} text The start of the file. + * @param {string} name The header name, e.g. `Text Domain`. + * + * @returns {string|null} The value, or null when the header is missing or empty. + */ +function readField(text, name) { + const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + const match = text.match(new RegExp(`^[ \\t/*#@]*${escaped}:(.*)$`, 'mi')) + const value = match ? match[1].replace(/\s*(?:\*\/|\?>).*/, '').trim() : '' + + return value === '' ? null : value +} + +/** + * Reads the start of a file, with CR-only line endings made LF. + * + * @param {string} file The file. + * + * @returns {string} Its first 8 KiB. + */ +function readStart(file) { + const fd = fs.openSync(file, 'r') + try { + const buffer = Buffer.alloc(HEADER_BYTES) + const bytes = fs.readSync(fd, buffer, 0, HEADER_BYTES, 0) + + return buffer.toString('utf8', 0, bytes).replace(/\r/g, '\n') + } finally { + fs.closeSync(fd) + } +} + +/** + * Finds the plugin's main file in a directory and reads its `Text Domain` and `Domain Path`. + * + * @param {string} dir The plugin directory. + * + * @throws {Error} When the directory or a file exists but cannot be read. + * + * @returns {{file: string, textDomain: string|null, domainPath: string|null}|null} The main file's + * name, its text domain, and its domain path without leading and trailing slashes, a + * missing header as null; or null when no top-level PHP file has a `Plugin Name` header, + * or the directory does not exist. + */ +function readPluginHeader(dir) { + let entries + try { + entries = fs.readdirSync(dir, { withFileTypes: true }) + } catch (error) { + if (error.code === 'ENOENT' || error.code === 'ENOTDIR') { + return null + } + + throw error + } + + const files = entries + .filter((entry) => entry.isFile() && entry.name.endsWith('.php')) + .map((entry) => entry.name) + .sort() + + for (const file of files) { + const text = readStart(path.join(dir, file)) + + if (readField(text, 'Plugin Name') !== null) { + const domainPath = readField(text, 'Domain Path') + + return { + file, + textDomain: readField(text, 'Text Domain'), + domainPath: domainPath === null ? null : domainPath.replace(/^\/+|\/+$/g, ''), + } + } + } + + return null +} + +module.exports = { readPluginHeader } diff --git a/README.md b/README.md index 9cf24ccb..bfd74d72 100644 --- a/README.md +++ b/README.md @@ -119,7 +119,7 @@ Three drawers in the toolbox. You can use any one without the others. | Layer | Lives in | What's in it | |---|---|---| -| Composite actions | `.github/actions/` | Small single-purpose steps with no opinions: `setup-slic`, `setup-bun`, `setup-node`, `prepare-matrix`, `check-php-changes`, `smart-checkout`, `process-changelog`, `generate-pot`, `zip-name`, `release-zip`, `changed-files`, `skip-drafts`, `download-plugins` | +| Composite actions | `.github/actions/` | Small single-purpose steps with no opinions: `setup-slic`, `setup-bun`, `setup-node`, `prepare-matrix`, `check-php-changes`, `smart-checkout`, `process-changelog`, `generate-pot`, `push-translations`, `zip-name`, `release-zip`, `changed-files`, `skip-drafts`, `download-plugins` | | Reusable workflows | `.github/workflows/` | Full jobs built from the actions (standards, analysis, tests, zip, release prep). Most repos will only touch this layer. | | File sync | `templates/` + `.github/sync.yml` | Files that must exist in the target repo, grouped by brand and repo type | @@ -172,6 +172,7 @@ Each phase ends with something people can actually use. - [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`. +- [x] Port `push-translations` from TEC: a POT file to GlotPress, with the GlotPress project and the server folder as inputs. - [ ] Turn every hard-coded repo name, slug, or branch pattern into an input. - [ ] Self-checks: actionlint everything, unit test anything with real logic. - [ ] Tag `v1.0.0`. diff --git a/tests/actions/push-translations/push-translations.test.js b/tests/actions/push-translations/push-translations.test.js new file mode 100644 index 00000000..56ac8503 --- /dev/null +++ b/tests/actions/push-translations/push-translations.test.js @@ -0,0 +1,341 @@ +'use strict' + +const { afterEach, describe, it } = require('node:test') +const assert = require('node:assert') +const fs = require('node:fs') +const os = require('node:os') +const path = require('node:path') + +const { + runPushTranslations, + runReadResult, + readInputs, +} = require('../../../.github/actions/push-translations/push-translations.js') +const { coreWithOutputs } = require('../../support/actions.js') + +const BUILD_ID = '0123456789abcdef0123456789abcdef' + +/** What The Events Calendar passes, with the defaults of action.yml filled in. */ +const TEC = { + INPUT_PROJECT: 'the-events-calendar', + INPUT_POT_PATH: 'lang/the-events-calendar.pot', + INPUT_REMOTE_FOLDER: 'tec/', + INPUT_SITE_DIRECTORY: 'translations.stellarwp.com/html/', + INPUT_RESULT_URL: 'https://translations.stellarwp.com/bot-output/', + INPUT_HOST: 'ssh.example.com', + INPUT_USER: 'deploy', + INPUT_SSH_KEY: '-----BEGIN OPENSSH PRIVATE KEY-----\nabc\n-----END OPENSSH PRIVATE KEY-----', + INPUT_POT_LOCATION: '/home/deploy/pots/', +} + +/** What GiveWP passes: a project under a parent, and its own remote folder. */ +const GIVE = { + ...TEC, + INPUT_PROJECT: 'givewp/give', + INPUT_POT_PATH: 'languages/give.pot', + INPUT_REMOTE_FOLDER: 'givewp', +} + +describe('push-translations', () => { + it('accepts the TEC shape', () => { + assert.deepStrictEqual(readInputs(TEC, BUILD_ID), { + project: 'the-events-calendar', + 'pot-path': 'lang/the-events-calendar.pot', + host: 'ssh.example.com', + user: 'deploy', + 'remote-path': '/home/deploy/pots/tec/', + 'remote-pot': '/home/deploy/pots/tec/the-events-calendar.pot', + 'site-directory': 'translations.stellarwp.com/html', + 'result-file': `the-events-calendar-${BUILD_ID}`, + 'result-url': `https://translations.stellarwp.com/bot-output/the-events-calendar-${BUILD_ID}`, + }) + }) + + it('accepts the Give shape', () => { + assert.deepStrictEqual(readInputs(GIVE, BUILD_ID), { + project: 'givewp/give', + 'pot-path': 'languages/give.pot', + host: 'ssh.example.com', + user: 'deploy', + 'remote-path': '/home/deploy/pots/givewp/', + 'remote-pot': '/home/deploy/pots/givewp/give.pot', + 'site-directory': 'translations.stellarwp.com/html', + 'result-file': `give-${BUILD_ID}`, + 'result-url': `https://translations.stellarwp.com/bot-output/give-${BUILD_ID}`, + }) + }) + + it('trims the values, and takes a POT at the root and an absolute site directory', () => { + const read = readInputs( + { ...TEC, INPUT_POT_PATH: ' give.pot\n', INPUT_SITE_DIRECTORY: '/var/www/site', INPUT_HOST: '10.0.0.1\n' }, + BUILD_ID + ) + + assert.strictEqual(read['pot-path'], 'give.pot') + assert.strictEqual(read['site-directory'], '/var/www/site') + }) + + it('returns host and user without the newlines around them, which the later steps connect with', () => { + const read = readInputs({ ...TEC, INPUT_HOST: '\nssh.example.com\n', INPUT_USER: ' deploy\n' }, BUILD_ID) + + assert.strictEqual(read.host, 'ssh.example.com') + assert.strictEqual(read.user, 'deploy') + }) + + it('refuses a newline inside host or user', () => { + for (const input of ['INPUT_HOST', 'INPUT_USER']) { + assert.throws(() => readInputs({ ...TEC, [input]: 'example\nid' }, BUILD_ID), /Nothing was sent/) + } + }) + + it('gives each run a build id of its own, 32 hex characters', () => { + const [first, second] = [readInputs(TEC), readInputs(TEC)] + + assert.match(first['result-file'], /^the-events-calendar-[a-f0-9]{32}$/) + assert.notStrictEqual(first['result-file'], second['result-file']) + }) + + it('refuses a build id that is not 32 hex characters', () => { + assert.throws(() => readInputs(TEC, 'abc; rm -rf ~'), /build id/) + }) + + const refused = { + 'a shell metacharacter in project': { INPUT_PROJECT: 'give; rm -rf ~' }, + 'a command substitution in project': { INPUT_PROJECT: 'give$(id)' }, + 'a backtick in project': { INPUT_PROJECT: 'give`id`' }, + 'a space in project': { INPUT_PROJECT: 'give wp' }, + 'a parent directory in project': { INPUT_PROJECT: '../give' }, + 'an option as project': { INPUT_PROJECT: '--path=/tmp' }, + 'an absolute project': { INPUT_PROJECT: '/givewp/give' }, + 'an empty project': { INPUT_PROJECT: '' }, + 'a pipe in remote-folder': { INPUT_REMOTE_FOLDER: 'tec|cat' }, + 'a parent directory in remote-folder': { INPUT_REMOTE_FOLDER: 'tec/../..' }, + 'an absolute remote-folder': { INPUT_REMOTE_FOLDER: '/tec' }, + 'an empty remote-folder': { INPUT_REMOTE_FOLDER: ' ' }, + 'a quote in site-directory': { INPUT_SITE_DIRECTORY: "html' && id '" }, + 'a parent directory in site-directory': { INPUT_SITE_DIRECTORY: '../html' }, + 'a home shorthand in site-directory': { INPUT_SITE_DIRECTORY: '~/html' }, + 'an empty site-directory': { INPUT_SITE_DIRECTORY: '' }, + 'a pot-path that is not a .pot': { INPUT_POT_PATH: 'languages/give.php' }, + 'a space in pot-path': { INPUT_POT_PATH: 'languages/give wp.pot' }, + 'a parent directory in pot-path': { INPUT_POT_PATH: '../../etc/give.pot' }, + 'an absolute pot-path': { INPUT_POT_PATH: '/etc/give.pot' }, + 'a metacharacter in pot-path': { INPUT_POT_PATH: 'languages/$(id).pot' }, + 'a newline inside pot-path': { INPUT_POT_PATH: 'languages/give.pot\nid.pot' }, + 'an empty pot-path': { INPUT_POT_PATH: '' }, + 'a result-url that is not https': { INPUT_RESULT_URL: 'http://translations.stellarwp.com/bot-output/' }, + 'a file result-url': { INPUT_RESULT_URL: 'file:///etc/passwd' }, + 'a result-url with a query': { INPUT_RESULT_URL: 'https://translations.stellarwp.com/bot-output/?a=b' }, + 'a result-url with credentials': { INPUT_RESULT_URL: 'https://user:pass@translations.stellarwp.com/' }, + 'an empty result-url': { INPUT_RESULT_URL: '' }, + 'a metacharacter in host': { INPUT_HOST: 'example.com;id' }, + 'an option as host': { INPUT_HOST: '-oProxyCommand=id' }, + 'an empty host': { INPUT_HOST: '' }, + 'a space in user': { INPUT_USER: 'deploy -o x' }, + 'an empty user': { INPUT_USER: undefined }, + 'an empty ssh-key': { INPUT_SSH_KEY: ' \n' }, + 'a relative pot-location': { INPUT_POT_LOCATION: 'pots/' }, + 'a parent directory in pot-location': { INPUT_POT_LOCATION: '/home/deploy/../root/' }, + 'a metacharacter in pot-location': { INPUT_POT_LOCATION: '/home/deploy/pots/ && id' }, + 'an empty pot-location': { INPUT_POT_LOCATION: '' }, + } + + for (const [name, inputs] of Object.entries(refused)) { + it(`refuses ${name}`, () => { + const input = Object.keys(inputs)[0].replace('INPUT_', '').toLowerCase().replace(/_/g, '-') + + assert.throws( + () => readInputs({ ...TEC, ...inputs }, BUILD_ID), + new RegExp(`^Error: ${input} .*Nothing was sent to the translations server\\.$`, 's') + ) + }) + } + + it('does not repeat a value that comes from a secret in the message', () => { + for (const input of ['INPUT_HOST', 'INPUT_USER', 'INPUT_POT_LOCATION']) { + assert.throws( + () => readInputs({ ...TEC, [input]: 's3cret value' }, BUILD_ID), + (error) => !error.message.includes('s3cret') + ) + } + }) + + it('masks the build id, sets the validated values as outputs, and leaves the summary empty', async (t) => { + const { core, outputs, summary } = await coreWithOutputs(t) + + // core is a module namespace, so its calls are recorded through a wrapper. + const calls = [] + const recording = { + ...core, + setSecret: (value) => calls.push(['secret', value]) && core.setSecret(value), + setOutput: (name, value) => calls.push(['output', name]) && core.setOutput(name, value), + } + + await runPushTranslations({ core: recording, env: GIVE }) + + const set = outputs() + // The build id is masked before any output carries it, so the log shows *** in its place. + assert.deepStrictEqual(calls[0], ['secret', set['result-file'].slice(-32)]) + assert.strictEqual(calls.filter(([kind]) => kind === 'secret').length, 1) + assert.strictEqual(set.project, 'givewp/give') + assert.strictEqual(set['remote-pot'], '/home/deploy/pots/givewp/give.pot') + assert.match(set['result-file'], /^give-[a-f0-9]{32}$/) + assert.strictEqual(set['result-url'], `https://translations.stellarwp.com/bot-output/${set['result-file']}`) + assert.strictEqual(summary(), '') + assert.strictEqual(set.host, 'ssh.example.com') + assert.strictEqual(set.user, 'deploy') + // The key is never an output: the later steps take it from the input. + assert.ok(!Object.values(set).some((value) => value.includes('PRIVATE KEY'))) + }) +}) + +describe('runReadResult', () => { + /** A fetch that answers once and records the URL it was asked for. */ + const fetchOf = (status, body) => { + const urls = [] + + return { urls, fetchImpl: async (url) => (urls.push(url), new Response(body, { status })) } + } + + it('sets what the import printed as the output, several lines included', async (t) => { + const { core, outputs, summary } = await coreWithOutputs(t) + const { urls, fetchImpl } = fetchOf(200, '3 new strings added\n1 string obsoleted\n') + + await runReadResult({ core, env: { RESULT_URL: 'https://example.com/bot-output/give-abc' }, fetchImpl }) + + assert.deepStrictEqual(urls, ['https://example.com/bot-output/give-abc']) + assert.strictEqual(outputs()['glotpress-result'], '3 new strings added\n1 string obsoleted') + assert.match(summary(), /3 new strings added/) + }) + + it('fails when the site does not answer 200, and sets no output', async (t) => { + const { core, outputs } = await coreWithOutputs(t) + + await assert.rejects( + runReadResult({ core, env: { RESULT_URL: 'https://example.com/x' }, fetchImpl: fetchOf(404, 'no').fetchImpl }), + /answered 404/ + ) + assert.deepStrictEqual(outputs(), {}) + }) + + it('refuses a URL that is not https before any request', async (t) => { + const { core } = await coreWithOutputs(t) + const { urls, fetchImpl } = fetchOf(200, 'x') + + await assert.rejects(runReadResult({ core, env: { RESULT_URL: 'http://example.com/x' }, fetchImpl }), /no https URL/) + assert.deepStrictEqual(urls, []) + }) +}) + +describe('the pot-path default', () => { + const dirs = [] + + afterEach(() => { + dirs.splice(0).forEach((dir) => fs.rmSync(dir, { recursive: true, force: true })) + }) + + /** An empty temporary directory, removed after the test. */ + const tempDir = () => { + dirs.push(fs.mkdtempSync(path.join(os.tmpdir(), 'push-translations-'))) + return dirs.at(-1) + } + + /** + * A workspace holding one plugin file with the given header lines. + * + * @param {string} header The header lines, one per line. + * + * @returns {string} The workspace directory. + */ + function workspace(header) { + const dir = tempDir() + fs.writeFileSync(path.join(dir, 'give.php'), `/.pot from the plugin header when pot-path is empty', () => { + const env = { ...GIVE, INPUT_POT_PATH: '', GITHUB_WORKSPACE: workspace(' * Text Domain: give\n * Domain Path: /languages/') } + + assert.strictEqual(readInputs(env, BUILD_ID)['pot-path'], 'languages/give.pot') + }) + + it('is not used when pot-path is given', () => { + const env = { ...GIVE, GITHUB_WORKSPACE: workspace(' * Text Domain: other\n * Domain Path: /lang') } + + assert.strictEqual(readInputs(env, BUILD_ID)['pot-path'], 'languages/give.pot') + }) + + describe('with working-directory', () => { + /** + * A workspace with one plugin at its top and another checked out in `plugin/`. + * + * @returns {string} The workspace directory. + */ + function workspaceWithCheckout() { + const dir = workspace(' * Text Domain: root\n * Domain Path: /lang') + fs.mkdirSync(path.join(dir, 'plugin')) + fs.writeFileSync( + path.join(dir, 'plugin', 'give.php'), + ' { + const env = { ...GIVE, INPUT_WORKING_DIRECTORY: 'plugin', GITHUB_WORKSPACE: workspaceWithCheckout() } + const read = readInputs(env, BUILD_ID) + + assert.strictEqual(read['pot-path'], 'plugin/languages/give.pot') + assert.strictEqual(read['remote-pot'], '/home/deploy/pots/givewp/give.pot') + assert.strictEqual(read['result-file'], `give-${BUILD_ID}`) + }) + + it('reads the plugin header in the checkout when pot-path is empty', () => { + const env = { ...GIVE, INPUT_POT_PATH: '', INPUT_WORKING_DIRECTORY: 'plugin', GITHUB_WORKSPACE: workspaceWithCheckout() } + + assert.strictEqual(readInputs(env, BUILD_ID)['pot-path'], 'plugin/languages/give.pot') + }) + + it('takes ./, a trailing /, an absolute path inside the workspace, and . for the workspace', () => { + const dir = workspaceWithCheckout() + const potPath = (given) => + readInputs({ ...GIVE, INPUT_WORKING_DIRECTORY: given, GITHUB_WORKSPACE: dir }, BUILD_ID)['pot-path'] + + assert.strictEqual(potPath(' ./plugin/\n'), 'plugin/languages/give.pot') + assert.strictEqual(potPath(path.join(dir, 'plugin')), 'plugin/languages/give.pot') + assert.strictEqual(potPath('.'), 'languages/give.pot') + }) + + it('refuses a working-directory that is missing, outside the workspace, or not plain names', () => { + const dir = workspaceWithCheckout() + fs.mkdirSync(path.join(dir, 'my plugin')) + + for (const given of ['missing', '..', tempDir(), 'my plugin']) { + assert.throws( + () => readInputs({ ...GIVE, INPUT_WORKING_DIRECTORY: given, GITHUB_WORKSPACE: dir }, BUILD_ID), + /^Error: working-directory .*Nothing was sent to the translations server\.$/s, + given + ) + } + }) + }) + + const refused = { + 'no plugin file': null, + 'no Text Domain': ' * Domain Path: /languages', + 'no Domain Path': ' * Text Domain: give', + 'the root as its Domain Path': ' * Text Domain: give\n * Domain Path: /', + 'a Text Domain that is not a file name': ' * Text Domain: give $(id)\n * Domain Path: /languages', + } + + for (const [name, header] of Object.entries(refused)) { + it(`refuses an empty pot-path when the header has ${name}`, () => { + const dir = header === null ? tempDir() : workspace(header) + + assert.throws( + () => readInputs({ ...GIVE, INPUT_POT_PATH: '', GITHUB_WORKSPACE: dir }, BUILD_ID), + /^Error: pot-path .*Nothing was sent to the translations server\.$/s + ) + }) + } +}) diff --git a/tests/lib/plugin-header.test.js b/tests/lib/plugin-header.test.js new file mode 100644 index 00000000..4bb55c77 --- /dev/null +++ b/tests/lib/plugin-header.test.js @@ -0,0 +1,76 @@ +'use strict' + +const { describe, it, beforeEach, afterEach } = require('node:test') +const assert = require('node:assert/strict') +const fs = require('node:fs') +const os = require('node:os') +const path = require('node:path') + +const { readPluginHeader } = require('../../.github/lib/plugin-header.js') + +describe('readPluginHeader', () => { + let dir + + const write = (name, body) => { + fs.mkdirSync(path.dirname(path.join(dir, name)), { recursive: true }) + fs.writeFileSync(path.join(dir, name), body) + } + + beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'plugin-header-')) + }) + + afterEach(() => { + fs.rmSync(dir, { recursive: true, force: true }) + }) + + it('reads the Text Domain and Domain Path of the top-level PHP file with a Plugin Name', () => { + write('helpers.php', ' { + write('other-plugin.php', ' { + write('plugin.php', ' { + write('plugin.php', ' { + write('b.php', ' { + write('plugin.php', ` { + write('plugin.php', ' { + assert.equal(readPluginHeader(path.join(dir, 'nowhere')), null) + }) +})