Commit 4ac4c952cb5 for woocommerce
commit 4ac4c952cb586c2c5e84beb4fc79124b72f27c64
Author: Ján Mikláš <neosinner@gmail.com>
Date: Tue Nov 17 19:39:45 2026 +0100
Share extension packaging and test commands (#71068)
* Share extension packaging and test commands
* Add extension commands changelog entry
diff --git a/packages/js/extension-tooling/README.md b/packages/js/extension-tooling/README.md
index 5989aa7925e..3f91f4c8427 100644
--- a/packages/js/extension-tooling/README.md
+++ b/packages/js/extension-tooling/README.md
@@ -15,6 +15,38 @@ Use `--github-output` to write the normalized JSON to `GITHUB_OUTPUT` under `jso
To run the reader before installing dependencies, get `bin/woo-config.sh` and `bin/woo-config.schema.json` from the same reviewed commit of this package. Keep the files in the same directory and run `bash /path/to/woo-config.sh` from the extension root.
+## Packaging and test commands
+
+Run `pnpm exec woo-extension-tooling <command> [args]` from the extension root. Call the same command without `pnpm exec` inside package scripts. Existing build steps, ZIP excludes, hooks, and environment scripts stay in the extension.
+
+| Command | Use |
+| ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `build-zip [commit]` | Run the configured build and write `deploy/<slug>.zip`. A commit argument selects committed files when the build step is empty. |
+| `makepot` | Generate `languages/<slug>.pot` from the extension's translation settings with WP-CLI. |
+| `e2e <mode> [args]` | Keep the existing `prepare`, `start`, `setup`, `reset`, `run`, and `with-env` modes. `prepare` extracts the ZIP and calls the extension's `bin/link_plugins.js`. |
+| `phpunit [setup\|run\|help] [args]` | Provision the wp-env test site or run its PHPUnit suite. Use `phpunit direct <config> [args]` for an extension that already provisions the site separately. |
+| `phplint [paths]`, `phpcs [args]`, `phpcs-baseline [args]` | Check PHP syntax, report PHPCS findings outside the baseline, or generate a baseline with the extension's Composer tools. |
+| `phpcompat [archive]` | Check the supplied production ZIP, or run the extension's `build:zip` script first. |
+
+Choose a single folder name for `config.woo.zip.root`. When `build-zip` receives a commit, it runs that commit's staging hook from the archived source directory. The checkout's `package.json` must match the selected commit. If it differs, check out the commit and run `build-zip` there.
+
+`e2e setup` uses the extension's `build:zip` script unless `E2E_PLUGIN_ZIP` supplies a ZIP. It calls `bin/link_plugins.js` to write `.wp-env.e2e.json`, `wp-env:e2e` to manage the site, and `env:test:e2e:seed` to seed it. `e2e with-env` also calls `test:e2e` to run the suite.
+
+`phpcs-baseline` uses the scan paths set by the extension's PHPCS ruleset. Declare at least one `<file>` entry in the ruleset.
+
+For hosts with Composer and no Node.js, check out this package's `bin` directory from a reviewed WooCommerce commit and run its Bash files directly. Install the tools used by the selected command, such as `jq` for configuration, `rsync` and `zip` for packaging, `unzip` for ZIP checks, `git` for syntax checks, and WP-CLI for POT generation. Keep `woo-config.sh` and `woo-config.schema.json` alongside the commands that read extension configuration. For example, from the extension root:
+
+```sh
+bash "$EXTENSION_TOOLING_BIN/install.sh" wordpress_test root root 127.0.0.1 7.0 11.2.0
+bash "$EXTENSION_TOOLING_BIN/phplint.sh" .
+bash "$EXTENSION_TOOLING_BIN/phpcs.sh" .
+bash "$EXTENSION_TOOLING_BIN/phpcompat.sh" deploy/example-extension.zip
+```
+
+Set `EXTENSION_TOOLING_BIN` to the absolute path of that `bin` directory. The installer uses Git, Subversion, curl or wget, and a MySQL client to reset and provision the selected test database and directories. It accepts a numeric WordPress release, `latest`, or `nightly`, and a WooCommerce tag, `latest`, or `trunk`. WordPress `nightly` tracks trunk. WordPress `latest` uses the same resolved release for the core and test library. The installer resolves relative `WP_TESTS_DIR`, `WP_CORE_DIR`, and `WC_CORE_DIR` paths from the invocation directory.
+
+The Bash ZIP command works without Node.js when `config.woo.zip.build` is empty and the extension's staging hook and Composer scripts, if present, also work on that host.
+
## Webpack
Import the helpers from the extension's webpack configuration. Keep the entry paths, output paths and match patterns in that configuration.
diff --git a/packages/js/extension-tooling/bin/build-zip.sh b/packages/js/extension-tooling/bin/build-zip.sh
new file mode 100644
index 00000000000..3efcf964628
--- /dev/null
+++ b/packages/js/extension-tooling/bin/build-zip.sh
@@ -0,0 +1,90 @@
+#!/usr/bin/env bash
+#
+# Packages the plugin as deploy/<slug>.zip with one root folder, config.woo.zip.root
+# (default: the slug).
+#
+# Usage: woo-extension-tooling build-zip [<commit>], from the plugin root.
+# Without a commit: runs the config.woo.zip.build package script (default `build`; empty for
+# none), then packages the current checkout, uncommitted and untracked files included.
+# With a commit: packages the files committed at it, for plugins without a build step.
+#
+# Steps: copy the source into a staging folder (never .git, node_modules, deploy or vendor),
+# install production Composer dependencies there when config.woo.zip.composerProduction is true,
+# run bin/hooks/build-zip-stage.sh <staging folder> when the repository has it, then zip the
+# staging folder without the paths that the exclude list (config.woo.zip.exclude, default
+# exclude.lst) names. The exclude list has one `zip -x` wildcard per line, matched against
+# `<root>/<path>`; a leading `/` anchors a line at the plugin root, and `#` starts a comment.
+set -euo pipefail
+
+root=$PWD
+
+config=$(bash "$(dirname "$0")/woo-config.sh")
+name=$(jq -r .slug <<< "$config")
+plugin_dir=$(jq -r .zip.root <<< "$config")
+case "$plugin_dir" in
+ ''|.|..|-*|*/*|*\\*)
+ echo 'zip.root must be a single folder name without path separators or a leading hyphen.' >&2
+ exit 1
+ ;;
+esac
+exclude=$(jq -r .zip.exclude <<< "$config")
+build=$(jq -r '.zip.build // ""' <<< "$config")
+composer_production=$(jq -r .zip.composerProduction <<< "$config")
+ref=${1:-}
+
+work=$(mktemp -d)
+trap 'rm -rf -- "$work"' EXIT
+
+source_dir=$root
+if [[ -n "$ref" ]]; then
+ if [[ -n "$build" ]]; then
+ echo "Packaging a commit needs a plugin without a build step (config.woo.zip.build is \"$build\"). Check the commit out and run the ZIP build there." >&2
+ exit 1
+ fi
+ commit=$(git rev-parse --verify --end-of-options "$ref^{commit}")
+ git diff --quiet "$commit" -- package.json || { echo "package.json differs from $commit; check the commit out instead." >&2; exit 1; }
+ source_dir=$work/source
+ mkdir "$source_dir"
+ git archive --format=tar "$commit" | tar -x -C "$source_dir"
+elif [[ -n "$build" ]]; then
+ pnpm run "$build"
+fi
+
+if [[ ! -f "$source_dir/$exclude" ]]; then
+ echo "Missing exclude list: $exclude" >&2
+ exit 1
+fi
+
+stage=$work/stage/$plugin_dir
+mkdir -p "$stage"
+rsync -a --exclude=/.git --exclude=/node_modules --exclude=/deploy --exclude=/vendor "$source_dir/" "$stage/"
+
+if [[ "$composer_production" == true ]]; then
+ # Composer reads the package's Git version and revision through this pointer.
+ if git_dir=$(git -C "$root" rev-parse --absolute-git-dir 2>/dev/null); then
+ printf 'gitdir: %s\n' "$git_dir" > "$stage/.git"
+ fi
+ (cd "$stage" && composer install --no-dev --prefer-dist --no-progress --no-interaction)
+ rm -f "$stage/.git"
+fi
+
+if [[ -f "$source_dir/bin/hooks/build-zip-stage.sh" ]]; then
+ (cd "$source_dir" && bash bin/hooks/build-zip-stage.sh "$stage")
+fi
+
+# Anchor `/` lines at the plugin folder and drop comments and blank lines.
+patterns=$work/exclude.lst
+while IFS= read -r line || [[ -n "$line" ]]; do
+ line=${line%$'\r'}
+ [[ -z "$line" || "$line" == \#* ]] && continue
+ if [[ "$line" == /* ]]; then
+ line="$plugin_dir$line"
+ fi
+ printf '%s\n' "$line"
+done < "$source_dir/$exclude" > "$patterns"
+
+(cd "$work/stage" && zip -qr "$work/plugin.zip" "$plugin_dir" -x "@$patterns")
+
+mkdir -p deploy
+mv "$work/plugin.zip" "deploy/$name.zip"
+echo "Built deploy/$name.zip"
diff --git a/packages/js/extension-tooling/bin/e2e.sh b/packages/js/extension-tooling/bin/e2e.sh
new file mode 100644
index 00000000000..51b5b55c22f
--- /dev/null
+++ b/packages/js/extension-tooling/bin/e2e.sh
@@ -0,0 +1,189 @@
+#!/usr/bin/env bash
+#
+# Playwright E2E runner. The browser test site (.wp-env.e2e.json, `pnpm run wp-env:e2e`) runs
+# the packaged plugin: `prepare` unzips deploy/<name>.zip (or $E2E_PLUGIN_ZIP) into
+# deploy/e2e-plugin/, and the repository's bin/link_plugins.js writes .wp-env.e2e.json from
+# .wp-env.test.json with that folder in place of ".".
+#
+# Usage: woo-extension-tooling e2e [ prepare | start | setup | reset | run [playwright args] | with-env [playwright args] | help ]
+set -euo pipefail
+
+config=$(bash "$(dirname "$0")/woo-config.sh")
+plugin_dir=$(jq -r .zip.root <<< "$config")
+main_file=$(jq -r '.mainFile | split("/") | last' <<< "$config")
+zip_name=$(jq -r .slug <<< "$config")
+subcommand=${1:-help}
+shift || true
+
+usage() {
+ cat <<-'USAGE'
+ Playwright E2E runner for the browser test site (.wp-env.e2e.json).
+
+ pnpm run test:e2e:setup Package the plugin, start the site, reset and seed it (leaves it up)
+ pnpm run test:e2e Run Playwright against the running site; arguments go to `playwright test`
+ pnpm run test:e2e:reset Reset the database and seed it again
+ pnpm run test:e2e:with-env Full pipeline, as CI: setup, the whole suite, then stop the site
+ woo-extension-tooling e2e prepare Unzip the package and write .wp-env.e2e.json only
+ woo-extension-tooling e2e start Start the site only
+
+ Environment:
+ E2E_PLUGIN_ZIP=<zip> Test this ZIP instead of building deploy/<name>.zip
+ E2E_WP_VERSION, E2E_WC_VERSION latest (default), nightly or a release tag
+ E2E_TARGET=<file> Spec files to run: a path or part of a file name (run only)
+ E2E_FILTER=<regex> Test titles or tags to run, as --grep (run only)
+ E2E_SHOW_UI=1 Show the browser, as --headed (run only)
+ WP_ENV_TESTS_PORT=<port> Port of the site, for worktrees (default 8889)
+ USAGE
+}
+
+prepare() {
+ local zip=${E2E_PLUGIN_ZIP:-}
+ if [[ -z "$zip" ]]; then
+ pnpm run build:zip
+ zip="deploy/$zip_name.zip"
+ fi
+ if [[ ! -f "$zip" ]]; then
+ echo "Plugin ZIP not found: $zip" >&2
+ exit 1
+ fi
+
+ mkdir -p deploy
+ rm -rf deploy/e2e-plugin
+ unzip -q "$zip" -d deploy/e2e-plugin
+ if [[ ! -f "deploy/e2e-plugin/$plugin_dir/$main_file" ]]; then
+ echo "Plugin ZIP must contain $plugin_dir/$main_file: $zip" >&2
+ exit 1
+ fi
+
+ export WP_VERSION=${E2E_WP_VERSION:-${WP_VERSION:-latest}}
+ export WC_VERSION=${E2E_WC_VERSION:-${WC_VERSION:-latest}}
+ [[ "$WP_VERSION" != trunk ]] || WP_VERSION=nightly
+ [[ "$WC_VERSION" != trunk ]] || WC_VERSION=nightly
+ if [[ "$WP_VERSION" != latest && "$WP_VERSION" != nightly && ! "$WP_VERSION" =~ ^[0-9]+\.[0-9]+(\.[0-9]+)?(-[[:alnum:]]+([.-][[:alnum:]]+)*)?$ ]]; then
+ echo "Invalid WordPress version: $WP_VERSION (expected latest, nightly or a release tag)" >&2
+ exit 1
+ fi
+ if [[ "$WC_VERSION" != latest && "$WC_VERSION" != nightly && ! "$WC_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[[:alnum:]]+([.-][[:alnum:]]+)*)?$ ]]; then
+ echo "Invalid WooCommerce version: $WC_VERSION (expected latest, nightly or a release tag)" >&2
+ exit 1
+ fi
+ if [[ -f bin/hooks/e2e-prepare.sh ]]; then
+ bash bin/hooks/e2e-prepare.sh
+ fi
+ node ./bin/link_plugins.js
+}
+
+start() {
+ # Start every site session with an empty log so the warnings check sees only this run.
+ mkdir -p tests/_output
+ : > tests/_output/e2e-debug.log
+ chmod a+rw tests/_output/e2e-debug.log
+ pnpm run wp-env:e2e start "$@"
+}
+
+reset() {
+ : > tests/_output/e2e-debug.log
+ pnpm run wp-env:e2e reset
+ pnpm run env:test:e2e:seed
+}
+
+run_playwright() {
+ local arg port
+ local args=( test --config tests/e2e/playwright.config.js )
+ [[ -z "${E2E_TARGET:-}" ]] || args+=( "$E2E_TARGET" )
+ [[ -z "${E2E_FILTER:-}" ]] || args+=( --grep "$E2E_FILTER" )
+ [[ -z "${E2E_SHOW_UI:-}" ]] || args+=( --headed )
+ args+=( "$@" )
+
+ for arg in "$@"; do
+ case "$arg" in
+ --list|--help|-h|--version|-V)
+ exec pnpm exec playwright "${args[@]}"
+ ;;
+ esac
+ done
+
+ if [[ -z "${WP_BASE_URL:-}" ]]; then
+ if ! port=$(pnpm --silent run wp-env:e2e status --json 2>/dev/null | node -e '
+ const { status, ports } = JSON.parse(require("node:fs").readFileSync(0, "utf8"));
+ const port = ports?.development;
+ if (status !== "running" || !/^\d+$/.test(port) || port < 1 || port > 65535) process.exit(1);
+ console.log(port);
+ ' 2>/dev/null); then
+ echo "The browser test site is unavailable. Run pnpm run test:e2e:setup or set WP_BASE_URL." >&2
+ return 1
+ fi
+ export WP_BASE_URL="http://localhost:$port"
+ export WP_ENV_TESTS_PORT="$port"
+ fi
+
+ exec pnpm exec playwright "${args[@]}"
+}
+
+stop_site() {
+ local result=$?
+ if ! pnpm run wp-env:e2e stop && [[ "$result" == 0 ]]; then
+ result=1
+ fi
+ exit "$result"
+}
+
+case "$subcommand" in
+ prepare)
+ prepare
+ ;;
+ start)
+ start "$@"
+ ;;
+ setup)
+ prepare
+ start --update
+ reset
+ ;;
+ reset)
+ reset
+ ;;
+ run)
+ run_playwright "$@"
+ ;;
+ with-env)
+ unset E2E_TARGET E2E_FILTER E2E_SHOW_UI
+ if [[ -f .wp-env.e2e.json ]]; then
+ # After a failed first start, `wp-env status` reports "Environment not initialized"
+ # and exits 1. That site has nothing to stop; prepare writes .wp-env.e2e.json again.
+ status_errors=$(mktemp)
+ if status=$(pnpm --silent run wp-env:e2e status --json 2> "$status_errors"); then
+ state=$(node -p 'JSON.parse(require("node:fs").readFileSync(0, "utf8")).status' <<< "$status" 2> /dev/null) || state=unknown
+ elif grep -q 'Environment not initialized' "$status_errors"; then
+ state=uninitialized
+ else
+ state=unknown
+ fi
+ rm -f "$status_errors"
+ case "$state" in
+ running)
+ echo "The test site is already running. Use pnpm run test:e2e." >&2
+ exit 1
+ ;;
+ stopped|uninitialized) ;;
+ *)
+ echo "Could not determine whether the test site is running." >&2
+ exit 1
+ ;;
+ esac
+ fi
+ prepare
+ trap stop_site EXIT
+ start --update
+ reset
+ pnpm run test:e2e "$@"
+ ;;
+ help|-h|--help)
+ usage
+ ;;
+ *)
+ echo "Unknown E2E command: $subcommand" >&2
+ usage >&2
+ exit 2
+ ;;
+esac
diff --git a/packages/js/extension-tooling/bin/install.sh b/packages/js/extension-tooling/bin/install.sh
new file mode 100644
index 00000000000..5acb01d9499
--- /dev/null
+++ b/packages/js/extension-tooling/bin/install.sh
@@ -0,0 +1,250 @@
+#!/usr/bin/env bash
+
+set -euo pipefail
+
+if [[ ${RUN_UNIT_TESTS:-} == 0 ]]; then
+ exit 0
+fi
+
+if [ $# -lt 3 ]; then
+ echo "Usage: $0 <db-name> <db-user> <db-pass> [db-host] [wp-version] [wc-version]"
+ exit 1
+fi
+
+DB_NAME=$1
+DB_USER=$2
+DB_PASS=$3
+DB_HOST=${4-localhost}
+WP_VERSION=${5-latest}
+WC_VERSION=${6-latest}
+
+TESTS_LIB_DIR="${WP_TESTS_DIR-/tmp/wordpress-tests-lib}"
+TESTS_WP_DIR="${WP_CORE_DIR-/tmp/wordpress}"
+TESTS_WC_DIR="${WC_CORE_DIR-/tmp/woocommerce}"
+
+# These paths must keep pointing to the same directories after changing cwd.
+for directory in TESTS_LIB_DIR TESTS_WP_DIR TESTS_WC_DIR; do
+ case "${!directory}" in
+ '')
+ echo 'WP_TESTS_DIR, WP_CORE_DIR and WC_CORE_DIR must be nonempty when set.' >&2
+ exit 1
+ ;;
+ /*) ;;
+ *) printf -v "$directory" '%s/%s' "$PWD" "${!directory}" ;;
+ esac
+done
+
+TESTS_DIR="$TESTS_WP_DIR/.."
+
+printf '%s\n' "$TESTS_LIB_DIR" "$TESTS_WP_DIR" "$TESTS_WC_DIR" "$TESTS_DIR"
+
+downloads=$(mktemp -d)
+trap 'rm -rf -- "$downloads"' EXIT
+
+download() {
+ if command -v curl >/dev/null; then
+ curl --fail --silent --show-error --proto '=https' "$1" > "$2"
+ elif command -v wget >/dev/null; then
+ wget -nv -O "$2" "$1"
+ else
+ echo 'Downloads require curl or wget.' >&2
+ return 1
+ fi
+}
+
+if [[ -z "$WC_VERSION" || "$WC_VERSION" == 'latest' ]]; then
+ echo "WooCommerce version not provided. Fetching latest tag from org..."
+ download https://api.wordpress.org/plugins/info/1.0/woocommerce.json "$downloads/woocommerce.json"
+ # shellcheck disable=SC2016 # The PHP process reads its own argument.
+ WC_VERSION=$(php -r '
+ $response = json_decode(file_get_contents($argv[1]), true);
+ $version = $response["version"] ?? null;
+ if (!is_string($version)) { exit(1); }
+ echo $version;
+ ' "$downloads/woocommerce.json") || {
+ echo 'Could not read the latest WooCommerce version from WordPress.org.' >&2
+ exit 1
+ }
+ echo "WooCommerce version fetched: $WC_VERSION"
+fi
+
+# Install exactly the requested ref: a tag (x.y.z, x.y.z-rc.N, nightly) or the trunk branch.
+# Never fall back to another version, so a matrix row always tests what its name says.
+if [[ $WC_VERSION == 'trunk' ]]; then
+ latestTag=trunk
+elif [[ -n $WC_VERSION ]] && git ls-remote --exit-code --refs --tags https://github.com/woocommerce/woocommerce "refs/tags/$WC_VERSION" > /dev/null; then
+ latestTag=$WC_VERSION
+else
+ echo "Error: WooCommerce version '$WC_VERSION' has no matching tag in woocommerce/woocommerce." >&2
+ exit 1
+fi
+
+# Only need to check normal versions. Betas and rcs are not supported.
+if [[ $WP_VERSION =~ ^[0-9]+(\.[0-9]+)*$ ]]; then
+ WP_TESTS_TAG="tags/$WP_VERSION"
+ WP_TARBALL="https://wordpress.org/wordpress-$WP_VERSION.tar.gz"
+elif [[ $WP_VERSION == 'nightly' ]]; then
+ WP_TESTS_TAG="trunk"
+elif [[ $WP_VERSION == 'latest' ]]; then
+ download https://api.wordpress.org/core/version-check/1.7/ "$downloads/wordpress.json"
+ # shellcheck disable=SC2016 # The PHP process reads its own argument.
+ LATEST_VERSION=$(php -r '
+ $response = json_decode(file_get_contents($argv[1]), true);
+ $version = $response["offers"][0]["version"] ?? null;
+ if (!is_string($version)) { exit(1); }
+ echo $version;
+ ' "$downloads/wordpress.json") || {
+ echo 'Could not read the latest WordPress version from WordPress.org.' >&2
+ exit 1
+ }
+ if [[ ! "$LATEST_VERSION" =~ ^[0-9]+\.[0-9]+(\.[0-9]+)?$ ]]; then
+ echo "Latest WordPress version could not be found" >&2
+ exit 1
+ fi
+ WP_TESTS_TAG="tags/$LATEST_VERSION"
+ WP_TARBALL="https://wordpress.org/wordpress-$LATEST_VERSION.tar.gz"
+else
+ echo "Invalid WordPress version: $WP_VERSION (expected latest, nightly or a numeric release)" >&2
+ exit 1
+fi
+
+install_wp() {
+ if [ -d "$TESTS_WP_DIR" ]; then
+ rm -rf -- "$TESTS_WP_DIR"
+ fi
+
+ mkdir -p -- "$TESTS_WP_DIR"
+
+ if [[ $WP_VERSION == 'nightly' ]]; then
+ download https://wordpress.org/nightly-builds/wordpress-latest.zip "$downloads/wordpress.zip"
+ unzip -q "$downloads/wordpress.zip" -d "$downloads"
+ cp -a "$downloads/wordpress/." "$TESTS_WP_DIR"
+ else
+ download "$WP_TARBALL" "$downloads/wordpress.tar.gz"
+ tar --strip-components=1 -zxmf "$downloads/wordpress.tar.gz" -C "$TESTS_WP_DIR"
+ fi
+ mkdir -p "$TESTS_WP_DIR/wp-content/uploads"
+}
+
+# Escapes a value for a PHP single-quoted string (backslash, quote), then for a sed `s|...|...|` replacement (backslash, &, |).
+sed_php_value() {
+ printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e "s/'/\\\\'/g" -e 's/[\\&|]/\\&/g'
+}
+
+install_test_suite() {
+ if [ -d "$TESTS_LIB_DIR" ]; then
+ rm -rf -- "$TESTS_LIB_DIR"
+ fi
+
+ local source="https://develop.svn.wordpress.org/$WP_TESTS_TAG"
+ mkdir -p -- "$TESTS_LIB_DIR"
+ svn co --quiet --ignore-externals "$source/tests/phpunit/includes/" "$TESTS_LIB_DIR/includes"
+ svn co --quiet --ignore-externals "$source/tests/phpunit/data/" "$TESTS_LIB_DIR/data"
+ download "$source/wp-tests-config-sample.php" "$downloads/wp-tests-config-sample.php"
+ sed -e "s|dirname( __FILE__ ) . '/src/'|'$(sed_php_value "$TESTS_WP_DIR")/'|" \
+ -e "/DB_NAME/s|youremptytestdbnamehere|$(sed_php_value "$DB_NAME")|" \
+ -e "/DB_USER/s|yourusernamehere|$(sed_php_value "$DB_USER")|" \
+ -e "/DB_PASSWORD/s|yourpasswordhere|$(sed_php_value "$DB_PASS")|" \
+ -e "/DB_HOST/s|localhost|$(sed_php_value "$DB_HOST")|" \
+ "$downloads/wp-tests-config-sample.php" > "$downloads/wp-tests-config.php"
+}
+
+install_db() {
+ local DB_HOSTNAME DB_SOCK_OR_PORT
+ if [[ "$DB_HOST" == :* ]]; then
+ # It's a socket, e.g. ':/path/to/socket'.
+ DB_HOSTNAME=""
+ DB_SOCK_OR_PORT=${DB_HOST#:}
+ elif [[ "$DB_HOST" == *:* ]]; then
+ DB_HOSTNAME=${DB_HOST%:*}
+ DB_SOCK_OR_PORT=${DB_HOST##*:}
+ else
+ DB_HOSTNAME=$DB_HOST
+ DB_SOCK_OR_PORT=""
+ fi
+
+ local mysql_args=(--user="$DB_USER" --password="$DB_PASS")
+
+ if [[ -n $DB_SOCK_OR_PORT && ! $DB_SOCK_OR_PORT =~ ^[0-9]+$ ]]; then
+ mysql_args+=(--socket="$DB_SOCK_OR_PORT")
+ elif [[ -n $DB_HOSTNAME && -n $DB_SOCK_OR_PORT ]]; then
+ mysql_args+=(--host="$DB_HOSTNAME" --port="$DB_SOCK_OR_PORT" --protocol=tcp)
+ elif [[ -n $DB_HOSTNAME ]]; then
+ mysql_args+=(--host="$DB_HOSTNAME" --protocol=tcp)
+ fi
+
+ printf "drop database if exists \`%s\`\n" "${DB_NAME//\`/\`\`}" | mysql "${mysql_args[@]}"
+ mysqladmin "${mysql_args[@]}" create "$DB_NAME"
+
+ # Get the current PHP version
+ php_version=$(php -r 'echo PHP_VERSION;')
+
+ # For PHP version 7.0, change the default mysql authentication plugin to "mysql_native_password"
+ # as "caching_sha2_password" is not supported
+ # This is not needed if using MySQL server from LocalWP (and it will fail)
+ if [[ "$php_version" == *"7.0"* ]]; then
+
+ # Update mysql configuration file.
+ echo "[mysqld]" | sudo tee -a /etc/mysql/my.cnf
+ echo "default_authentication_plugin=mysql_native_password" | sudo tee -a /etc/mysql/my.cnf
+
+ echo "Restarting MYSQL server..."
+ sudo systemctl restart mysql.service
+
+ # Update root user.
+ echo "ALTER USER '${DB_USER}'@'$DB_HOSTNAME' IDENTIFIED WITH mysql_native_password BY '${DB_PASS}'" | mysql --user="${DB_USER}" --password="${DB_PASS}"
+
+ # Debug statement
+ # echo "SELECT @@GLOBAL.default_authentication_plugin" | mysql --user=${DB_USER} --password=${DB_PASS}
+ fi
+}
+
+install_woocommerce() {
+
+ if [ -d "$TESTS_WC_DIR" ]; then
+ rm -rf -- "$TESTS_WC_DIR"
+ fi
+
+ cd "$TESTS_DIR"
+
+ if [ -e wc-tmp ]; then
+ rm -rf wc-tmp
+ fi
+
+ if [ -d wc-tmp-monorepo ]; then
+ rm -rf wc-tmp-monorepo
+ fi
+
+ git clone --depth=1 --branch="$latestTag" https://github.com/woocommerce/woocommerce wc-tmp-monorepo
+ ln -s "$TESTS_DIR/wc-tmp-monorepo/plugins/woocommerce" "$TESTS_DIR/wc-tmp"
+ cd wc-tmp-monorepo/plugins/woocommerce
+
+ composer install --no-dev --no-scripts --optimize-autoloader
+
+ # Load WooCommerce test helpers without installing its development dependencies.
+ composer dump-autoload --dev --no-scripts --optimize
+
+ php bin/generate-feature-config.php
+
+ cd "$TESTS_DIR"
+ mv wc-tmp "$TESTS_WC_DIR"
+}
+
+print_versions() {
+ local wp_version wc_version
+ # shellcheck disable=SC2016 # The PHP process reads its own argument and version.
+ wp_version=$(php -r 'require $argv[1]; echo $wp_version;' "$TESTS_WP_DIR/wp-includes/version.php")
+ wc_version=$(awk '/^[[:space:]]*\*[[:space:]]*Version:/{print $NF; exit}' "$TESTS_WC_DIR/woocommerce.php")
+ echo "Installed WordPress: $wp_version (requested: $WP_VERSION)"
+ echo "Installed WooCommerce: $wc_version (requested: $WC_VERSION, ref: $latestTag)"
+}
+
+# A failed WordPress extraction can otherwise leave a stale completion marker.
+rm -f -- "$TESTS_LIB_DIR/wp-tests-config.php"
+install_wp
+install_test_suite
+install_db
+install_woocommerce
+print_versions
+# The wp-env runner uses this file to detect a complete setup.
+mv "$downloads/wp-tests-config.php" "$TESTS_LIB_DIR/wp-tests-config.php"
diff --git a/packages/js/extension-tooling/bin/makepot.sh b/packages/js/extension-tooling/bin/makepot.sh
new file mode 100644
index 00000000000..59037cec592
--- /dev/null
+++ b/packages/js/extension-tooling/bin/makepot.sh
@@ -0,0 +1,58 @@
+#!/usr/bin/env bash
+#
+# Writes the translation template languages/<slug>.pot with WP-CLI `wp i18n make-pot`.
+# config.woo.makepot.exclude lists the paths to skip on top of the WP-CLI defaults, and
+# config.woo.makepot.headers sets POT headers.
+#
+# Usage: woo-extension-tooling makepot, from the plugin root.
+#
+# WP-CLI: vendor/bin/wp when Composer installed it, else `wp` on PATH. Fails when the main
+# file is missing or no template is written; an earlier template is kept until a new one is.
+set -euo pipefail
+
+config=$(bash "$(dirname "$0")/woo-config.sh")
+slug=$(jq -r .slug <<< "$config")
+main_file=$(jq -r .mainFile <<< "$config")
+exclude=$(jq -r '.makepot.exclude | join(",")' <<< "$config")
+headers=$(jq -c .makepot.headers <<< "$config")
+pot=languages/$slug.pot
+
+if [[ ! -f "$main_file" ]]; then
+ echo "Missing main plugin file: $main_file" >&2
+ exit 1
+fi
+
+# Xdebug is not needed here and slows extraction down; large plugins need more than 128M.
+php_args='-d xdebug.mode=off -d memory_limit=2048M'
+
+mkdir -p languages
+# A fresh temporary file per run, removed on any exit, so a failed or overlapping run never
+# leaves a partial template in languages/.
+tmp=$(mktemp "languages/.$slug.pot.XXXXXX")
+trap 'rm -f "$tmp"' EXIT
+
+args=(i18n make-pot . "$tmp" "--slug=$slug")
+[[ -z "$exclude" ]] || args+=("--exclude=$exclude")
+[[ "$headers" == '{}' ]] || args+=("--headers=$headers")
+
+if [[ -x vendor/bin/wp ]]; then
+ wp=vendor/bin/wp
+elif ! wp=$(command -v wp); then
+ echo 'WP-CLI not found: run composer install or put wp on PATH.' >&2
+ exit 1
+fi
+# The phar starts with a php shebang. A Composer or WP-CLI launcher is a shell script that
+# passes WP_CLI_PHP_ARGS to PHP; handing it to php would print it instead of running it.
+if head -n 1 "$wp" | grep -q php; then
+ # shellcheck disable=SC2086 # php_args holds several options.
+ php $php_args "$wp" "${args[@]}"
+else
+ WP_CLI_PHP_ARGS=$php_args "$wp" "${args[@]}"
+fi
+
+if [[ ! -s "$tmp" ]]; then
+ echo "WP-CLI did not write $pot." >&2
+ exit 1
+fi
+chmod 644 "$tmp"
+mv "$tmp" "$pot"
diff --git a/packages/js/extension-tooling/bin/phpcompat.sh b/packages/js/extension-tooling/bin/phpcompat.sh
new file mode 100644
index 00000000000..c4336363ef5
--- /dev/null
+++ b/packages/js/extension-tooling/bin/phpcompat.sh
@@ -0,0 +1,23 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+if [ "$#" -gt 1 ]; then
+ echo "Usage: pnpm run phpcompat [production.zip]" >&2
+ exit 1
+fi
+
+# The ZIP name and its root folder come from package.json config.woo.
+slug="$(bash "$(dirname "$0")/woo-config.sh" .slug)"
+plugin_dir="$(bash "$(dirname "$0")/woo-config.sh" .zip.root)"
+if [ "$#" -eq 0 ]; then
+ pnpm run build:zip
+fi
+archive="${1:-deploy/$slug.zip}"
+
+# Keep the compatibility checker separate from development dependencies.
+composer --working-dir=tools/php-quality install --no-interaction --prefer-dist --no-progress
+production_dir="$(mktemp -d)"
+trap 'rm -rf "$production_dir"' EXIT
+unzip -q "$archive" -d "$production_dir"
+php tools/php-quality/vendor/bin/phpcs "$production_dir/$plugin_dir" \
+ --standard=phpcs-compat.xml.dist -ps --basepath="$production_dir/$plugin_dir"
diff --git a/packages/js/extension-tooling/bin/phpcs-baseline.sh b/packages/js/extension-tooling/bin/phpcs-baseline.sh
new file mode 100644
index 00000000000..79382c02e2a
--- /dev/null
+++ b/packages/js/extension-tooling/bin/phpcs-baseline.sh
@@ -0,0 +1,22 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+report="$(mktemp)"
+trap 'rm -f "$report"' EXIT
+status=0
+php vendor/bin/phpcs -q --report=json > "$report" || status=$?
+case "$status" in
+ 0|1|2) ;;
+ 3)
+ # shellcheck disable=SC2016 # The PHP process reads its own argument.
+ if ! php -r 'exit(is_array(json_decode(file_get_contents($argv[1]), true)["files"] ?? null) ? 0 : 1);' "$report"; then
+ cat "$report"
+ exit "$status"
+ fi
+ ;;
+ *) cat "$report"; exit "$status" ;;
+esac
+
+SARB=vendor/bin/sarb
+[ -f "$SARB" ] || SARB=tools/php-quality/vendor/bin/sarb
+php "$SARB" create --input-format=phpcodesniffer-json phpcs.baseline "$@" < "$report"
diff --git a/packages/js/extension-tooling/bin/phpcs.sh b/packages/js/extension-tooling/bin/phpcs.sh
new file mode 100644
index 00000000000..4737490ebb0
--- /dev/null
+++ b/packages/js/extension-tooling/bin/phpcs.sh
@@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+
+# Runs PHPCS and reports only the findings that are not in the baseline (SARB).
+# Run it from the plugin root. `--tests` checks the tests with phpcs-tests.xml.dist and
+# phpcs-tests.baseline; other arguments go to PHPCS (default: the whole plugin).
+set -eu
+
+# SARB is a root Composer dependency, or a tools/php-quality one.
+SARB=vendor/bin/sarb
+[ -f "$SARB" ] || SARB=tools/php-quality/vendor/bin/sarb
+BASELINE=phpcs.baseline
+if [ "${1:-}" = --tests ]; then
+ BASELINE=phpcs-tests.baseline
+ shift
+ set -- --standard=phpcs-tests.xml.dist "$@"
+else
+ [ "$#" -gt 0 ] || set -- .
+fi
+
+REPORT=$(mktemp)
+trap 'rm -f "$REPORT"' EXIT
+
+# PHPCS 4 can return 3 with findings. PHPCS 3 returns 3 on tool errors.
+STATUS=0
+php vendor/bin/phpcs -q --report=json "$@" > "$REPORT" || STATUS=$?
+case "$STATUS" in
+ 0|1|2) ;;
+ 3)
+ # shellcheck disable=SC2016 # The PHP process reads its own argument.
+ if ! php -r 'exit(is_array(json_decode(file_get_contents($argv[1]), true)["files"] ?? null) ? 0 : 1);' "$REPORT"; then
+ cat "$REPORT"
+ exit "$STATUS"
+ fi
+ ;;
+ *) cat "$REPORT"; exit "$STATUS" ;;
+esac
+
+# SARB's diff parser requires Git's standard a/ and b/ prefixes.
+GIT_CONFIG_COUNT=${GIT_CONFIG_COUNT:-0}
+for SETTING in diff.mnemonicPrefix diff.noprefix; do
+ export "GIT_CONFIG_KEY_${GIT_CONFIG_COUNT}=$SETTING"
+ export "GIT_CONFIG_VALUE_${GIT_CONFIG_COUNT}=false"
+ GIT_CONFIG_COUNT=$((GIT_CONFIG_COUNT + 1))
+done
+export GIT_CONFIG_COUNT
+
+if [ "${GITHUB_ACTIONS:-false}" = true ]; then
+ php "$SARB" remove "$BASELINE" --output-format=github < "$REPORT"
+else
+ php "$SARB" remove "$BASELINE" < "$REPORT"
+fi
diff --git a/packages/js/extension-tooling/bin/phplint.sh b/packages/js/extension-tooling/bin/phplint.sh
new file mode 100644
index 00000000000..ff3815daf31
--- /dev/null
+++ b/packages/js/extension-tooling/bin/phplint.sh
@@ -0,0 +1,18 @@
+#!/usr/bin/env bash
+
+# Checks the syntax of every tracked or new PHP file (ignored files excluded) with the PHP binary in use (`php -l`), one file per
+# call: PHP before 8.3 lints only the first file it is given. Reports every file that fails.
+# Run it from the plugin root. Arguments that are existing paths limit the check to them; others
+# are ignored, because `composer check:php -- <argument>` forwards its arguments to every step.
+set -euo pipefail
+
+paths=()
+for path in "$@"; do
+ if [[ -e "$path" ]]; then paths+=("$path"); fi
+done
+if [[ ${#paths[@]} -eq 0 ]]; then paths=(.); fi
+
+# A tracked file that was deleted without staging the removal has nothing to check.
+# shellcheck disable=SC2016 # $1 is read by the child shell for each file.
+git ls-files -z --cached --others --exclude-standard -- "${paths[@]}" | { grep -z '\.php$' || true; } \
+ | xargs -0 -n 1 -P 4 sh -c '[ ! -f "$1" ] || php -d display_errors=stderr -d log_errors=0 -l "$1" > /dev/null || exit 1' _
diff --git a/packages/js/extension-tooling/bin/phpunit.sh b/packages/js/extension-tooling/bin/phpunit.sh
new file mode 100644
index 00000000000..44d2df46530
--- /dev/null
+++ b/packages/js/extension-tooling/bin/phpunit.sh
@@ -0,0 +1,106 @@
+#!/usr/bin/env bash
+
+# PHPUnit runner for the wp-env tests site (.wp-env.test.json).
+#
+# Local only. CI installs the test suite in its own PHPUnit workflow (see .github/workflows/).
+#
+# USAGE
+# pnpm run test:php:env [phpunit args] Run PHPUnit; installs WP + WooCommerce on first run
+# pnpm run test:php:env:setup Reinstall WP + WooCommerce (e.g. after changing a version)
+# pnpm run test:php:env:help Show this message
+# woo-extension-tooling phpunit direct <config> [args] Use a pre-provisioned site
+#
+# OPTIONS (env vars)
+# WC_ORDER_DATASTORE=hpos Order storage: cpt (default) or hpos; CI runs both
+# UNIT_WC_VERSION=trunk WooCommerce: latest (default, as CI), nightly, trunk, or X.Y.Z (setup only)
+# UNIT_WP_VERSION=7.0 WordPress: latest (default, as CI), nightly, or X.Y[.Z] (setup only)
+# The variables in package.json config.woo.phpunit.passEnv are passed into the container when set.
+#
+# EXAMPLES
+# pnpm run test:php:env --filter <TestClassName>
+# WC_ORDER_DATASTORE=hpos pnpm run test:php:env
+# UNIT_WC_VERSION=trunk pnpm run test:php:env:setup && pnpm run test:php:env
+#
+# Worktrees: export WP_ENV_PORT / WP_ENV_TESTS_PORT first (see AGENTS.md).
+set -euo pipefail
+
+if [[ ! -f package.json ]]; then
+ echo 'No package.json here. Run this from the plugin root.' >&2
+ exit 1
+fi
+
+TESTS_DIR=/tmp/wordpress-tests-lib
+# wp-env mounts the checkout under its folder name, so this also works in worktrees.
+PLUGIN_DIR="wp-content/plugins/${PWD##*/}"
+
+usage() {
+ sed -n '/^# USAGE/,/^set -euo/p' "$0" | sed '$d; s/^# \{0,1\}//'
+}
+
+compose() {
+ local install_path
+ install_path=$(pnpm --silent run wp-env:test status --json | node -p 'JSON.parse(require("fs").readFileSync(0, "utf8")).installPath')
+ docker compose -f "${install_path}/docker-compose.yml" "$@"
+}
+
+# Same as `pnpm run wp-env:test run cli --env-cwd=<dir> <command>` (host user, so files it writes stay
+# ours), minus wp-env's argument parser, which turns `7.0` into `7` and keeps `--debug`,
+# `--help` and `--version` for itself.
+exec_tests_cli() {
+ compose exec -u "$(id -u):$(id -g)" -w "$1" cli "${@:2}"
+}
+
+setup() {
+ local installer
+ installer=$(cat "$(dirname "$0")/install.sh")
+ compose exec -T -u root cli apk add --no-cache subversion git
+ # Run from /tmp: in a git worktree, the checkout's .git points to a host path that
+ # doesn't exist in the container, which makes install.sh's `git ls-remote` fail.
+ # Pass the shared script as one argument so child commands can still read stdin.
+ exec_tests_cli /tmp \
+ env WP_TESTS_DIR="$TESTS_DIR" bash -c "$installer" install.sh wordpress_test root password mysql \
+ "${UNIT_WP_VERSION:-latest}" "${UNIT_WC_VERSION:-latest}"
+}
+
+run() {
+ if [ -z "$(compose ps -q --status running cli)" ]; then
+ echo "wp-env is not running. Start it with: pnpm run env:test:start (export WP_ENV_PORT / WP_ENV_TESTS_PORT first in a worktree)." >&2
+ exit 1
+ fi
+ # install.sh empties each directory before refilling it, so any missing file means a failed or interrupted setup.
+ # wp-tests-config.php is the last file the test library step writes, so it catches a setup that stopped partway through it.
+ if ! compose exec -T cli test -f /tmp/wordpress/wp-settings.php -a -f "${TESTS_DIR}/includes/functions.php" -a -f "${TESTS_DIR}/wp-tests-config.php" -a -f /tmp/woocommerce/woocommerce.php; then
+ echo "Test suite missing or incomplete in the tests site; running setup first."
+ setup
+ fi
+ # The suite's own test variables (config.woo.phpunit.passEnv), which CI sets on the host.
+ local env_args=(WP_TESTS_DIR="$TESTS_DIR" WC_ORDER_DATASTORE="${WC_ORDER_DATASTORE:-cpt}") pass_env var
+ pass_env=$(bash "$(dirname "$0")/woo-config.sh" '.phpunit.passEnv[]')
+ for var in $pass_env; do
+ if [ -n "${!var:-}" ]; then env_args+=("${var}=${!var}"); fi
+ done
+ exec_tests_cli "/var/www/html/${PLUGIN_DIR}" \
+ env "${env_args[@]}" php vendor/bin/phpunit -c phpunit.xml.dist --fail-on-empty-test-suite "$@"
+}
+
+case "${1:-run}" in
+ setup) setup ;;
+ run) shift || true; run "$@" ;;
+ direct)
+ shift
+ if [[ $# -eq 0 ]]; then
+ usage >&2
+ exit 1
+ fi
+ if [[ ! -f vendor/autoload.php ]]; then
+ echo 'Install the locked PHP dependencies with composer install first.' >&2
+ exit 1
+ fi
+ xml=$1
+ shift
+ exec pnpm run wp-env:test run cli --env-cwd="$PLUGIN_DIR" -- \
+ php vendor/bin/phpunit -c "$xml" --fail-on-empty-test-suite "$@"
+ ;;
+ help | -h | --help) usage ;;
+ *) usage; exit 1 ;;
+esac
diff --git a/packages/js/extension-tooling/bin/woo-extension-tooling.js b/packages/js/extension-tooling/bin/woo-extension-tooling.js
new file mode 100755
index 00000000000..399b5eca969
--- /dev/null
+++ b/packages/js/extension-tooling/bin/woo-extension-tooling.js
@@ -0,0 +1,42 @@
+#!/usr/bin/env node
+
+const { spawnSync } = require( 'node:child_process' );
+const { constants } = require( 'node:os' );
+const path = require( 'node:path' );
+
+const commands = [
+ 'build-zip',
+ 'install',
+ 'makepot',
+ 'e2e',
+ 'phpunit',
+ 'phplint',
+ 'phpcs',
+ 'phpcompat',
+ 'phpcs-baseline',
+];
+const [ command, ...args ] = process.argv.slice( 2 );
+
+if ( commands.includes( command ) ) {
+ const result = spawnSync(
+ 'bash',
+ [ path.join( __dirname, `${ command }.sh` ), ...args ],
+ { stdio: 'inherit' }
+ );
+ if ( result.error ) {
+ process.stderr.write( `${ result.error.message }\n` );
+ process.exitCode = 1;
+ } else {
+ // Node ignores some signals, so report the shell's conventional status.
+ process.exitCode =
+ result.status ?? 128 + constants.signals[ result.signal ];
+ }
+} else {
+ const output = `Usage: woo-extension-tooling <${ commands.join( ' | ' ) }> [args]\n`;
+ if ( ! command || command === '--help' || command === '-h' ) {
+ process.stdout.write( output );
+ } else {
+ process.stderr.write( `Unknown command: ${ command }\n${ output }` );
+ process.exitCode = 2;
+ }
+}
diff --git a/packages/js/extension-tooling/changelog/wooprd-4108-extract-extension-commands b/packages/js/extension-tooling/changelog/wooprd-4108-extract-extension-commands
new file mode 100644
index 00000000000..aa49c6bc1ac
--- /dev/null
+++ b/packages/js/extension-tooling/changelog/wooprd-4108-extract-extension-commands
@@ -0,0 +1,4 @@
+Significance: minor
+Type: add
+
+Add shared packaging, test provisioning and PHP quality commands for WooCommerce extensions.
diff --git a/packages/js/extension-tooling/eslint.config.mjs b/packages/js/extension-tooling/eslint.config.mjs
index 21626d6e5f7..bef3a9c51d5 100644
--- a/packages/js/extension-tooling/eslint.config.mjs
+++ b/packages/js/extension-tooling/eslint.config.mjs
@@ -6,8 +6,8 @@ import woocommerce from '@woocommerce/eslint-config';
export default [
...woocommerce,
{
- files: [ 'src/**/*.js', 'test/**/*.js' ],
- // Extension webpack configs and Node tests use CommonJS.
+ files: [ 'bin/**/*.js', 'src/**/*.js', 'test/**/*.js' ],
+ // Extension webpack configs, CLI and Node tests use CommonJS.
rules: {
'@typescript-eslint/no-require-imports': 'off',
},
diff --git a/packages/js/extension-tooling/package.json b/packages/js/extension-tooling/package.json
index 3b1b67a4b11..5b20a55d28a 100644
--- a/packages/js/extension-tooling/package.json
+++ b/packages/js/extension-tooling/package.json
@@ -22,7 +22,8 @@
"bin": {
"woo-extension-config": "./bin/woo-config.sh",
"woo-extension-env-start": "./bin/env-start.sh",
- "woo-extension-env-dev-reset": "./bin/env-dev-reset.sh"
+ "woo-extension-env-dev-reset": "./bin/env-dev-reset.sh",
+ "woo-extension-tooling": "./bin/woo-extension-tooling.js"
},
"files": [
"bin",
@@ -34,7 +35,7 @@
},
"scripts": {
"changelog": "XDEBUG_MODE=off composer install --quiet && composer exec -- changelogger",
- "lint": "eslint src test",
+ "lint": "eslint src test bin/*.js",
"test": "node --test"
},
"dependencies": {
@@ -49,7 +50,7 @@
"ci": {
"lint": {
"command": "lint",
- "changes": "{src,test}/**/*.js"
+ "changes": "{bin,src,test}/**/*.js"
},
"tests": [
{
@@ -57,8 +58,7 @@
"command": "test",
"changes": [
"package.json",
- "bin/env-start.sh",
- "bin/woo-config.*",
+ "bin/*",
"{src,test}/**/*.js"
],
"events": [
diff --git a/packages/js/extension-tooling/test/commands.test.js b/packages/js/extension-tooling/test/commands.test.js
new file mode 100644
index 00000000000..8c00082499f
--- /dev/null
+++ b/packages/js/extension-tooling/test/commands.test.js
@@ -0,0 +1,467 @@
+const assert = require( 'node:assert/strict' );
+const { spawnSync } = require( 'node:child_process' );
+const fs = require( 'node:fs' );
+const os = require( 'node:os' );
+const path = require( 'node:path' );
+const { test } = require( 'node:test' );
+
+const toolingBin = path.join( __dirname, '..', 'bin' );
+
+function extension( context ) {
+ const directory = fs.mkdtempSync( path.join( os.tmpdir(), 'woo-tools-' ) );
+ context.after( () =>
+ fs.rmSync( directory, { recursive: true, force: true } )
+ );
+ fs.writeFileSync(
+ path.join( directory, 'package.json' ),
+ JSON.stringify( {
+ name: 'example-extension',
+ config: { woo: { zip: { build: '', root: 'plugin-root' } } },
+ } )
+ );
+ return directory;
+}
+
+function run( directory, command, args, env = {} ) {
+ const result = spawnSync( command, args, {
+ cwd: directory,
+ env: { ...process.env, ...env },
+ encoding: 'utf8',
+ } );
+ assert.ifError( result.error );
+ assert.equal( result.status, 0, result.stderr );
+ return result.stdout;
+}
+
+test( 'builds the plugin ZIP without npm and prepares that ZIP through a linked launcher', ( context ) => {
+ const directory = extension( context );
+ fs.mkdirSync( path.join( directory, 'bin/hooks' ), { recursive: true } );
+ fs.writeFileSync(
+ path.join( directory, 'example-extension.php' ),
+ '<?php\n'
+ );
+ fs.writeFileSync(
+ path.join( directory, 'exclude.lst' ),
+ '# ignored\r\n/local-only.txt\r\n/bin/*\r\n'
+ );
+ fs.writeFileSync( path.join( directory, 'local-only.txt' ), 'skip me' );
+ fs.writeFileSync(
+ path.join( directory, 'bin/hooks/build-zip-stage.sh' ),
+ 'printf staged > "$1/staged.txt"\n'
+ );
+ fs.writeFileSync(
+ path.join( directory, 'bin/hooks/e2e-prepare.sh' ),
+ 'printf "%s/%s" "$WP_VERSION" "$WC_VERSION" > deploy/versions\n'
+ );
+ fs.writeFileSync(
+ path.join( directory, 'bin/link_plugins.js' ),
+ 'require("node:fs").writeFileSync("deploy/link-ran", "");\n'
+ );
+ const zip = 'deploy/example-extension.zip';
+ run( directory, 'bash', [ path.join( toolingBin, 'build-zip.sh' ) ] );
+ const contents = run( directory, 'unzip', [ '-Z1', zip ] ).split( '\n' );
+ assert.ok( contents.includes( 'plugin-root/example-extension.php' ) );
+ assert.ok( contents.includes( 'plugin-root/staged.txt' ) );
+ assert.ok( ! contents.includes( 'plugin-root/local-only.txt' ) );
+ assert.ok(
+ ! contents.some( ( name ) => name.startsWith( 'plugin-root/bin/' ) )
+ );
+
+ const link = path.join( directory, 'woo-extension-tooling' );
+ fs.symlinkSync( path.join( toolingBin, 'woo-extension-tooling.js' ), link );
+ run( directory, link, [ 'e2e', 'prepare' ], {
+ E2E_PLUGIN_ZIP: zip,
+ E2E_WP_VERSION: '7.0.1',
+ E2E_WC_VERSION: '11.3.0-rc.1',
+ } );
+ assert.equal(
+ fs.readFileSync( path.join( directory, 'deploy/versions' ), 'utf8' ),
+ '7.0.1/11.3.0-rc.1'
+ );
+ assert.equal(
+ fs.readFileSync(
+ path.join( directory, 'deploy/e2e-plugin/plugin-root/staged.txt' ),
+ 'utf8'
+ ),
+ 'staged'
+ );
+ assert.ok( fs.existsSync( path.join( directory, 'deploy/link-ran' ) ) );
+} );
+
+test( 'rejects invalid ZIP root folder names', ( context ) => {
+ const directory = extension( context );
+ const manifest = path.join( directory, 'package.json' );
+ const pkg = JSON.parse( fs.readFileSync( manifest, 'utf8' ) );
+ fs.writeFileSync( path.join( directory, 'exclude.lst' ), '' );
+ for ( const name of [
+ '',
+ '.',
+ '..',
+ '-root',
+ 'parent/child',
+ 'parent\\child',
+ ] ) {
+ pkg.config.woo.zip.root = name;
+ fs.writeFileSync( manifest, JSON.stringify( pkg ) );
+ const result = spawnSync(
+ 'bash',
+ [ path.join( toolingBin, 'build-zip.sh' ) ],
+ {
+ cwd: directory,
+ encoding: 'utf8',
+ }
+ );
+ assert.equal( result.status, 1, JSON.stringify( name ) );
+ assert.ok(
+ result.stderr.includes( 'zip.root must be a single folder name' ),
+ result.stderr
+ );
+ assert.ok( ! fs.existsSync( path.join( directory, 'deploy' ) ) );
+ }
+} );
+
+test( 'uses the staging hook and its inputs from the selected commit', ( context ) => {
+ const directory = extension( context );
+ const hook = 'bin/hooks/build-zip-stage.sh';
+ const input = 'hook-input.txt';
+ fs.mkdirSync( path.join( directory, 'bin/hooks' ), { recursive: true } );
+ fs.writeFileSync( path.join( directory, 'exclude.lst' ), '/bin/*\n' );
+ fs.writeFileSync( path.join( directory, input ), 'committed input' );
+ fs.writeFileSync(
+ path.join( directory, hook ),
+ 'cat hook-input.txt > "$1/staged.txt"\n'
+ );
+ run( directory, 'git', [ 'init', '-q' ] );
+ run( directory, 'git', [
+ 'add',
+ '--',
+ 'package.json',
+ 'exclude.lst',
+ hook,
+ input,
+ ] );
+ run( directory, 'git', [
+ '-c',
+ 'user.name=Extension Tooling Test',
+ '-c',
+ 'user.email=extension-tooling@example.test',
+ '-c',
+ 'core.hooksPath=/dev/null',
+ '-c',
+ 'commit.gpgsign=false',
+ 'commit',
+ '-qm',
+ 'Stage fixture files',
+ ] );
+ fs.writeFileSync( path.join( directory, hook ), 'exit 12\n' );
+ fs.writeFileSync( path.join( directory, input ), 'uncommitted input' );
+ const args = [ path.join( toolingBin, 'build-zip.sh' ), 'HEAD' ];
+ const manifest = path.join( directory, 'package.json' );
+ const originalManifest = fs.readFileSync( manifest, 'utf8' );
+ for ( const [ build, warning ] of [
+ [ 'build', 'Packaging a commit needs a plugin without a build step' ],
+ [ '', 'package.json differs from' ],
+ ] ) {
+ const pkg = JSON.parse( originalManifest );
+ pkg.version = '1.0.1';
+ pkg.config.woo.zip.build = build;
+ fs.writeFileSync( manifest, JSON.stringify( pkg ) );
+ const rejected = spawnSync( 'bash', args, {
+ cwd: directory,
+ encoding: 'utf8',
+ } );
+ assert.equal( rejected.status, 1, rejected.stderr );
+ assert.ok( rejected.stderr.includes( warning ), rejected.stderr );
+ assert.ok( ! fs.existsSync( path.join( directory, 'deploy' ) ) );
+ }
+ fs.writeFileSync( manifest, originalManifest );
+ run( directory, 'bash', args );
+ assert.equal(
+ run( directory, 'unzip', [
+ '-p',
+ 'deploy/example-extension.zip',
+ 'plugin-root/staged.txt',
+ ] ),
+ 'committed input'
+ );
+} );
+
+test( 'forwards XML and test arguments to a pre-provisioned PHPUnit site', ( context ) => {
+ const directory = extension( context );
+ fs.mkdirSync( path.join( directory, 'vendor' ) );
+ fs.writeFileSync(
+ path.join( directory, 'vendor/autoload.php' ),
+ '<?php\n'
+ );
+ fs.writeFileSync(
+ path.join( directory, 'pnpm' ),
+ '#!/bin/sh\nprintf "%s\\n" "$@"\n',
+ { mode: 0o755 }
+ );
+ const output = run(
+ directory,
+ 'bash',
+ [
+ path.join( toolingBin, 'phpunit.sh' ),
+ 'direct',
+ 'phpunit.xml',
+ '--filter',
+ 'test with spaces',
+ ],
+ { PATH: directory + path.delimiter + process.env.PATH }
+ );
+ assert.deepEqual( output.trim().split( '\n' ), [
+ 'run',
+ 'wp-env:test',
+ 'run',
+ 'cli',
+ `--env-cwd=wp-content/plugins/${ path.basename( directory ) }`,
+ '--',
+ 'php',
+ 'vendor/bin/phpunit',
+ '-c',
+ 'phpunit.xml',
+ '--fail-on-empty-test-suite',
+ '--filter',
+ 'test with spaces',
+ ] );
+} );
+
+test( 'returns a failing exit status when a command is terminated by a signal', ( context ) => {
+ const directory = extension( context );
+ fs.writeFileSync(
+ path.join( directory, 'bash' ),
+ '#!/bin/sh\nkill -PIPE $$\n',
+ { mode: 0o755 }
+ );
+ const result = spawnSync(
+ path.join( toolingBin, 'woo-extension-tooling.js' ),
+ [ 'phplint' ],
+ {
+ cwd: directory,
+ env: {
+ ...process.env,
+ PATH: directory + path.delimiter + process.env.PATH,
+ },
+ }
+ );
+ assert.equal( result.status, 128 + os.constants.signals.SIGPIPE );
+} );
+
+test( 'passes PHPCS findings to SARB and preserves tool errors', ( context ) => {
+ const directory = extension( context );
+ const vendorBin = path.join( directory, 'vendor/bin' );
+ fs.mkdirSync( vendorBin, { recursive: true } );
+ fs.writeFileSync(
+ path.join( vendorBin, 'phpcs' ),
+ '<?php echo getenv("PHPCS_REPORT"); exit(3);'
+ );
+ fs.writeFileSync(
+ path.join( vendorBin, 'sarb' ),
+ '<?php echo stream_get_contents(STDIN);'
+ );
+ const report = '{"files": {}}';
+
+ for ( const command of [ 'phpcs.sh', 'phpcs-baseline.sh' ] ) {
+ const args = [ path.join( toolingBin, command ) ];
+ assert.equal(
+ run( directory, 'bash', args, { PHPCS_REPORT: report } ),
+ report
+ );
+ const diagnostic = 'ERROR: the coding standard is not installed.';
+ const result = spawnSync( 'bash', args, {
+ cwd: directory,
+ env: { ...process.env, PHPCS_REPORT: diagnostic },
+ encoding: 'utf8',
+ } );
+ assert.equal( result.status, 3, result.stderr );
+ assert.equal( result.stdout, diagnostic );
+ }
+} );
+
+test( 'uses the exact WordPress archive, test library tag and WooCommerce tag without npm', ( context ) => {
+ const directory = extension( context );
+ const executable = path.join( directory, 'stub' );
+ const wpSource = path.join( directory, 'download/wordpress/wp-includes' );
+ fs.mkdirSync( wpSource, { recursive: true } );
+ fs.writeFileSync(
+ path.join( wpSource, 'version.php' ),
+ "<?php $wp_version = '7.0';\n"
+ );
+ run( directory, 'tar', [
+ '-czf',
+ 'wordpress.tar.gz',
+ '-C',
+ 'download',
+ 'wordpress',
+ ] );
+ fs.writeFileSync(
+ executable,
+ `#!/bin/bash
+set -eu
+printf '%s\\n' "$@" >> "$REQUESTS"
+case "$(basename "$0")" in
+ curl)
+ case "\${!#}" in
+ */wordpress-7.0.tar.gz) cat "$FIXTURE/wordpress.tar.gz" ;;
+ */wp-tests-config-sample.php)
+ printf '%s\\n' "<?php define( 'ABSPATH', dirname( __FILE__ ) . '/src/' );" "define( 'DB_PASSWORD', 'yourpasswordhere' );" ;;
+ */core/version-check/1.7/)
+ if [[ -n "\${WP_RELEASE_RESPONSE:-}" ]]; then
+ printf '%s\\n' "$WP_RELEASE_RESPONSE"
+ else
+ printf '%s\\n' '{"offers":[{"version":"7.0"}]}'
+ fi ;;
+ */woocommerce.json) printf '%s\\n' '{"version": "11.2.0"}' ;;
+ *) exit 2 ;;
+ esac ;;
+ svn) mkdir -p "\${!#}" ;;
+ git)
+ if [[ "$1" == ls-remote ]]; then
+ [[ "\${!#}" == refs/tags/11.2.0 ]]
+ else
+ [[ "$3" == --branch=11.2.0 ]]
+ target="\${!#}/plugins/woocommerce"
+ mkdir -p "$target/bin"
+ printf ' * Version: 11.2.0\\n' > "$target/woocommerce.php"
+ printf '<?php\\n' > "$target/bin/generate-feature-config.php"
+ fi ;;
+ mysql) cat >/dev/null ;;
+ mysqladmin|composer) : ;;
+ *) exit 2 ;;
+esac
+`,
+ { mode: 0o755 }
+ );
+ for ( const name of [
+ 'curl',
+ 'svn',
+ 'git',
+ 'mysql',
+ 'mysqladmin',
+ 'composer',
+ ] ) {
+ fs.symlinkSync( executable, path.join( directory, name ) );
+ }
+ const wpDirectory = path.join( directory, 'test core' );
+ const tests = path.join( directory, 'test library' );
+ const requests = path.join( directory, 'requests' );
+ const env = {
+ ...process.env,
+ PATH: directory + path.delimiter + process.env.PATH,
+ FIXTURE: directory,
+ REQUESTS: requests,
+ RUN_UNIT_TESTS: '1',
+ WP_CORE_DIR: wpDirectory,
+ WP_TESTS_DIR: tests,
+ WC_CORE_DIR: path.join( directory, 'test woocommerce' ),
+ };
+ const password = "fixture 'a|b&c\\d";
+ const install = [
+ path.join( toolingBin, 'install.sh' ),
+ 'wordpress_test',
+ 'root',
+ password,
+ 'mysql',
+ ];
+ for ( const versions of [
+ [ '7.0', '11.2.0' ],
+ [ 'latest', 'latest' ],
+ ] ) {
+ fs.writeFileSync( requests, '' );
+ const output = run(
+ directory,
+ 'bash',
+ [ ...install, ...versions ],
+ env
+ );
+ assert.ok( output.includes( 'Installed WordPress: 7.0' ) );
+ assert.ok( output.includes( 'Installed WooCommerce: 11.2.0' ) );
+ const calls = fs.readFileSync( requests, 'utf8' );
+ assert.ok(
+ calls.includes( 'https://wordpress.org/wordpress-7.0.tar.gz' )
+ );
+ assert.ok(
+ calls.includes(
+ 'https://develop.svn.wordpress.org/tags/7.0/tests/phpunit/includes/'
+ )
+ );
+ assert.ok( calls.includes( '\nrefs/tags/11.2.0\n' ) );
+ assert.equal(
+ run( directory, 'php', [
+ '-r',
+ 'require $argv[1]; echo ABSPATH, "\\n", DB_PASSWORD;',
+ path.join( tests, 'wp-tests-config.php' ),
+ ] ),
+ `${ wpDirectory }/\n${ password }`
+ );
+ }
+
+ const relativePaths = {
+ WP_CORE_DIR: 'relative sites/test core',
+ WP_TESTS_DIR: 'relative test library',
+ WC_CORE_DIR: 'relative woocommerce',
+ };
+ run( directory, 'bash', [ ...install, '7.0', '11.2.0' ], {
+ ...env,
+ ...relativePaths,
+ } );
+ assert.ok(
+ fs.existsSync(
+ path.join( directory, relativePaths.WC_CORE_DIR, 'woocommerce.php' )
+ )
+ );
+ assert.equal(
+ run( directory, 'php', [
+ '-r',
+ 'require $argv[1]; echo ABSPATH;',
+ path.join(
+ directory,
+ relativePaths.WP_TESTS_DIR,
+ 'wp-tests-config.php'
+ ),
+ ] ),
+ fs.realpathSync( path.join( directory, relativePaths.WP_CORE_DIR ) ) +
+ '/'
+ );
+
+ for ( const [ versions, warning, overrides ] of [
+ [ [ '7.1-RC1', '11.2.0' ], 'Invalid WordPress version' ],
+ [ [ '7.0', '11.2.1' ], 'no matching tag in woocommerce/woocommerce' ],
+ [
+ [ 'latest', '11.2.0' ],
+ 'Could not read the latest WordPress version',
+ ],
+ [
+ [ '7.0', '11.2.0' ],
+ 'must be nonempty when set',
+ { WP_TESTS_DIR: '' },
+ ],
+ ] ) {
+ const result = spawnSync( 'bash', [ ...install, ...versions ], {
+ cwd: directory,
+ env: { ...env, WP_RELEASE_RESPONSE: 'invalid-json', ...overrides },
+ encoding: 'utf8',
+ } );
+ assert.equal( result.status, 1, result.stderr );
+ assert.ok( result.stderr.includes( warning ), result.stderr );
+ }
+
+ // A failed extraction can leave wp-settings.php in the new directory.
+ fs.writeFileSync(
+ path.join( directory, 'tar' ),
+ `#!/bin/sh
+touch "$WP_CORE_DIR/wp-settings.php"
+exit 4
+`,
+ { mode: 0o755 }
+ );
+ const failed = spawnSync( 'bash', [ ...install, '7.0', '11.2.0' ], {
+ cwd: directory,
+ env,
+ encoding: 'utf8',
+ } );
+ assert.equal( failed.status, 4, failed.stderr );
+ assert.ok( fs.existsSync( path.join( wpDirectory, 'wp-settings.php' ) ) );
+ assert.ok( ! fs.existsSync( path.join( tests, 'wp-tests-config.php' ) ) );
+} );