Skip to content

Commit 8b0a895

Browse files
authored
feat: modernise colour detection with FORCE_COLOR, COLORTERM and TERM=dumb (#10653)
1 parent 50df18d commit 8b0a895

3 files changed

Lines changed: 165 additions & 74 deletions

File tree

‎system/CLI/Terminal.php‎

Lines changed: 33 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -92,36 +92,53 @@ public function streamSupports(string $function, $stream): bool
9292
}
9393

9494
/**
95-
* Whether the stream supports colours, following https://no-color.org/ and the Windows console emulators.
95+
* Whether the stream supports colours, following https://no-color.org/, https://force-color.org/ and the terminal hints.
9696
*
9797
* @param resource $stream
9898
*/
9999
public function hasColorSupport($stream): bool
100100
{
101-
if ($this->hasEnv('NO_COLOR')) {
101+
$noColor = env('NO_COLOR');
102+
103+
if ($noColor !== null && $noColor !== '') {
104+
// no-color.org: only an empty value is disregarded.
102105
return false;
103106
}
104107

105-
if (getenv('TERM_PROGRAM') === 'Hyper') {
108+
$forceColor = env('FORCE_COLOR');
109+
110+
if ($forceColor !== null && $forceColor !== '') {
111+
// force-color.org: only an empty value is disregarded.
106112
return true;
107113
}
108114

109-
if (is_windows()) {
110-
return $this->streamSupports('sapi_windows_vt100_support', $stream)
111-
|| $this->hasEnv('ANSICON')
112-
|| getenv('ConEmuANSI') === 'ON'
113-
|| getenv('TERM') === 'xterm';
115+
$msystem = strtoupper((string) env('MSYSTEM', ''));
116+
117+
if (! $this->streamSupports('stream_isatty', $stream) && $msystem !== 'MINGW32' && $msystem !== 'MINGW64') {
118+
return false;
114119
}
115120

116-
return $this->streamSupports('stream_isatty', $stream);
117-
}
121+
if (is_windows() && $this->streamSupports('sapi_windows_vt100_support', $stream)) {
122+
return true;
123+
}
118124

119-
/**
120-
* Whether the variable is set in the live `$_SERVER` or the process environment.
121-
*/
122-
private function hasEnv(string $name): bool
123-
{
124-
return isset($_SERVER[$name]) || getenv($name) !== false; // @phpstan-ignore codeigniter.superglobalsOffsetAccess (reads live $_SERVER, not the snapshot service)
125+
if (
126+
env('TERM_PROGRAM') === 'Hyper'
127+
|| env('COLORTERM') !== null
128+
|| env('ANSICON') !== null
129+
|| env('ConEmuANSI') === 'ON'
130+
) {
131+
return true;
132+
}
133+
134+
$term = (string) env('TERM', '');
135+
136+
if ($term === 'dumb') {
137+
return false;
138+
}
139+
140+
return ! is_windows()
141+
|| preg_match('/^((screen|xterm|vt100|vt220|putty|rxvt|ansi|cygwin|linux).*)|(.*-256(color)?(-bce)?)$/', $term) === 1;
125142
}
126143

127144
/**

‎tests/system/CLI/TerminalTest.php‎

Lines changed: 127 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,60 @@
2525
#[Group('Others')]
2626
final class TerminalTest extends CIUnitTestCase
2727
{
28+
private const COLOR_HINTS = [
29+
'NO_COLOR',
30+
'FORCE_COLOR',
31+
'MSYSTEM',
32+
'TERM_PROGRAM',
33+
'COLORTERM',
34+
'ANSICON',
35+
'ConEmuANSI',
36+
'TERM',
37+
];
38+
39+
/**
40+
* @var array<string, array{false|string, mixed, array<array-key, mixed>|float|int|string|null}>
41+
*/
42+
private array $savedHints = [];
43+
44+
protected function setUp(): void
45+
{
46+
parent::setUp();
47+
48+
$superglobals = service('superglobals');
49+
50+
foreach (self::COLOR_HINTS as $name) {
51+
$this->savedHints[$name] = [getenv($name), $_ENV[$name] ?? null, $superglobals->server($name)];
52+
53+
putenv($name);
54+
unset($_ENV[$name]);
55+
$superglobals->unsetServer($name);
56+
}
57+
}
58+
59+
protected function tearDown(): void
60+
{
61+
$superglobals = service('superglobals');
62+
63+
foreach ($this->savedHints as $name => [$process, $env, $server]) {
64+
putenv($process === false ? $name : "{$name}={$process}");
65+
66+
if ($env === null) {
67+
unset($_ENV[$name]);
68+
} else {
69+
$_ENV[$name] = $env;
70+
}
71+
72+
if ($server === null) {
73+
$superglobals->unsetServer($name);
74+
} else {
75+
$superglobals->setServer($name, $server);
76+
}
77+
}
78+
79+
parent::tearDown();
80+
}
81+
2882
public function testDimensionsArePositive(): void
2983
{
3084
$terminal = new Terminal();
@@ -73,46 +127,25 @@ function_exists('sapi_windows_vt100_support'),
73127
);
74128
}
75129

76-
public function testHasColorSupportFollowsNoColorInTheEnvironment(): void
130+
public function testHasColorSupportFollowsNoColorInServer(): void
77131
{
78-
$noColor = getenv('NO_COLOR');
79-
putenv('NO_COLOR=1');
132+
service('superglobals')->setServer('NO_COLOR', '1');
80133

81-
try {
82-
$this->assertFalse((new Terminal())->hasColorSupport(STDOUT));
83-
} finally {
84-
putenv($noColor === false ? 'NO_COLOR' : "NO_COLOR={$noColor}");
85-
}
134+
$this->assertFalse((new Terminal())->hasColorSupport(STDOUT));
86135
}
87136

88-
public function testHasColorSupportFollowsNoColorInServer(): void
137+
public function testHasColorSupportFollowsNoColorInDotEnv(): void
89138
{
90-
$superglobals = service('superglobals');
139+
$_ENV['NO_COLOR'] = '1';
91140

92-
$noColor = $superglobals->server('NO_COLOR');
93-
$superglobals->setServer('NO_COLOR', '1');
94-
95-
try {
96-
$this->assertFalse((new Terminal())->hasColorSupport(STDOUT));
97-
} finally {
98-
if ($noColor === null) {
99-
$superglobals->unsetServer('NO_COLOR');
100-
} else {
101-
$superglobals->setServer('NO_COLOR', $noColor);
102-
}
103-
}
141+
$this->assertFalse((new Terminal())->hasColorSupport(STDOUT));
104142
}
105143

106-
public function testHasColorSupportOnHyperTerminals(): void
144+
public function testHasColorSupportFollowsForceColorInServer(): void
107145
{
108-
$termProgram = getenv('TERM_PROGRAM');
109-
putenv('TERM_PROGRAM=Hyper');
146+
service('superglobals')->setServer('FORCE_COLOR', '1');
110147

111-
try {
112-
$this->assertTrue((new Terminal())->hasColorSupport(STDOUT));
113-
} finally {
114-
putenv($termProgram === false ? 'TERM_PROGRAM' : "TERM_PROGRAM={$termProgram}");
115-
}
148+
$this->assertTrue($this->createTerminal(tty: false)->hasColorSupport(STDOUT));
116149
}
117150

118151
public function testHasColorSupportFallsBackToTheStreamCheck(): void
@@ -123,49 +156,85 @@ public function testHasColorSupportFallsBackToTheStreamCheck(): void
123156
/**
124157
* @param array<string, string> $env
125158
*/
126-
#[DataProvider('provideHasColorSupportOnWindowsFollowsTheConsoleHints')]
127-
public function testHasColorSupportOnWindowsFollowsTheConsoleHints(array $env, bool $expected): void
159+
#[DataProvider('provideHasColorSupportFollowsTheTerminalHints')]
160+
public function testHasColorSupportFollowsTheTerminalHints(array $env, bool $windows, bool $tty, bool $vt100, bool $expected): void
128161
{
129-
$saved = [];
130-
131-
foreach (['ANSICON', 'ConEmuANSI', 'TERM'] as $name) {
132-
$saved[$name] = getenv($name);
133-
putenv($name);
134-
}
135-
136162
foreach ($env as $name => $value) {
137163
putenv("{$name}={$value}");
138164
}
139165

140-
is_windows(true);
166+
is_windows($windows);
141167

142-
try {
143-
$this->assertSame(
144-
$expected || function_exists('sapi_windows_vt100_support'),
145-
(new Terminal())->hasColorSupport(STDOUT),
146-
);
147-
} finally {
148-
foreach ($saved as $name => $value) {
149-
putenv($value === false ? $name : "{$name}={$value}");
150-
}
151-
}
168+
$this->assertSame($expected, $this->createTerminal($tty, $vt100)->hasColorSupport(STDOUT));
152169
}
153170

154171
/**
155-
* @return iterable<string, array{array<string, string>, bool}>
172+
* @return iterable<string, array{array<string, string>, bool, bool, bool, bool}>
156173
*/
157-
public static function provideHasColorSupportOnWindowsFollowsTheConsoleHints(): iterable
174+
public static function provideHasColorSupportFollowsTheTerminalHints(): iterable
158175
{
159-
yield 'no hints' => [[], false];
176+
yield 'NO_COLOR over FORCE_COLOR' => [['NO_COLOR' => '1', 'FORCE_COLOR' => '1'], false, true, false, false];
177+
178+
yield 'NO_COLOR of 0' => [['NO_COLOR' => '0'], false, true, false, false];
179+
180+
yield 'NO_COLOR of false' => [['NO_COLOR' => 'false'], false, true, false, false];
181+
182+
yield 'empty NO_COLOR' => [['NO_COLOR' => ''], false, true, false, true];
183+
184+
yield 'FORCE_COLOR without a TTY' => [['FORCE_COLOR' => '1'], false, false, false, true];
185+
186+
yield 'FORCE_COLOR of 0 without a TTY' => [['FORCE_COLOR' => '0'], false, false, false, true];
187+
188+
yield 'FORCE_COLOR of false without a TTY' => [['FORCE_COLOR' => 'false'], false, false, false, true];
189+
190+
yield 'empty FORCE_COLOR without a TTY' => [['FORCE_COLOR' => ''], false, false, false, false];
191+
192+
yield 'no TTY' => [[], false, false, false, false];
193+
194+
yield 'no TTY under MINGW64' => [['MSYSTEM' => 'MINGW64', 'TERM' => 'xterm'], true, false, false, true];
195+
196+
yield 'no TTY under lowercase mingw32' => [['MSYSTEM' => 'mingw32', 'TERM' => 'xterm'], true, false, false, true];
160197

161-
yield 'ANSICON' => [['ANSICON' => '1'], true];
198+
yield 'no TTY under MSYS' => [['MSYSTEM' => 'MSYS', 'TERM' => 'xterm'], true, false, false, false];
162199

163-
yield 'ConEmuANSI on' => [['ConEmuANSI' => 'ON'], true];
200+
yield 'Windows VT100' => [[], true, true, true, true];
164201

165-
yield 'ConEmuANSI off' => [['ConEmuANSI' => 'OFF'], false];
202+
yield 'VT100 support ignored off Windows' => [['TERM' => 'dumb'], false, true, true, false];
166203

167-
yield 'TERM xterm' => [['TERM' => 'xterm'], true];
204+
yield 'Hyper' => [['TERM_PROGRAM' => 'Hyper', 'TERM' => 'dumb'], true, true, false, true];
205+
206+
yield 'COLORTERM' => [['COLORTERM' => 'truecolor'], true, true, false, true];
207+
208+
yield 'ANSICON' => [['ANSICON' => '1'], true, true, false, true];
209+
210+
yield 'ConEmuANSI on' => [['ConEmuANSI' => 'ON'], true, true, false, true];
211+
212+
yield 'ConEmuANSI off' => [['ConEmuANSI' => 'OFF'], true, true, false, false];
213+
214+
yield 'TERM dumb' => [['TERM' => 'dumb'], false, true, false, false];
215+
216+
yield 'TTY without TERM' => [[], false, true, false, true];
217+
218+
yield 'TTY with an unlisted TERM' => [['TERM' => 'unknown'], false, true, false, true];
219+
220+
yield 'Windows without hints' => [[], true, true, false, false];
221+
222+
yield 'Windows TERM xterm' => [['TERM' => 'xterm'], true, true, false, true];
223+
224+
yield 'Windows TERM cygwin' => [['TERM' => 'cygwin'], true, true, false, true];
225+
226+
yield 'Windows TERM 256color' => [['TERM' => 'tmux-256color'], true, true, false, true];
227+
228+
yield 'Windows unlisted TERM' => [['TERM' => 'unknown'], true, true, false, false];
229+
}
230+
231+
private function createTerminal(bool $tty, bool $vt100 = false): Terminal
232+
{
233+
$terminal = $this->createPartialMock(Terminal::class, ['streamSupports']);
234+
$terminal->method('streamSupports')->willReturnCallback(
235+
static fn (string $function): bool => $function === 'stream_isatty' ? $tty : $vt100,
236+
);
168237

169-
yield 'TERM other' => [['TERM' => 'xterm-256color'], false];
238+
return $terminal;
170239
}
171240
}

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ Behavior Changes
3636
- **CLI:** ``CLI::showProgress()`` now draws a full bar at 100% for a step beyond the total, instead of throwing a ``ValueError``.
3737
- **CLI:** ``CLI::error()`` no longer leaves colour support disabled for STDOUT when it is given an invalid colour name, and
3838
``CLI::write()``, ``CLI::print()``, and ``CLI::color()`` now accept an empty foreground with a background instead of throwing.
39+
- **CLI:** An empty ``NO_COLOR`` no longer turns colour off, following https://no-color.org/. Colour detection now turns colour off when ``TERM`` is ``dumb``, and on Windows when the stream is not a terminal (outside MSYS2's
40+
``MINGW32`` and ``MINGW64``). On Windows without VT100 support, any ``TERM`` starting with ``xterm``, ``screen``, ``vt100``, ``vt220``, ``putty``,
41+
``rxvt``, ``ansi``, ``cygwin`` or ``linux``, or ending in ``-256color``, now enables colour, where previously only ``xterm`` did.
3942
Colouring text that already contains a coloured segment now keeps that segment whatever its colour, where previously only the
4043
dim colours (``\033[0;...m``) were kept and a bright or background-only segment lost the colour of the text after it.
4144
- **CLI:** The output state moved out of the static ``CLI`` properties. A subclass of ``CLI`` that overrides ``fwrite()`` or ``color()``, or reads
@@ -269,6 +272,8 @@ Commands
269272
See :ref:`modern-commands-writing-output`.
270273
- Added ``--silent``, ``--quiet`` / ``-q``, and ``--verbose`` / ``-v``, ``-vv``, ``-vvv`` to every command, with ``SHELL_VERBOSITY`` as the fallback. Modern
271274
commands can write at a :php:class:`Verbosity <CodeIgniter\\CLI\\Verbosity>` through ``$this->getOutput()``. ``lang:find`` uses the global ``--verbose`` in place of its own. See :ref:`spark-verbosity` and :ref:`modern-commands-verbosity`.
275+
- Colour detection now honours ``FORCE_COLOR`` (see https://force-color.org/), which turns colour on even when the output is piped, and ``COLORTERM``.
276+
``NO_COLOR`` still wins over both. The colour variables can also be set in the **.env** file.
272277
- Added :php:class:`AbstractGeneratorCommand <CodeIgniter\\CLI\\AbstractGeneratorCommand>` and the ``#[GeneratorCommand]`` attribute, the modern
273278
counterpart of ``GeneratorTrait`` for commands that generate files from templates. Generator commands built on it accept the ``-n``, ``-s``,
274279
and ``-f`` shortcuts for ``--namespace``, ``--suffix``, and ``--force``. See :doc:`../cli/cli_modern_generators`.

0 commit comments

Comments
 (0)