Skip to content

Commit ef3ec05

Browse files
authored
Merge pull request #400 from wp-cli/setup-commands-step
Add a step to run several setup commands in a single process
2 parents 23c6dc4 + 71bc505 commit ef3ec05

3 files changed

Lines changed: 144 additions & 0 deletions

File tree

‎features/behat-steps.feature‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -574,6 +574,33 @@ Feature: Test that WP-CLI Behat steps work as expected
574574
twentysixteen,active
575575
"""
576576

577+
@require-wp
578+
Scenario: Run setup commands in a single process
579+
Given a WP installation
580+
And these setup commands:
581+
| command | save |
582+
| wp eval 'echo wp_insert_post( [ "post_title" => "First", "post_status" => "publish" ] );' | POST_ID |
583+
| wp eval 'echo get_the_title( {POST_ID} );' | TITLE |
584+
| wp eval 'echo getmypid();' | FIRST |
585+
| wp eval 'echo getmypid();' | SECOND |
586+
| wp config set WP_CLI_TEST_CONSTANT "a value" | |
587+
588+
When I run `wp eval 'echo get_post_field( "post_title", {POST_ID} ) . "|{TITLE}";'`
589+
Then STDOUT should be:
590+
"""
591+
First|First
592+
"""
593+
594+
When I run `wp eval 'echo "{FIRST}" === "{SECOND}" ? "same process" : "different processes";'`
595+
Then STDOUT should be:
596+
"""
597+
same process
598+
"""
599+
And the wp-config.php file should contain:
600+
"""
601+
'WP_CLI_TEST_CONSTANT', 'a value'
602+
"""
603+
577604
@require-wp
578605
Scenario: Test custom wp-content directory
579606
Given a WP installation

‎src/Context/FeatureContext.php‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1676,6 +1676,88 @@ public function proc( $command, $assoc_args = [], $path = '' ): Process {
16761676
return Process::create( $command, $cwd, $env );
16771677
}
16781678

1679+
/**
1680+
* Run several WP-CLI commands one after the other in a single `wp` process.
1681+
*
1682+
* Each command has to start with `wp `, and has to succeed. A command can use the
1683+
* output saved by an earlier command in the same batch as a {VARIABLE}.
1684+
*
1685+
* @param array<array{0: string, 1: string}> $commands Pairs of command and the name of the variable to save its STDOUT into, or ''.
1686+
*/
1687+
public function run_commands_in_single_process( array $commands ): void {
1688+
$batch_variables = array_filter( array_column( $commands, 1 ) );
1689+
1690+
$rows = [];
1691+
foreach ( $commands as list( $command, $save ) ) {
1692+
// Variables saved within the batch are only known once the process runs.
1693+
$command = (string) preg_replace_callback(
1694+
'/\{([A-Z_][A-Z_0-9]*)\}/',
1695+
function ( $matches ) use ( $batch_variables ) {
1696+
return in_array( $matches[1], $batch_variables, true ) ? $matches[0] : $this->replace_variables( $matches[0] );
1697+
},
1698+
$command
1699+
);
1700+
1701+
if ( 0 !== strpos( $command, 'wp ' ) ) {
1702+
throw new RuntimeException( "Only WP-CLI commands can run in a single process, got: {$command}" );
1703+
}
1704+
1705+
// These change how WordPress is loaded, which has already happened for every command but the first.
1706+
if ( preg_match( '/(?:^|\s)--(?:require|path|url|skip-plugins|skip-themes|skip-packages|context|exec|ssh|http)(?:[=\s]|$)/', $command ) ) {
1707+
throw new RuntimeException( "Commands that change how WordPress is loaded cannot share a process, got: {$command}" );
1708+
}
1709+
1710+
$rows[] = [ substr( $command, 3 ), $save ];
1711+
}
1712+
1713+
$marker = 'WP_CLI_TEST_SAVED_VARIABLES:';
1714+
$started = 'WP_CLI_TEST_STARTED_COMMAND:';
1715+
$code = '<?php
1716+
$wp_cli_test_saved = [];
1717+
foreach ( ' . var_export( $rows, true ) . ' as $wp_cli_test_index => $wp_cli_test_row ) {
1718+
echo "\n' . $started . '{$wp_cli_test_index}\n";
1719+
$wp_cli_test_command = strtr( $wp_cli_test_row[0], $wp_cli_test_saved );
1720+
$wp_cli_test_result = WP_CLI::runcommand( $wp_cli_test_command, [ "launch" => false, "return" => "all", "exit_error" => false ] );
1721+
if ( 0 !== $wp_cli_test_result->return_code ) {
1722+
fwrite( STDERR, "\$ wp {$wp_cli_test_command}\n{$wp_cli_test_result->stdout}\n{$wp_cli_test_result->stderr}\nexit status: {$wp_cli_test_result->return_code}\n" );
1723+
exit( 1 );
1724+
}
1725+
if ( "" !== $wp_cli_test_row[1] ) {
1726+
$wp_cli_test_saved[ "{" . $wp_cli_test_row[1] . "}" ] = trim( $wp_cli_test_result->stdout, "\n" );
1727+
}
1728+
}
1729+
echo "\n' . $marker . '" . json_encode( $wp_cli_test_saved ) . "\n";
1730+
';
1731+
1732+
$file = $this->variables['RUN_DIR'] . '/' . uniqid( 'wp-cli-test-commands-', true ) . '.php';
1733+
file_put_contents( $file, $code );
1734+
1735+
try {
1736+
$result = $this->proc( Utils\esc_cmd( 'wp eval-file %s', $file ) )->run();
1737+
} finally {
1738+
unlink( $file );
1739+
}
1740+
1741+
if ( 0 !== $result->return_code ) {
1742+
$stdout = trim( (string) preg_replace( '/^' . $started . '\d+$/m', '', $result->stdout ) );
1743+
throw new RuntimeException( "Running the commands in a single process failed:\n{$result->stderr}\n{$stdout}" );
1744+
}
1745+
1746+
$position = strrpos( $result->stdout, $marker );
1747+
$saved = false !== $position ? json_decode( trim( substr( $result->stdout, $position + strlen( $marker ) ) ), true ) : null;
1748+
if ( ! is_array( $saved ) ) {
1749+
$last = preg_match_all( '/^' . $started . '(\d+)$/m', $result->stdout, $matches ) ? (int) end( $matches[1] ) : null;
1750+
if ( null !== $last ) {
1751+
throw new RuntimeException( "The process ended while running `wp {$rows[ $last ][0]}`. A command that exits on its own cannot share a process with other commands." );
1752+
}
1753+
throw new RuntimeException( "Could not read the saved variables from the output:\n{$result->stdout}" );
1754+
}
1755+
1756+
foreach ( $saved as $placeholder => $value ) {
1757+
$this->variables[ trim( $placeholder, '{}' ) ] = $value;
1758+
}
1759+
}
1760+
16791761
/**
16801762
* Start a background process. Will automatically be closed when the tests finish.
16811763
*

‎src/Context/GivenStepDefinitions.php‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,41 @@ public function given_these_installed_plugins_or_themes( $active, $type, PyStrin
477477
$this->install_extensions( $type, $lines, $activate );
478478
}
479479

480+
/**
481+
* Runs several setup commands in a single process.
482+
*
483+
* Avoids loading WordPress once per command when a scenario needs several fixtures. The `command`
484+
* column holds the WP-CLI commands, which all have to succeed. The optional `save` column names a
485+
* variable to save the command's STDOUT into, which later commands in the same table can use.
486+
*
487+
* ```
488+
* Scenario: My example scenario
489+
* Given a WP installation
490+
* And these setup commands:
491+
* | command | save |
492+
* | wp post create --post_title="First post" --porcelain | POST_ID |
493+
* | wp post meta add {POST_ID} color blue | |
494+
* | wp term create category Fruit --porcelain | TERM_ID |
495+
* ```
496+
*
497+
* @access public
498+
*
499+
* @Given these setup commands:
500+
*
501+
* @param TableNode $table
502+
*/
503+
public function given_these_setup_commands( TableNode $table ): void {
504+
$commands = [];
505+
foreach ( $table->getHash() as $row ) {
506+
if ( ! isset( $row['command'] ) ) {
507+
throw new RuntimeException( 'The setup commands table needs a "command" column.' );
508+
}
509+
$commands[] = [ $row['command'], trim( $row['save'] ?? '', '{} ' ) ];
510+
}
511+
512+
$this->run_commands_in_single_process( $commands );
513+
}
514+
480515
/**
481516
* Configure a custom `wp-content` directory.
482517
*

0 commit comments

Comments
 (0)