Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lib: respect terminal capabilities on styleText #54389

Merged
41 changes: 36 additions & 5 deletions doc/api/util.md
Original file line number Diff line number Diff line change
Expand Up @@ -1810,24 +1810,55 @@ console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m'));
added:
- v21.7.0
- v20.12.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/54389
description: Respect isTTY and colors environment variables
RafaelGSS marked this conversation as resolved.
Show resolved Hide resolved
such as NO_COLORS, NODE_DISABLE_COLORS, and FORCE_COLOR.
-->

* `format` {string | Array} A text format or an Array
of text formats defined in `util.inspect.colors`.
* `text` {string} The text to to be formatted.
* `options` {Object}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You need to add this to the function's signature above.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in cc08b60

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not what I meant. You have to update

## `util.styleText(format, text)`

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@RafaelGSS I've updated the doc for ya :)

* `validateStream` {boolean} When true, `stream` is checked to see if it can handle colors. **Default:** `true`.
* `stream` {Stream} A stream that will be validated if it can be colored. **Default:** `process.stdout`.

This function returns a formatted text considering the `format` passed.
This function returns a formatted text considering the `format` passed
for printing in a terminal, it is aware of the terminal's capabilities
RafaelGSS marked this conversation as resolved.
Show resolved Hide resolved
and act according to the configuration set via `NO_COLORS`,
`NODE_DISABLE_COLORS` and `FORCE_COLOR` environment variables.
RafaelGSS marked this conversation as resolved.
Show resolved Hide resolved

```mjs
import { styleText } from 'node:util';
const errorMessage = styleText('red', 'Error! Error!');
console.log(errorMessage);
import { stderr } from 'node:process';

const successMessage = styleText('green', 'Success!');
console.log(successMessage);

const errorMessage = styleText(
'red',
'Error! Error!',
// Validate if process.stderr has TTY
{ stream: stderr },
);
console.error(successMessage);
```

```cjs
const { styleText } = require('node:util');
const errorMessage = styleText('red', 'Error! Error!');
console.log(errorMessage);
const { stderr } = require('node:process');

const successMessage = styleText('green', 'Success!');
console.log(successMessage);

const errorMessage = styleText(
'red',
'Error! Error!',
// Validate if process.stderr has TTY
{ stream: stderr },
);
console.error(successMessage);
```

