Skip to content

Commit 8b6ae4c

Browse files
clydinalan-agius4
authored andcommitted
refactor(@angular/cli): allow tty and color helpers to use a stream
The `isTTY` and `supportColor` helpers can now accept a stream to check instead of assuming stdout. This is useful if stderr needs to be checked, for instance. Also, color checking now uses Node.js `hasColors` where possible which has been available since Node.js v10.
1 parent 438b530 commit 8b6ae4c

File tree

2 files changed

+10
-24
lines changed

2 files changed

+10
-24
lines changed

packages/angular/cli/src/utilities/color.ts

Lines changed: 8 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -10,29 +10,15 @@ import { WriteStream } from 'node:tty';
1010

1111
export { color as colors, figures } from 'listr2';
1212

13-
export function supportColor(): boolean {
14-
if (process.env.FORCE_COLOR !== undefined) {
15-
// 2 colors: FORCE_COLOR = 0 (Disables colors), depth 1
16-
// 16 colors: FORCE_COLOR = 1, depth 4
17-
// 256 colors: FORCE_COLOR = 2, depth 8
18-
// 16,777,216 colors: FORCE_COLOR = 3, depth 16
19-
// See: https://nodejs.org/dist/latest-v12.x/docs/api/tty.html#tty_writestream_getcolordepth_env
20-
// and https://github.com/nodejs/node/blob/b9f36062d7b5c5039498e98d2f2c180dca2a7065/lib/internal/tty.js#L106;
21-
switch (process.env.FORCE_COLOR) {
22-
case '':
23-
case 'true':
24-
case '1':
25-
case '2':
26-
case '3':
27-
return true;
28-
default:
29-
return false;
30-
}
13+
export function supportColor(stream: NodeJS.WritableStream = process.stdout): boolean {
14+
if (stream instanceof WriteStream) {
15+
return stream.hasColors();
3116
}
3217

33-
if (process.stdout instanceof WriteStream) {
34-
return process.stdout.getColorDepth() > 1;
18+
try {
19+
// The hasColors function does not rely on any instance state and should ideally be static
20+
return WriteStream.prototype.hasColors();
21+
} catch {
22+
return process.env['FORCE_COLOR'] !== undefined && process.env['FORCE_COLOR'] !== '0';
3523
}
36-
37-
return false;
3824
}

packages/angular/cli/src/utilities/tty.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,12 @@ function _isTruthy(value: undefined | string): boolean {
1111
return value !== undefined && value !== '0' && value.toUpperCase() !== 'FALSE';
1212
}
1313

14-
export function isTTY(): boolean {
14+
export function isTTY(stream: NodeJS.WriteStream = process.stdout): boolean {
1515
// If we force TTY, we always return true.
1616
const force = process.env['NG_FORCE_TTY'];
1717
if (force !== undefined) {
1818
return _isTruthy(force);
1919
}
2020

21-
return !!process.stdout.isTTY && !_isTruthy(process.env['CI']);
21+
return !!stream.isTTY && !_isTruthy(process.env['CI']);
2222
}

0 commit comments

Comments
 (0)