Skip to content

Commit

Permalink
refactor(@angular/cli): allow tty and color helpers to use a stream
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
clydin authored and alan-agius4 committed Jun 21, 2024
1 parent 438b530 commit 8b6ae4c
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 24 deletions.
30 changes: 8 additions & 22 deletions packages/angular/cli/src/utilities/color.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,29 +10,15 @@ import { WriteStream } from 'node:tty';

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

export function supportColor(): boolean {
if (process.env.FORCE_COLOR !== undefined) {
// 2 colors: FORCE_COLOR = 0 (Disables colors), depth 1
// 16 colors: FORCE_COLOR = 1, depth 4
// 256 colors: FORCE_COLOR = 2, depth 8
// 16,777,216 colors: FORCE_COLOR = 3, depth 16
// See: https://nodejs.org/dist/latest-v12.x/docs/api/tty.html#tty_writestream_getcolordepth_env
// and https://github.com/nodejs/node/blob/b9f36062d7b5c5039498e98d2f2c180dca2a7065/lib/internal/tty.js#L106;
switch (process.env.FORCE_COLOR) {
case '':
case 'true':
case '1':
case '2':
case '3':
return true;
default:
return false;
}
export function supportColor(stream: NodeJS.WritableStream = process.stdout): boolean {
if (stream instanceof WriteStream) {
return stream.hasColors();
}

if (process.stdout instanceof WriteStream) {
return process.stdout.getColorDepth() > 1;
try {
// The hasColors function does not rely on any instance state and should ideally be static
return WriteStream.prototype.hasColors();
} catch {
return process.env['FORCE_COLOR'] !== undefined && process.env['FORCE_COLOR'] !== '0';
}

return false;
}
4 changes: 2 additions & 2 deletions packages/angular/cli/src/utilities/tty.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ function _isTruthy(value: undefined | string): boolean {
return value !== undefined && value !== '0' && value.toUpperCase() !== 'FALSE';
}

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

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

0 comments on commit 8b6ae4c

Please sign in to comment.