diff --git a/system/CLI/CLI.php b/system/CLI/CLI.php index f116f4c5f533..fcbbf429b043 100644 --- a/system/CLI/CLI.php +++ b/system/CLI/CLI.php @@ -161,6 +161,13 @@ class CLI */ protected static $width; + /** + * Whether the current stream supports colored output. + * + * @var boolean + */ + protected static $isColored = false; + //-------------------------------------------------------------------- /** @@ -177,6 +184,9 @@ public static function init() static::$segments = []; static::$options = []; + // Check our stream resource for color support + static::$isColored = static::hasColorSupport(STDOUT); + static::parseCommandLine(); static::$initialized = true; @@ -487,7 +497,7 @@ public static function clearScreen() */ public static function color(string $text, string $foreground, string $background = null, string $format = null): string { - if (! static::hasColorSupport(STDOUT)) + if (! static::$isColored) { return $text; } @@ -544,7 +554,7 @@ public static function color(string $text, string $foreground, string $backgroun } } - return $string . ($text . "\033[0m"); + return $string . $text . "\033[0m"; } //-------------------------------------------------------------------- diff --git a/tests/system/CLI/CLITest.php b/tests/system/CLI/CLITest.php index c954a77abd9f..2c6c844051ae 100644 --- a/tests/system/CLI/CLITest.php +++ b/tests/system/CLI/CLITest.php @@ -97,6 +97,7 @@ public function testColorSupportOnNoColor() $nocolor = getenv('NO_COLOR'); putenv('NO_COLOR=1'); + CLI::init(); // force re-check on env $this->assertEquals('test', CLI::color('test', 'white', 'green')); putenv($nocolor ? "NO_COLOR=$nocolor" : 'NO_COLOR'); } @@ -106,6 +107,7 @@ public function testColorSupportOnHyperTerminals() $termProgram = getenv('TERM_PROGRAM'); putenv('TERM_PROGRAM=Hyper'); + CLI::init(); // force re-check on env $this->assertEquals("\033[1;37m\033[42m\033[4mtest\033[0m", CLI::color('test', 'white', 'green', 'underline')); putenv($termProgram ? "TERM_PROGRAM=$termProgram" : 'TERM_PROGRAM'); } @@ -118,6 +120,9 @@ public function testStreamSupports() public function testColor() { + // After the tests on NO_COLOR and TERM_PROGRAM above, + // the $isColored variable is rigged. So we reset this. + CLI::init(); $this->assertEquals("\033[1;37m\033[42m\033[4mtest\033[0m", CLI::color('test', 'white', 'green', 'underline')); }