Skip to content

Commit 8d46660

Browse files
committed
feat: send spark error output to STDERR
1 parent d219b08 commit 8d46660

13 files changed

Lines changed: 191 additions & 15 deletions

File tree

‎system/CLI/BaseCommand.php‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,9 @@ protected function showError(Throwable $e)
150150
$message = $e->getMessage();
151151
$config = config(Exceptions::class);
152152

153-
require $config->errorViewPath . '/cli/error_exception.php';
153+
CLI::redirectToStderr(static function () use ($exception, $message, $config): void {
154+
require $config->errorViewPath . '/cli/error_exception.php';
155+
});
154156
}
155157

156158
/**

‎system/CLI/CLI.php‎

Lines changed: 45 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,8 @@ class CLI
136136
*/
137137
protected static ?InputOutput $io = null;
138138

139+
protected static bool $stdoutToStderr = false;
140+
139141
/**
140142
* Static "constructor".
141143
*
@@ -1138,23 +1140,59 @@ public static function table(array $tbody, array $thead = [])
11381140
*/
11391141
protected static function fwrite($handle, string $string)
11401142
{
1143+
if (static::$stdoutToStderr && $handle === STDOUT) {
1144+
$handle = STDERR;
1145+
}
1146+
11411147
static::$io->fwrite($handle, $string);
11421148
}
11431149

1150+
/**
1151+
* Runs the callback with its STDOUT writes sent to STDERR.
1152+
*
1153+
* @param callable(): void $callback
1154+
*
1155+
* @internal
1156+
*/
1157+
public static function redirectToStderr(callable $callback): void
1158+
{
1159+
if (! is_cli()) {
1160+
$callback();
1161+
1162+
return;
1163+
}
1164+
1165+
$stdoutToStderr = static::$stdoutToStderr;
1166+
$isColored = static::$isColored;
1167+
$lastWrite = static::$lastWrite;
1168+
1169+
static::$stdoutToStderr = true;
1170+
static::$isColored = static::hasColorSupport(STDERR);
1171+
1172+
try {
1173+
$callback();
1174+
} finally {
1175+
static::$stdoutToStderr = $stdoutToStderr;
1176+
static::$isColored = $isColored;
1177+
static::$lastWrite = $lastWrite;
1178+
}
1179+
}
1180+
11441181
/**
11451182
* Testing purpose only
11461183
*
11471184
* @internal
11481185
*/
11491186
public static function reset(): void
11501187
{
1151-
static::$initialized = false;
1152-
static::$segments = [];
1153-
static::$options = [];
1154-
static::$lastWrite = null;
1155-
static::$height = null;
1156-
static::$width = null;
1157-
static::$isColored = static::hasColorSupport(STDOUT);
1188+
static::$initialized = false;
1189+
static::$segments = [];
1190+
static::$options = [];
1191+
static::$lastWrite = null;
1192+
static::$height = null;
1193+
static::$width = null;
1194+
static::$isColored = static::hasColorSupport(STDOUT);
1195+
static::$stdoutToStderr = false;
11581196

11591197
static::resetInputOutput();
11601198
}

‎system/Debug/ExceptionHandler.php‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
use Closure;
1717
use CodeIgniter\API\ResponseTrait;
18+
use CodeIgniter\CLI\CLI;
1819
use CodeIgniter\Exceptions\PageNotFoundException;
1920
use CodeIgniter\HTTP\CLIRequest;
2021
use CodeIgniter\HTTP\Exceptions\HTTPException;
@@ -121,7 +122,11 @@ public function handle(
121122
}
122123

123124
// Displays the HTML or CLI error code.
124-
$this->render($exception, $statusCode, $viewFile);
125+
if ($request instanceof IncomingRequest) {
126+
$this->render($exception, $statusCode, $viewFile);
127+
} else {
128+
CLI::redirectToStderr(fn () => $this->render($exception, $statusCode, $viewFile));
129+
}
125130

