Skip to content

Commit

Permalink
Merge pull request #3181 from paulbalandan/refactor-cli-color-support
Browse files Browse the repository at this point in the history
Refactor color detection in CLI
  • Loading branch information
lonnieezell authored Jun 29, 2020
2 parents 512f7b2 + c4726e4 commit d9864e3
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
14 changes: 12 additions & 2 deletions system/CLI/CLI.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,13 @@ class CLI
*/
protected static $width;

/**
* Whether the current stream supports colored output.
*
* @var boolean
*/
protected static $isColored = false;

//--------------------------------------------------------------------

/**
Expand All @@ -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;
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -544,7 +554,7 @@ public static function color(string $text, string $foreground, string $backgroun
}
}

return $string . ($text . "\033[0m");
return $string . $text . "\033[0m";
}

//--------------------------------------------------------------------
Expand Down
5 changes: 5 additions & 0 deletions tests/system/CLI/CLITest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}
Expand All @@ -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');
}
Expand All @@ -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'));
}

Expand Down

0 comments on commit d9864e3

Please sign in to comment.