Skip to content

wp-now: Add executeWPCli() function to download and execute WP-CLI #395

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 24 commits into from
May 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
b5173cb
wp-now: add basic wp-cli command
sejas May 19, 2023
e101433
Merge branch 'trunk' of github.com:Automattic/wordpress-playground in…
sejas May 22, 2023
af6a0ad
wp-now: remove wp command until we fix pthreads
sejas May 23, 2023
d5ba677
wp-now: remove unnecessary flags for wp-cli
sejas May 23, 2023
f53d520
Merge branch 'trunk' of github.com:Automattic/wordpress-playground in…
sejas May 23, 2023
8fcff51
wp-now: force creating an empty file for downloadFile
sejas May 23, 2023
ad3513d
wp-now: add tests for executeWPCli
sejas May 23, 2023
de46790
wp-now: optimize tests and download files in parallel
sejas May 23, 2023
877cfe7
wp-now: accept path as second argument on executeWPCli
sejas May 23, 2023
5741ae8
wp-now: improve download file
sejas May 23, 2023
244ee69
wp-now: add emscriptenOptions to startWPNow
sejas May 23, 2023
7f1f9ce
wp-now: change wp-cli option to get its version
sejas May 23, 2023
863b338
wp-now: download wp-cli only for that test collection
sejas May 23, 2023
96ae2cf
wp-now: move downloadWithTimer to another PR
sejas May 23, 2023
cc86a62
Merge branch 'trunk' of github.com:Automattic/wordpress-playground in…
sejas May 24, 2023
1766aa1
wp-now: use downloadWithTimer for wp-cli
sejas May 24, 2023
da7699d
wp-now: change wp-cli test version
sejas May 24, 2023
99174cc
wp-now: avoid exposing emscriptenOptions and just onStdout
sejas May 24, 2023
acfbe6f
wp-now: remove unused import
sejas May 24, 2023
471b353
wp-now: mock console.log for wp-cli tests
sejas May 24, 2023
ca269c6
wp-now: remove the stdout and emscriptenOptions unnecessary
sejas May 24, 2023
e0395e6
wp-now: add comment on executeWPCli marking it as unstable
sejas May 24, 2023
a241c2d
Merge branch 'trunk' into add/wp-now-command-wp-cli
danielbachhuber May 25, 2023
5e8e97c
Use a tmp directory for WP-CLI tests
danielbachhuber May 25, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/wp-now/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,9 @@ export const DEFAULT_PHP_VERSION = '8.0';
* The default WordPress version to use when running the WP Now server.
*/
export const DEFAULT_WORDPRESS_VERSION = 'latest';

/**
* The URL for downloading the "wp-cli" WordPress cli.
*/
export const WP_CLI_URL =
'https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar';
52 changes: 51 additions & 1 deletion packages/wp-now/src/download.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@ import followRedirects from 'follow-redirects';
import unzipper from 'unzipper';
import os from 'os';
import { IncomingMessage } from 'http';
import { DEFAULT_WORDPRESS_VERSION, SQLITE_URL } from './constants';
import { DEFAULT_WORDPRESS_VERSION, SQLITE_URL, WP_CLI_URL } from './constants';
import { isValidWordPressVersion } from './wp-playground-wordpress';
import { output } from './output';
import getWpNowPath from './get-wp-now-path';
import getWordpressVersionsPath from './get-wordpress-versions-path';
import getSqlitePath from './get-sqlite-path';
import getWpCliPath from './get-wp-cli-path';

function getWordPressVersionUrl(version = DEFAULT_WORDPRESS_VERSION) {
if (!isValidWordPressVersion(version)) {
Expand All @@ -28,6 +29,55 @@ interface DownloadFileAndUnzipResult {
followRedirects.maxRedirects = 5;
const { https } = followRedirects;

async function downloadFile({
url,
destinationFilePath,
itemName,
}): Promise<DownloadFileAndUnzipResult> {
let statusCode = 0;
try {
if (fs.existsSync(destinationFilePath)) {
return { downloaded: false, statusCode: 0 };
}
fs.ensureDirSync(path.dirname(destinationFilePath));
const response = await new Promise<IncomingMessage>((resolve) =>
https.get(url, (response) => resolve(response))
);
statusCode = response.statusCode;
if (response.statusCode !== 200) {
throw new Error(
`Failed to download file (Status code ${response.statusCode}).`
);
}
await new Promise<void>((resolve, reject) => {
fs.ensureFileSync(destinationFilePath);
const file = fs.createWriteStream(destinationFilePath);
response.pipe(file);
file.on('finish', () => {
file.close();
resolve();
});
file.on('error', (error) => {
file.close();
reject(error);
});
});
output?.log(`Downloaded ${itemName} to ${destinationFilePath}`);
return { downloaded: true, statusCode };
} catch (error) {
output?.error(`Error downloading file ${itemName}`, error);
return { downloaded: false, statusCode };
}
}

export async function downloadWPCLI() {
return downloadFile({
url: WP_CLI_URL,
destinationFilePath: getWpCliPath(),
itemName: 'wp-cli',
});
}

async function downloadFileAndUnzip({
url,
destinationFolder,
Expand Down
41 changes: 41 additions & 0 deletions packages/wp-now/src/execute-wp-cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import startWPNow from './wp-now';
import { downloadWPCLI } from './download';
import { disableOutput } from './output';
import getWpCliPath from './get-wp-cli-path';
import getWpNowConfig from './config';
import { DEFAULT_PHP_VERSION, DEFAULT_WORDPRESS_VERSION } from './constants';

/**
* This is an unstable API. Multiple wp-cli commands may not work due to a current limitation on php-wasm and pthreads.
* @param args The arguments to pass to wp-cli.
*/
export async function executeWPCli(args: string[]) {
await downloadWPCLI();
disableOutput();
const options = await getWpNowConfig({
php: DEFAULT_PHP_VERSION,
wp: DEFAULT_WORDPRESS_VERSION,
path: process.env.WP_NOW_PROJECT_PATH || process.cwd(),
});
const { phpInstances, options: wpNowOptions } = await startWPNow({
...options,
numberOfPhpInstances: 2,
});
const [, php] = phpInstances;

try {
php.useHostFilesystem();
await php.cli([
'php',
getWpCliPath(),
`--path=${wpNowOptions.documentRoot}`,
...args,
]);
} catch (resultOrError) {
const success =
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI I merged this change: https://github.com/WordPress/wordpress-playground/pull/470/files#diff-3652c54df4b8d0d8e367481121e32f08cc409cfc4236fdb3172d69dcbf6ca8b0

It shouldn't matter here at all and this check still passes, but I wanted to flag it here just in case.

resultOrError.name === 'ExitStatus' && resultOrError.status === 0;
if (!success) {
throw resultOrError;
}
}
}
13 changes: 13 additions & 0 deletions packages/wp-now/src/get-wp-cli-path.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import path from 'path';
import getWpNowPath from './get-wp-now-path';
import getWpCliTmpPath from './get-wp-cli-tmp-path';

/**
* The path for wp-cli phar file within the WP Now folder.
*/
export default function getWpCliPath() {
if (process.env.NODE_ENV !== 'test') {
return path.join(getWpNowPath(), 'wp-cli.phar');
}
return getWpCliTmpPath();
}
11 changes: 11 additions & 0 deletions packages/wp-now/src/get-wp-cli-tmp-path.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import path from 'path';
import os from 'os';

/**
* The full path to the hidden WP-CLI folder in the user's tmp directory.
*/
export default function getWpCliTmpPath() {
const tmpDirectory = os.tmpdir();

return path.join(tmpDirectory, `wp-now-tests-wp-cli-hidden-folder`);
}
41 changes: 41 additions & 0 deletions packages/wp-now/src/tests/wp-now.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,14 @@ import {
} from '../wp-playground-wordpress';
import {
downloadSqliteIntegrationPlugin,
downloadWPCLI,
downloadWordPress,
} from '../download';
import os from 'os';
import crypto from 'crypto';
import getWpNowTmpPath from '../get-wp-now-tmp-path';
import getWpCliTmpPath from '../get-wp-cli-tmp-path';
import { executeWPCli } from '../execute-wp-cli';

const exampleDir = __dirname + '/mode-examples';

Expand Down Expand Up @@ -510,3 +513,41 @@ describe('Test starting different modes', () => {
expect(themeName.text).toContain('Twenty Twenty-Three');
});
});

/**
* Test wp-cli command.
*/
describe('wp-cli command', () => {
let consoleSpy;
let output = '';

beforeEach(() => {
function onStdout(outputLine: string) {
output += outputLine;
}
consoleSpy = vi.spyOn(console, 'log');
consoleSpy.mockImplementation(onStdout);
});

afterEach(() => {
output = '';
consoleSpy.mockRestore();
});

beforeAll(async () => {
await downloadWithTimer('wp-cli', downloadWPCLI);
});

afterAll(() => {
fs.removeSync(getWpCliTmpPath());
});

/**
* Test wp-cli displays the version.
* We don't need the WordPress context for this test.
*/
test('wp-cli displays the version', async () => {
await executeWPCli(['cli', 'version']);
expect(output).toMatch(/WP-CLI (\d\.?)+/i);
});
});
4 changes: 2 additions & 2 deletions packages/wp-now/src/wp-now.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fs from 'fs-extra';
import { NodePHP } from '@php-wasm/node';
import { NodePHP, PHPLoaderOptions } from '@php-wasm/node';
import path from 'path';
import { SQLITE_FILENAME } from './constants';
import {
Expand Down Expand Up @@ -42,7 +42,7 @@ export default async function startWPNow(
options: Partial<WPNowOptions> = {}
): Promise<{ php: NodePHP; phpInstances: NodePHP[]; options: WPNowOptions }> {
const { documentRoot } = options;
const nodePHPOptions = {
const nodePHPOptions: PHPLoaderOptions = {
requestHandler: {
documentRoot,
absoluteUrl: options.absoluteUrl,
Expand Down
2 changes: 1 addition & 1 deletion packages/wp-now/tsconfig.spec.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"types": ["jest", "node"]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice

"types": ["vitest/globals", "vitest/importMeta", "vite/client", "node"]
},
"include": [
"jest.config.ts",
Expand Down