126131
if (! service('environment')->isTesting()) {
127132
exit($exitCode); // @codeCoverageIgnore

‎tests/system/CLI/AbstractCommandTest.php‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
use CodeIgniter\Commands\Help;
2727
use CodeIgniter\Exceptions\LogicException;
2828
use CodeIgniter\Test\CIUnitTestCase;
29+
use CodeIgniter\Test\Filters\CITestStreamFilter;
2930
use CodeIgniter\Test\Mock\MockInputOutput;
3031
use CodeIgniter\Test\StreamFilterTrait;
3132
use Config\App;
@@ -234,6 +235,8 @@ public function testRenderThrowable(): void
234235
{
235236
$command = new AppAboutCommand(new Commands());
236237

238+
CITestStreamFilter::removeOutputFilter();
239+
237240
$this->assertSame(EXIT_ERROR, $command->bomb());
238241
$this->assertStringContainsString('[CodeIgniter\CLI\Exceptions\CLIException]', $this->getStreamFilterBuffer());
239242
$this->assertStringContainsString('Invalid "background" color: "Background".', $this->getStreamFilterBuffer());

‎tests/system/CLI/BaseCommandTest.php‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
use CodeIgniter\CodeIgniter;
1818
use CodeIgniter\Log\Logger;
1919
use CodeIgniter\Test\CIUnitTestCase;
20+
use CodeIgniter\Test\Filters\CITestStreamFilter;
2021
use CodeIgniter\Test\StreamFilterTrait;
2122
use PHPUnit\Framework\Attributes\After;
2223
use PHPUnit\Framework\Attributes\Before;
@@ -89,6 +90,8 @@ public function testShowError(): void
8990
{
9091
$command = new AppInfo(single_service('logger'), single_service('commands'));
9192

93+
CITestStreamFilter::removeOutputFilter();
94+
9295
$this->assertSame(1, $command->bomb());
9396
$this->assertStringContainsString('[CodeIgniter\CLI\Exceptions\CLIException]', $this->getStreamFilterBuffer());
9497
$this->assertStringContainsString('Invalid "background" color: "Background".', $this->getStreamFilterBuffer());

‎tests/system/CLI/CLITest.php‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -649,6 +649,96 @@ public function testMixedWriteError(): void
649649
);
650650
}
651651

652+
public function testRedirectToStderrRoutesStdoutWritesOnlyWhileTheCallbackRuns(): void
653+
{
654+
$io = new class () extends InputOutput {
655+
/**
656+
* @var list<array{string, string}>
657+
*/
658+
public array $writes = [];
659+
660+
public function fwrite($handle, string $string): void
661+
{
662+
$this->writes[] = [$handle === STDERR ? 'STDERR' : 'STDOUT', $string];
663+
}
664+
};
665+
CLI::setInputOutput($io);
666+
667+
CLI::print('before');
668+
669+
CLI::redirectToStderr(static function (): void {
670+
CLI::write('inside');
671+
});
672+
673+
try {
674+
CLI::redirectToStderr(static function (): void {
675+
throw new RuntimeException('Callback failed.');
676+
});
677+
} catch (RuntimeException) {
678+
}
679+
680+
CLI::write('after');
681+
682+
$this->assertSame([
683+
['STDOUT', 'before'],
684+
['STDERR', "\ninside\n"],
685+
['STDOUT', "\nafter\n"],
686+
], $io->writes);
687+
}
688+
689+
public function testRedirectToStderrDoesNotRedirectOutsideCli(): void
690+
{
691+
$io = new class () extends InputOutput {
692+
/**
693+
* @var list<array{string, string}>
694+
*/
695+
public array $writes = [];
696+
697+
public function fwrite($handle, string $string): void
698+
{
699+
$this->writes[] = [$handle === STDERR ? 'STDERR' : 'STDOUT', $string];
700+
}
701+
};
702+
CLI::setInputOutput($io);
703+
704+
is_cli(false);
705+
706+
try {
707+
CLI::redirectToStderr(static function (): void {
708+
CLI::write('inside');
709+
});
710+
} finally {
711+
is_cli(true);
712+
}
713+
714+
$this->assertSame([['STDOUT', "\ninside\n"]], $io->writes);
715+
}
716+
717+
public function testRedirectToStderrUsesTheColorSupportOfStderr(): void
718+
{
719+
$superglobals = service('superglobals');
720+
$noColor = $superglobals->server('NO_COLOR');
721+
722+
(new ReflectionProperty(CLI::class, 'isColored'))->setValue(null, true);
723+
$superglobals->setServer('NO_COLOR', '1');
724+
725+
try {
726+
CLI::redirectToStderr(static function (): void {
727+
CLI::write('inside', 'red');
728+
});
729+
} finally {
730+
if ($noColor === null) {
731+
$superglobals->unsetServer('NO_COLOR');
732+
} else {
733+
$superglobals->setServer('NO_COLOR', $noColor);
734+
}
735+
}
736+
737+
CLI::write('after', 'red');
738+
739+
$this->assertSame("\ninside\n\n\033[0;31mafter\033[0m\n", $this->getStreamFilterBuffer());
740+
}
741+
652742
public function testErrorForeground(): void
653743
{
654744
CLI::error('test', 'purple');

‎tests/system/Debug/ExceptionHandlerTest.php‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
use CodeIgniter\HTTP\SiteURI;
2222
use CodeIgniter\HTTP\UserAgent;
2323
use CodeIgniter\Test\CIUnitTestCase;
24+
use CodeIgniter\Test\Filters\CITestStreamFilter;
2425
use CodeIgniter\Test\IniTestTrait;
2526
use CodeIgniter\Test\StreamFilterTrait;
2627
use Config\App;
@@ -253,6 +254,21 @@ public function testHandleCLIPageNotFoundException(): void
253254
$this->resetStreamFilterBuffer();
254255
}
255256

257+
public function testHandleCLIExceptionWritesToStderr(): void
258+
{
259+
$request = Services::clirequest(null, false);
260+
/** @var Response $response */
261+
$response = service('response', null, false);
262+
$response->pretend();
263+
264+
CITestStreamFilter::removeOutputFilter();
265+
266+
$this->handler->handle(new RuntimeException('Something broke.'), $request, $response, 500, EXIT_ERROR);
267+
268+
$this->assertStringContainsString('[' . RuntimeException::class . ']', $this->getStreamFilterBuffer());
269+
$this->assertStringContainsString('Something broke.', $this->getStreamFilterBuffer());
270+
}
271+
256272
public function testMaskSensitiveData(): void
257273
{
258274
$maskSensitiveData = self::getPrivateMethodInvoker($this->handler, 'maskSensitiveData');

‎user_guide_src/source/changelogs/v4.8.0.rst‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ Behavior Changes
2525

2626
- The static ``Boot::initializeConsole()`` method no longer handles the display of the console header. This is now handled within ``Console::run()``.
2727
If you have overridden ``Boot::initializeConsole()``, you should remove any code related to displaying the console header, as this is now the responsibility of the ``Console`` class.
28+
- **CLI:** Uncaught exceptions in ``spark``, and errors shown with ``BaseCommand::showError()`` or ``AbstractCommand::renderThrowable()`` (as ``migrate`` and
29+
``db:seed`` do), are now printed to STDERR instead of STDOUT. The exit code is unchanged.
30+
See :ref:`upgrade-480-cli-error-output`.
2831
- **Commands:** The ``-h`` option to ``routes`` command which was mapped previously to the ``--sort-by-handler`` option is now removed.
2932
Use ``--sort-by-handler`` instead to sort the routes by handler when running the ``routes`` command.
3033
- **Commands:** The ``filter:check`` command now requires the HTTP method argument to be uppercase (e.g., ``spark filter:check GET /`` instead of ``spark filter:check get /``).

‎user_guide_src/source/cli/cli_commands.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ be familiar with when creating your own commands. It also has a :doc:`Logger </g
127127
128128
:param Throwable $e: The exception to use for error reporting.
129129

130-
A convenience method to maintain a consistent and clear error output to the CLI:
130+
A convenience method to maintain a consistent and clear error output on STDERR:
131131

132132
.. literalinclude:: cli_commands/006.php
133133

‎user_guide_src/source/cli/cli_modern_commands.rst‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -620,8 +620,8 @@ covered in the sections above and are not listed here.
620620
621621
:param Throwable $e: The throwable to render.
622622

623-
Produces the same formatted output the framework uses for uncaught
624-
exceptions. Safe to call from any command.
623+
Produces the same formatted output on STDERR that the framework uses
624+
for uncaught exceptions. Safe to call from any command.
625625

626626
.. php:method:: hasArgument(string $name): bool
627627

0 commit comments

Comments
 (0)