mirror of
https://github.com/nodejs/node.git
synced 2025-08-15 13:48:44 +02:00
lib: respect terminal capabilities on styleText
This PR changes styleText API to respect terminal capabilities and environment variables such as NO_COLOR, NODE_DISABLE_COLORS, and FORCE_COLOR. PR-URL: https://github.com/nodejs/node/pull/54389 Fixes: https://github.com/nodejs/node/issues/54365 Reviewed-By: Moshe Atlow <moshe@atlow.co.il> Reviewed-By: Claudio Wunder <cwunder@gnome.org> Reviewed-By: Rich Trott <rtrott@gmail.com>
This commit is contained in:
parent
4f14eb1545
commit
4a0ec20a35
4 changed files with 146 additions and 13 deletions
42
lib/util.js
42
lib/util.js
|
@ -56,12 +56,25 @@ const {
|
|||
} = require('internal/util/inspect');
|
||||
const { debuglog } = require('internal/util/debuglog');
|
||||
const {
|
||||
validateBoolean,
|
||||
validateFunction,
|
||||
validateNumber,
|
||||
validateString,
|
||||
validateOneOf,
|
||||
} = require('internal/validators');
|
||||
const {
|
||||
isReadableStream,
|
||||
isWritableStream,
|
||||
isNodeStream,
|
||||
} = require('internal/streams/utils');
|
||||
const types = require('internal/util/types');
|
||||
|
||||
let utilColors;
|
||||
function lazyUtilColors() {
|
||||
utilColors ??= require('internal/util/colors');
|
||||
return utilColors;
|
||||
}
|
||||
|
||||
const binding = internalBinding('util');
|
||||
|
||||
const {
|
||||
|
@ -92,10 +105,25 @@ function escapeStyleCode(code) {
|
|||
/**
|
||||
* @param {string | string[]} format
|
||||
* @param {string} text
|
||||
* @param {object} [options={}]
|
||||
* @param {boolean} [options.validateStream=true] - Whether to validate the stream.
|
||||
* @param {Stream} [options.stream=process.stdout] - The stream used for validation.
|
||||
* @returns {string}
|
||||
*/
|
||||
function styleText(format, text) {
|
||||
function styleText(format, text, { validateStream = true, stream = process.stdout } = {}) {
|
||||
validateString(text, 'text');
|
||||
validateBoolean(validateStream, 'options.validateStream');
|
||||
|
||||
if (validateStream) {
|
||||
if (
|
||||
!isReadableStream(stream) &&
|
||||
!isWritableStream(stream) &&
|
||||
!isNodeStream(stream)
|
||||
) {
|
||||
throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream);
|
||||
}
|
||||
}
|
||||
|
||||
if (ArrayIsArray(format)) {
|
||||
let left = '';
|
||||
let right = '';
|
||||
|
@ -115,6 +143,18 @@ function styleText(format, text) {
|
|||
if (formatCodes == null) {
|
||||
validateOneOf(format, 'format', ObjectKeys(inspect.colors));
|
||||
}
|
||||
|
||||
// Check colorize only after validating arg type and value
|
||||
if (
|
||||
validateStream &&
|
||||
(
|
||||
!stream ||
|
||||
!lazyUtilColors().shouldColorize(stream)
|
||||
)
|
||||
) {
|
||||
return text;
|
||||
}
|
||||
|
||||
return `${escapeStyleCode(formatCodes[0])}${text}${escapeStyleCode(formatCodes[1])}`;
|
||||
}
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue