Skip to content
Merged
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
4 changes: 3 additions & 1 deletion system/CLI/BaseCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,9 @@ protected function showError(Throwable $e)
$message = $e->getMessage();
$config = config(Exceptions::class);

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

/**
Expand Down
52 changes: 45 additions & 7 deletions system/CLI/CLI.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,8 @@ class CLI
*/
protected static ?InputOutput $io = null;

protected static bool $stdoutToStderr = false;

/**
* Static "constructor".
*
Expand Down Expand Up @@ -1138,23 +1140,59 @@ public static function table(array $tbody, array $thead = [])
*/
protected static function fwrite($handle, string $string)
{
if (static::$stdoutToStderr && $handle === STDOUT) {
$handle = STDERR;
}

static::$io->fwrite($handle, $string);
}

/**
* Runs the callback with its STDOUT writes sent to STDERR.
*
* @param callable(): void $callback
*
* @internal
*/
public static function redirectToStderr(callable $callback): void
{
if (! is_cli()) {
$callback();

return;
}

$stdoutToStderr = static::$stdoutToStderr;
$isColored = static::$isColored;
$lastWrite = static::$lastWrite;

static::$stdoutToStderr = true;
static::$isColored = static::hasColorSupport(STDERR);

try {
$callback();
} finally {
static::$stdoutToStderr = $stdoutToStderr;
static::$isColored = $isColored;
static::$lastWrite = $lastWrite;
}
}

/**
* Testing purpose only
*
* @internal
*/
public static function reset(): void
{
static::$initialized = false;
static::$segments = [];
static::$options = [];
static::$lastWrite = null;
static::$height = null;
static::$width = null;
static::$isColored = static::hasColorSupport(STDOUT);
static::$initialized = false;
static::$segments = [];
static::$options = [];
static::$lastWrite = null;
static::$height = null;
static::$width = null;
static::$isColored = static::hasColorSupport(STDOUT);
static::$stdoutToStderr = false;

static::resetInputOutput();
}
Expand Down
7 changes: 6 additions & 1 deletion system/Debug/ExceptionHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use Closure;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\CLI\CLI;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\Exceptions\HTTPException;
Expand Down Expand Up @@ -121,7 +122,11 @@ public function handle(
}

// Displays the HTML or CLI error code.
$this->render($exception, $statusCode, $viewFile);
if ($request instanceof IncomingRequest) {
$this->render($exception, $statusCode, $viewFile);
} else {
CLI::redirectToStderr(fn () => $this->render($exception, $statusCode, $viewFile));
}

if (! service('environment')->isTesting()) {
exit($exitCode); // @codeCoverageIgnore
Expand Down
3 changes: 3 additions & 0 deletions tests/system/CLI/AbstractCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
use CodeIgniter\Commands\Help;
use CodeIgniter\Exceptions\LogicException;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\Filters\CITestStreamFilter;
use CodeIgniter\Test\Mock\MockInputOutput;
use CodeIgniter\Test\StreamFilterTrait;
use Config\App;
Expand Down Expand Up @@ -234,6 +235,8 @@ public function testRenderThrowable(): void
{
$command = new AppAboutCommand(new Commands());

CITestStreamFilter::removeOutputFilter();

$this->assertSame(EXIT_ERROR, $command->bomb());
$this->assertStringContainsString('[CodeIgniter\CLI\Exceptions\CLIException]', $this->getStreamFilterBuffer());
$this->assertStringContainsString('Invalid "background" color: "Background".', $this->getStreamFilterBuffer());
Expand Down
3 changes: 3 additions & 0 deletions tests/system/CLI/BaseCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use CodeIgniter\CodeIgniter;
use CodeIgniter\Log\Logger;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\Filters\CITestStreamFilter;
use CodeIgniter\Test\StreamFilterTrait;
use PHPUnit\Framework\Attributes\After;
use PHPUnit\Framework\Attributes\Before;
Expand Down Expand Up @@ -89,6 +90,8 @@ public function testShowError(): void
{
$command = new AppInfo(single_service('logger'), single_service('commands'));

CITestStreamFilter::removeOutputFilter();

$this->assertSame(1, $command->bomb());
$this->assertStringContainsString('[CodeIgniter\CLI\Exceptions\CLIException]', $this->getStreamFilterBuffer());
$this->assertStringContainsString('Invalid "background" color: "Background".', $this->getStreamFilterBuffer());
Expand Down
90 changes: 90 additions & 0 deletions tests/system/CLI/CLITest.php
Original file line number Diff line number Diff line change
Expand Up @@ -649,6 +649,96 @@ public function testMixedWriteError(): void
);
}

public function testRedirectToStderrRoutesStdoutWritesOnlyWhileTheCallbackRuns(): void
{
$io = new class () extends InputOutput {
/**
* @var list<array{string, string}>
*/
public array $writes = [];

public function fwrite($handle, string $string): void
{
$this->writes[] = [$handle === STDERR ? 'STDERR' : 'STDOUT', $string];
}
};
CLI::setInputOutput($io);

CLI::print('before');

CLI::redirectToStderr(static function (): void {
CLI::write('inside');
});

try {
CLI::redirectToStderr(static function (): void {
throw new RuntimeException('Callback failed.');
});
} catch (RuntimeException) {
}

CLI::write('after');

$this->assertSame([
['STDOUT', 'before'],
['STDERR', "\ninside\n"],
['STDOUT', "\nafter\n"],
], $io->writes);
}

public function testRedirectToStderrDoesNotRedirectOutsideCli(): void
{
$io = new class () extends InputOutput {
/**
* @var list<array{string, string}>
*/
public array $writes = [];

public function fwrite($handle, string $string): void
{
$this->writes[] = [$handle === STDERR ? 'STDERR' : 'STDOUT', $string];
}
};
CLI::setInputOutput($io);

is_cli(false);

try {
CLI::redirectToStderr(static function (): void {
CLI::write('inside');
});
} finally {
is_cli(true);
}

$this->assertSame([['STDOUT', "\ninside\n"]], $io->writes);
}

public function testRedirectToStderrUsesTheColorSupportOfStderr(): void
{
$superglobals = service('superglobals');
$noColor = $superglobals->server('NO_COLOR');

(new ReflectionProperty(CLI::class, 'isColored'))->setValue(null, true);
$superglobals->setServer('NO_COLOR', '1');

try {
CLI::redirectToStderr(static function (): void {
CLI::write('inside', 'red');
});
} finally {
if ($noColor === null) {
$superglobals->unsetServer('NO_COLOR');
} else {
$superglobals->setServer('NO_COLOR', $noColor);
}
}

CLI::write('after', 'red');

$this->assertSame("\ninside\n\n\033[0;31mafter\033[0m\n", $this->getStreamFilterBuffer());
}

public function testErrorForeground(): void
{
CLI::error('test', 'purple');
Expand Down
16 changes: 16 additions & 0 deletions tests/system/Debug/ExceptionHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use CodeIgniter\HTTP\SiteURI;
use CodeIgniter\HTTP\UserAgent;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\Filters\CITestStreamFilter;
use CodeIgniter\Test\IniTestTrait;
use CodeIgniter\Test\StreamFilterTrait;
use Config\App;
Expand Down Expand Up @@ -253,6 +254,21 @@ public function testHandleCLIPageNotFoundException(): void
$this->resetStreamFilterBuffer();
}

public function testHandleCLIExceptionWritesToStderr(): void
{
$request = Services::clirequest(null, false);
/** @var Response $response */
$response = service('response', null, false);
$response->pretend();

CITestStreamFilter::removeOutputFilter();

$this->handler->handle(new RuntimeException('Something broke.'), $request, $response, 500, EXIT_ERROR);

$this->assertStringContainsString('[' . RuntimeException::class . ']', $this->getStreamFilterBuffer());
$this->assertStringContainsString('Something broke.', $this->getStreamFilterBuffer());
}

public function testMaskSensitiveData(): void
{
$maskSensitiveData = self::getPrivateMethodInvoker($this->handler, 'maskSensitiveData');
Expand Down
3 changes: 3 additions & 0 deletions user_guide_src/source/changelogs/v4.8.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ Behavior Changes

- The static ``Boot::initializeConsole()`` method no longer handles the display of the console header. This is now handled within ``Console::run()``.
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.
- **CLI:** Uncaught exceptions in ``spark``, and errors shown with ``BaseCommand::showError()`` or ``AbstractCommand::renderThrowable()`` (as ``migrate`` and
``db:seed`` do), are now printed to STDERR instead of STDOUT. The exit code is unchanged.
See :ref:`upgrade-480-cli-error-output`.
- **Commands:** The ``-h`` option to ``routes`` command which was mapped previously to the ``--sort-by-handler`` option is now removed.
Use ``--sort-by-handler`` instead to sort the routes by handler when running the ``routes`` command.
- **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 /``).
Expand Down
2 changes: 1 addition & 1 deletion user_guide_src/source/cli/cli_commands.rst
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ be familiar with when creating your own commands. It also has a :doc:`Logger </g

:param Throwable $e: The exception to use for error reporting.

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

.. literalinclude:: cli_commands/006.php

Expand Down
4 changes: 2 additions & 2 deletions user_guide_src/source/cli/cli_modern_commands.rst
Original file line number Diff line number Diff line change
Expand Up @@ -620,8 +620,8 @@ covered in the sections above and are not listed here.

:param Throwable $e: The throwable to render.

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

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

Expand Down
16 changes: 16 additions & 0 deletions user_guide_src/source/installation/upgrade_480.rst
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,22 @@ Command Alternatives Visibility
``CodeIgniter\CLI\Commands::getCommandAlternatives()`` is now ``public``. If you extend ``Commands`` and override this method,
change the override's visibility from ``protected`` to ``public``.

.. _upgrade-480-cli-error-output:

CLI Error Output
================

Uncaught exceptions in ``spark``, and errors shown with ``BaseCommand::showError()`` or
``AbstractCommand::renderThrowable()``, are now printed to STDERR instead of STDOUT, so they no
longer mix with output read by another program.
The exit code is unchanged.

If you redirect only STDOUT to a log file (``php spark my:command > my.log``), errors no longer
reach that file. Redirect STDERR as well to keep them (``php spark my:command > my.log 2>&1``).

A custom CLI error view that writes with ``echo`` instead of the ``CLI`` class still prints to
STDOUT.

Uploaded File Move Return Type
==============================

Expand Down
4 changes: 2 additions & 2 deletions utils/phpstan-baseline/arguments.count.neon
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# total 4 errors
# total 6 errors

parameters:
ignoreErrors:
-
message: '#^Function is_cli invoked with 1 parameter, 0 required\.$#'
count: 2
count: 4
path: ../../tests/system/CLI/CLITest.php

-
Expand Down
2 changes: 1 addition & 1 deletion utils/phpstan-baseline/loader.neon
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# total 30 errors
# total 32 errors

includes:
- arguments.count.neon
Expand Down
Loading