Skip to content

Commit 4fcf188

Browse files
Copilotswissspidy
andcommitted
Add exception handling to REPL to prevent session crashes
Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com>
1 parent bbd4f3d commit 4fcf188

2 files changed

Lines changed: 53 additions & 4 deletions

File tree

‎features/shell.feature‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,3 +77,41 @@ Feature: WordPress REPL
7777
"""
7878
history: -1: invalid option
7979
"""
80+
81+
Scenario: Exception handling preserves session state
82+
Given a WP install
83+
And a session file:
84+
"""
85+
$foo = 'test_value';
86+
require 'nonexistent_file.txt';
87+
echo $foo;
88+
"""
89+
90+
When I run `wp shell --basic < session`
91+
Then STDOUT should contain:
92+
"""
93+
test_value
94+
"""
95+
And STDERR should contain:
96+
"""
97+
Error: Failed opening required 'nonexistent_file.txt'
98+
"""
99+
100+
Scenario: Exception handling for expression errors
101+
Given a WP install
102+
And a session file:
103+
"""
104+
$bar = 'preserved';
105+
nonexistent_function();
106+
$bar;
107+
"""
108+
109+
When I run `wp shell --basic < session`
110+
Then STDOUT should contain:
111+
"""
112+
string(9) "preserved"
113+
"""
114+
And STDERR should contain:
115+
"""
116+
Call to undefined function nonexistent_function()
117+
"""

‎src/WP_CLI/Shell/REPL.php‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,13 @@ public function start() {
2929

3030
if ( self::starts_with( self::non_expressions(), $line ) ) {
3131
ob_start();
32-
// phpcs:ignore Squiz.PHP.Eval.Discouraged -- This is meant to be a REPL, no way to avoid eval.
33-
eval( $line );
32+
try {
33+
// phpcs:ignore Squiz.PHP.Eval.Discouraged -- This is meant to be a REPL, no way to avoid eval.
34+
eval( $line );
35+
} catch ( \Throwable $e ) {
36+
// Display the error message but continue the session
37+
fwrite( STDERR, $e . "\n" );
38+
}
3439
$out = (string) ob_get_clean();
3540
if ( 0 < strlen( $out ) ) {
3641
$out = rtrim( $out, "\n" ) . "\n";
@@ -43,8 +48,14 @@ public function start() {
4348

4449
// Write directly to STDOUT, to sidestep any output buffers created by plugins
4550
ob_start();
46-
// phpcs:ignore Squiz.PHP.Eval.Discouraged -- This is meant to be a REPL, no way to avoid eval.
47-
$evl = eval( $line );
51+
try {
52+
// phpcs:ignore Squiz.PHP.Eval.Discouraged -- This is meant to be a REPL, no way to avoid eval.
53+
$evl = eval( $line );
54+
} catch ( \Throwable $e ) {
55+
// Display the error message but continue the session
56+
fwrite( STDERR, $e . "\n" );
57+
$evl = null;
58+
}
4859
$out = (string) ob_get_clean();
4960
if ( 0 < strlen( $out ) ) {
5061
echo rtrim( $out, "\n" ) . "\n";

0 commit comments

Comments
 (0)