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
135 changes: 133 additions & 2 deletions src/Shell_Command.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,51 @@ 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).
*
* ## EXAMPLES
*
* # Call get_bloginfo() to get the name of the site.
* $ wp shell
* 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>
*
* @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;
}

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

$implementations = array(
Expand Down Expand Up @@ -55,8 +86,108 @@ public function __invoke( $_, $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 ) {
// 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();

// Get the WP-CLI script path
$wp_cli_script = null;
foreach ( array( 'argv', '_SERVER' ) as $source ) {
if ( 'argv' === $source && is_array( $GLOBALS['argv'] ) && isset( $GLOBALS['argv'][0] ) ) {
$wp_cli_script = $GLOBALS['argv'][0];
break;
} elseif ( '_SERVER' === $source && is_array( $_SERVER['argv'] ) && isset( $_SERVER['argv'][0] ) ) {
$wp_cli_script = $_SERVER['argv'][0];
break;
}
}
Comment on lines +147 to +156

Choose a reason for hiding this comment

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

medium

The logic to determine the WP-CLI script path is unnecessarily complex. It can be simplified for better readability and maintainability by using a direct if/elseif check on $GLOBALS['argv'] and $_SERVER['argv'] instead of a foreach loop.

		$wp_cli_script = null;
		if ( isset( $GLOBALS['argv'][0] ) ) {
			$wp_cli_script = $GLOBALS['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 the path argument if present in $_SERVER
if ( isset( $_SERVER['argv'] ) && is_array( $_SERVER['argv'] ) ) {
foreach ( $_SERVER['argv'] as $arg ) {
if ( is_string( $arg ) && '--path=' === substr( $arg, 0, 7 ) ) {
$args[] = $arg;
}
}
}
Comment on lines +175 to +182

Choose a reason for hiding this comment

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

high

The current implementation for preserving the --path argument is fragile. It only works for the --path=/some/path format and will fail if the argument is passed with a space, like --path /my/path. This can lead to the shell restarting in an incorrect directory.

A more robust approach is to retrieve the configuration value directly from WP-CLI's runner. This would also make it easier to preserve other important global parameters (e.g., --user, --url) to ensure a consistent environment after restarting.

		// Add the path argument if present from the runner's config.
		$config = WP_CLI::get_runner()->config;
		if ( isset( $config['path'] ) ) {
			$args[] = '--path=' . $config['path'];
		}


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' );
}
}
96 changes: 94 additions & 2 deletions 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 @@ -121,7 +153,7 @@ private static function create_prompt_cmd( $prompt, $history_path ) {
$prompt = escapeshellarg( $prompt );
$history_path = escapeshellarg( $history_path );
if ( getenv( 'WP_CLI_CUSTOM_SHELL' ) ) {
$shell_binary = getenv( 'WP_CLI_CUSTOM_SHELL' );
$shell_binary = (string) getenv( 'WP_CLI_CUSTOM_SHELL' );
} else {
$shell_binary = '/bin/bash';
}
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;
}
}