`util.inspect.colors` also provides text formats such as `italic`, and
Expand Down
37 changes: 36 additions & 1 deletion lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -92,10 +105,32 @@ 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 output stream to write the styled text to.
RafaelGSS marked this conversation as resolved.
Show resolved Hide resolved
* @returns {string}
*/
function styleText(format, text) {
function styleText(format, text, { validateStream = true, stream = process.stdout } = {}) {
validateString(text, 'text');
RafaelGSS marked this conversation as resolved.
Show resolved Hide resolved
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 (
!stream ||
RafaelGSS marked this conversation as resolved.
Show resolved Hide resolved
!lazyUtilColors().shouldColorize(stream)
) {
return text;
}
}

if (ArrayIsArray(format)) {
let left = '';
let right = '';
Expand Down
46 changes: 43 additions & 3 deletions test/parallel/test-util-styletext.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
'use strict';
require('../common');
const assert = require('assert');
const util = require('util');

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this test is being significantly updated, it would be nice if it could be structured more using node:test

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it blocking? Otherwise, I prefer to do it in a follow-up PR.

const common = require('../common');
const assert = require('node:assert');
const util = require('node:util');
const { WriteStream } = require('node:tty');

const styled = '\u001b[31mtest\u001b[39m';
const noChange = 'test';

const fd = common.getTTYfd();
const writeStream = new WriteStream(fd);

Check failure on line 12 in test/parallel/test-util-styletext.js

View workflow job for this annotation

GitHub Actions / test-linux

--- stderr --- node:tty:92 throw new ERR_INVALID_FD(fd); ^ RangeError [ERR_INVALID_FD]: "fd" must be a positive integer: -1 at new WriteStream (node:tty:92:11) at Object.<anonymous> (/home/runner/work/node/node/test/parallel/test-util-styletext.js:12:21) at Module._compile (node:internal/modules/cjs/loader:1546:14) at Module._extensions..js (node:internal/modules/cjs/loader:1691:10) at Module.load (node:internal/modules/cjs/loader:1317:32) at Module._load (node:internal/modules/cjs/loader:1127:12) at TracingChannel.traceSync (node:diagnostics_channel:315:14) at wrapModuleLoad (node:internal/modules/cjs/loader:217:24) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:166:5) at node:internal/main/run_main_module:30:49 { code: 'ERR_INVALID_FD' } Node.js v23.0.0-pre Command: out/Release/node --test-reporter=spec --test-reporter-destination=stdout --test-reporter=./tools/github_reporter/index.js --test-reporter-destination=stdout /home/runner/work/node/node/test/parallel/test-util-styletext.js

Check failure on line 12 in test/parallel/test-util-styletext.js

View workflow job for this annotation

GitHub Actions / test-macOS

--- stderr --- node:tty:92 throw new ERR_INVALID_FD(fd); ^ RangeError [ERR_INVALID_FD]: "fd" must be a positive integer: -1 at new WriteStream (node:tty:92:11) at Object.<anonymous> (/Users/runner/work/node/node/test/parallel/test-util-styletext.js:12:21) at Module._compile (node:internal/modules/cjs/loader:1546:14) at Module._extensions..js (node:internal/modules/cjs/loader:1691:10) at Module.load (node:internal/modules/cjs/loader:1317:32) at Module._load (node:internal/modules/cjs/loader:1127:12) at TracingChannel.traceSync (node:diagnostics_channel:315:14) at wrapModuleLoad (node:internal/modules/cjs/loader:217:24) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:166:5) at node:internal/main/run_main_module:30:49 { code: 'ERR_INVALID_FD' } Node.js v23.0.0-pre Command: out/Release/node --test-reporter=spec --test-reporter-destination=stdout --test-reporter=./tools/github_reporter/index.js --test-reporter-destination=stdout /Users/runner/work/node/node/test/parallel/test-util-styletext.js

[
undefined,
Expand Down Expand Up @@ -41,3 +49,35 @@
}, {
code: 'ERR_INVALID_ARG_VALUE',
});

assert.throws(() => {
util.styleText('red', 'text', { stream: {} });
}, {
code: 'ERR_INVALID_ARG_TYPE',
});

// does not throw
RafaelGSS marked this conversation as resolved.
Show resolved Hide resolved
util.styleText('red', 'text', { stream: {}, validateStream: false });

assert.strictEqual(util.styleText('red', 'test'), styled);

const originalEnv = process.env;
[
{ isTTY: true, env: {}, expected: styled },
{ isTTY: false, env: {}, expected: noChange },
{ isTTY: true, env: { NODE_DISABLE_COLORS: '1' }, expected: noChange },
{ isTTY: true, env: { NO_COLOR: '1' }, expected: noChange },
{ isTTY: true, env: { FORCE_COLOR: '1' }, expected: styled },
{ isTTY: true, env: { FORCE_COLOR: '1', NODE_DISABLE_COLORS: '1' }, expected: styled },
{ isTTY: false, env: { FORCE_COLOR: '1', NO_COLOR: '1', NODE_DISABLE_COLORS: '1' }, expected: styled },
{ isTTY: true, env: { FORCE_COLOR: '1', NO_COLOR: '1', NODE_DISABLE_COLORS: '1' }, expected: styled },
].forEach((testCase) => {
writeStream.isTTY = testCase.isTTY;
process.env = {
...process.env,
...testCase.env
};
const output = util.styleText('red', 'test', { stream: writeStream });
assert.strictEqual(output, testCase.expected);
process.env = originalEnv;
});
Loading