Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
}
],
"require": {
"wp-cli/wp-cli": "^2.12"
"wp-cli/wp-cli": "^2.13"
},
"require-dev": {
"wp-cli/wp-cli-tests": "^5"
Expand Down
37 changes: 37 additions & 0 deletions features/shell.feature
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,43 @@ Feature: WordPress REPL
"""
And STDERR should be empty

Scenario: Restart shell
Given a WP install
And a session file:
"""
$a = 1;
restart
$b = 2;
"""

When I run `wp shell --basic < session`
Then STDOUT should contain:
"""
Restarting shell...
"""
And STDOUT should contain:
"""
=> int(2)
"""

Scenario: Exit shell
Given a WP install
And a session file:
"""
$a = 1;
exit
"""

When I run `wp shell --basic < session`
Then STDOUT should contain:
"""
=> int(1)
"""
And STDOUT should not contain:
"""
exit
"""

Scenario: Input starting with dash
Given a WP install
And a session file:
Expand Down
152 changes: 149 additions & 3 deletions src/Shell_Command.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,21 @@ class Shell_Command extends WP_CLI_Command {
* is loaded, you have access to all the functions, classes and globals
* that you can use within a WordPress plugin, for example.
*
* The `restart` command reloads the shell by spawning a new PHP process,
* allowing modified code to be fully reloaded. Note that this requires
* the `pcntl_exec()` function. If not available, the shell restarts
* in-process, which resets variables but doesn't reload PHP files.
*
* ## OPTIONS
*
* [--basic]
* : Force the use of WP-CLI's built-in PHP REPL, even if the Boris or
* PsySH PHP REPLs are available.
*
* [--watch=<path>]
* : Watch a file or directory for changes and automatically restart the shell.
* Only works with the built-in REPL (--basic).
*
* [--hook=<hook>]
* : Ensure that a specific WordPress action hook has fired before starting the shell.
* This validates that the preconditions associated with that hook are met.
Expand All @@ -34,10 +43,32 @@ class Shell_Command extends WP_CLI_Command {
* wp> get_bloginfo( 'name' );
* => string(6) "WP-CLI"
*
* # Restart the shell to reload code changes.
* $ wp shell
* wp> restart
* Restarting shell in new process...
* wp>
*
* # Watch a directory for changes and auto-restart.
* $ wp shell --watch=wp-content/plugins/my-plugin
* wp> // Make changes to files in the plugin directory
* Detected changes in wp-content/plugins/my-plugin, restarting shell...
* wp>
*
* # Start a shell, ensuring the 'init' hook has already fired.
* $ wp shell --hook=init
*
* @param string[] $_ Positional arguments. Unused.
* @param array{basic?: bool, watch?: string} $assoc_args Associative arguments.
*/
public function __invoke( $_, $assoc_args ) {
$watch_path = Utils\get_flag_value( $assoc_args, 'watch', false );

if ( $watch_path && ! Utils\get_flag_value( $assoc_args, 'basic' ) ) {
WP_CLI::warning( 'The --watch option only works with the built-in REPL. Enabling --basic mode.' );
$assoc_args['basic'] = true;
}

$hook = Utils\get_flag_value( $assoc_args, 'hook', '' );

// No hook specified, start immediately.
Expand Down Expand Up @@ -67,9 +98,16 @@ public function __invoke( $_, $assoc_args ) {
/**
* Start the shell REPL.
*
* @param array<string,bool|string> $assoc_args Associative arguments.
* @param array{basic?: bool, watch?: string} $assoc_args Associative arguments.
*/
private function start_shell( $assoc_args ) {
$watch_path = Utils\get_flag_value( $assoc_args, 'watch', '' );

if ( $watch_path && ! Utils\get_flag_value( $assoc_args, 'basic' ) ) {
WP_CLI::warning( 'The --watch option only works with the built-in REPL. Enabling --basic mode.' );
$assoc_args['basic'] = true;
}

$class = WP_CLI\Shell\REPL::class;

$implementations = array(
Expand Down Expand Up @@ -98,8 +136,116 @@ private function start_shell( $assoc_args ) {
/**
* @var class-string<WP_CLI\Shell\REPL> $class
*/
$repl = new $class( 'wp> ' );
$repl->start();
if ( $watch_path ) {
$watch_path = $this->resolve_watch_path( $watch_path );
}

do {
$repl = new $class( 'wp> ' );
if ( $watch_path ) {
$repl->set_watch_path( $watch_path );
}
$exit_code = $repl->start();

// If restart requested, exec a new PHP process to reload all code
if ( WP_CLI\Shell\REPL::EXIT_CODE_RESTART === $exit_code ) {
$this->restart_process( $assoc_args );
// If restart_process() returns, pcntl_exec is not available, continue in-process
}
} while ( WP_CLI\Shell\REPL::EXIT_CODE_RESTART === $exit_code );
}
}

/**
* Resolve and validate the watch path.
*
* @param string $path Path to watch.
* @return string|never Absolute path to watch.
*/
private function resolve_watch_path( $path ) {
if ( ! file_exists( $path ) ) {
WP_CLI::error( "Watch path does not exist: {$path}" );
}

$realpath = realpath( $path );
if ( false === $realpath ) {
WP_CLI::error( "Could not resolve watch path: {$path}" );
}

return $realpath;
}

/**
* Restart the shell by spawning a new PHP process.
*
* This replaces the current process with a new one to fully reload all code.
* Falls back to in-process restart if pcntl_exec is not available.
*
* @param array{basic?: bool, watch?: string} $assoc_args Command arguments to preserve.
*/
private function restart_process( $assoc_args ) {
/**
* @var array{0?: string} $argv
*/
global $argv;

// Check if pcntl_exec is available
if ( ! function_exists( 'pcntl_exec' ) ) {
WP_CLI::debug( 'pcntl_exec not available, falling back to in-process restart', 'shell' );
return;
}

// Build the command to restart wp shell with the same arguments
$php_binary = Utils\get_php_binary();

/**
* @var array{argv: array{0?: string}} $_SERVER
*/

// Get the WP-CLI script path
$wp_cli_script = null;
if ( isset( $argv[0] ) ) {
$wp_cli_script = $argv[0];
} elseif ( isset( $_SERVER['argv'][0] ) ) {
$wp_cli_script = $_SERVER['argv'][0];
}

if ( ! $wp_cli_script ) {
WP_CLI::debug( 'Could not determine WP-CLI script path, falling back to in-process restart', 'shell' );
return;
}

// Build arguments array
$args = array( $php_binary, $wp_cli_script, 'shell' );

if ( Utils\get_flag_value( $assoc_args, 'basic' ) ) {
$args[] = '--basic';
}

$watch_path = Utils\get_flag_value( $assoc_args, 'watch', false );
if ( $watch_path ) {
$args[] = '--watch=' . $watch_path;
}

// Add global config values to preserve the environment after restart
$config = WP_CLI::get_runner()->config;
if ( isset( $config['path'] ) ) {
$args[] = '--path=' . $config['path'];
}
if ( isset( $config['user'] ) ) {
$args[] = '--user=' . $config['user'];
}
if ( isset( $config['url'] ) ) {
$args[] = '--url=' . $config['url'];
}

WP_CLI::log( 'Restarting shell in new process...' );

// Replace the current process with a new one
// Note: pcntl_exec does not return on success
pcntl_exec( $php_binary, array_slice( $args, 1 ) );

// If we reach here, exec failed
WP_CLI::warning( 'Failed to restart process, falling back to in-process restart' );
}
}
94 changes: 93 additions & 1 deletion src/WP_CLI/Shell/REPL.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,53 @@ class REPL {

private $history_file;

private $watch_path;

private $watch_mtime;

const EXIT_CODE_RESTART = 10;

public function __construct( $prompt ) {
$this->prompt = $prompt;

$this->set_history_file();
}

/**
* Set a path to watch for changes.
*
* @param string $path Path to watch for changes.
*/
public function set_watch_path( $path ) {
$this->watch_path = $path;
$this->watch_mtime = $this->get_recursive_mtime( $path );
}

public function start() {
// @phpstan-ignore while.alwaysTrue
while ( true ) {
// Check for file changes if watching
if ( $this->watch_path && $this->has_changes() ) {
WP_CLI::log( "Detected changes in {$this->watch_path}, restarting shell..." );
return self::EXIT_CODE_RESTART;
}

$line = $this->prompt();

if ( '' === $line ) {
continue;
}

// Check for special exit command
if ( 'exit' === trim( $line ) ) {
return 0;
}

// Check for special restart command
if ( 'restart' === trim( $line ) ) {
WP_CLI::log( 'Restarting shell...' );
return self::EXIT_CODE_RESTART;
}

$line = rtrim( $line, ';' ) . ';';

if ( self::starts_with( self::non_expressions(), $line ) ) {
Expand Down Expand Up @@ -153,4 +185,64 @@ private function set_history_file() {
private static function starts_with( $tokens, $line ) {
return preg_match( "/^($tokens)[\(\s]+/", $line );
}

/**
* Check if the watched path has changes.
*
* @return bool True if changes detected, false otherwise.
*/
private function has_changes() {
if ( ! $this->watch_path ) {
return false;
}

$current_mtime = $this->get_recursive_mtime( $this->watch_path );
return $current_mtime !== $this->watch_mtime;
}

/**
* Get the most recent modification time for a path recursively.
*
* @param string $path Path to check.
* @return int Most recent modification time.
*/
private function get_recursive_mtime( $path ) {
$mtime = 0;

if ( is_file( $path ) ) {
$file_mtime = filemtime( $path );
return false !== $file_mtime ? $file_mtime : 0;
}

if ( is_dir( $path ) ) {
$dir_mtime = filemtime( $path );
$mtime = false !== $dir_mtime ? $dir_mtime : 0;

try {
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator( $path, \RecursiveDirectoryIterator::SKIP_DOTS ),
\RecursiveIteratorIterator::SELF_FIRST
);

foreach ( $iterator as $file ) {
/** @var \SplFileInfo $file */
$file_mtime = $file->getMTime();
if ( $file_mtime > $mtime ) {
$mtime = $file_mtime;
}
}
} catch ( \UnexpectedValueException $e ) {
// Handle unreadable directories/files gracefully.
WP_CLI::warning(
sprintf(
'Could not read path "%s" while checking for changes: %s',
$path,
$e->getMessage()
)
);
}
}

return $mtime;
}
}