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

util: add colorize functionality #43523

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 41 additions & 1 deletion doc/api/util.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,47 @@ The `--throw-deprecation` command-line flag and `process.throwDeprecation`
property take precedence over `--trace-deprecation` and
`process.traceDeprecation`.

## `util.format(format[, ...args])`
## `util.colorize`
<!-- YAML
added: REPLACEME
-->

The `util.colorize` object provides functions that add ansi color codes to the
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
The `util.colorize` object provides functions that add ansi color codes to the
The `util.colorize` object provides functions that add ANSI color codes to the

A citation for “ANSI color codes” would be a good addition.

provided string. These may be used to style terminal output.

### `util.colorize.<style>[. ...<style>](string[, ...string])`
<!-- YAML
added: REPLACEME
-->

* `string` {string} The string that is formatted by the chosen style.
* Returns: {string} The formatted string

The API allows to be used with a builder/chaining pattern to add multiple styles
in one call. Nesting color codes is supported.

```js
const { colorize } = util;

console.log(
`${colorize.green('Heads up')}: only the "Heads up" is green`
);

console.log(
colorize.green('green', colorize.yellow('yellow'), 'green')
)

console.log(
colorize.bold.underline.red('bold red underline')
Copy link
Member

Choose a reason for hiding this comment

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

i would definitely prefer to avoid getters; both because it's a more confusing API, and because it's slower. i'd follow colors here, not chalk.

Copy link
Member Author

Choose a reason for hiding this comment

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

Colors supports this notation? Manipulating the string prototype is not ideal (that's the original colors API).

Copy link
Member

Choose a reason for hiding this comment

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

oh no, i meant colors/safe :-) definitely nobody should use the colors style :-)

Copy link
Member Author

Choose a reason for hiding this comment

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

I am somewhat puzzled: that exact API is the one implemented here?

Copy link
Member

Choose a reason for hiding this comment

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

oh, maybe i'm confused. i'd prefer colorize.bold().underline() to colorize.bold.underline, to be clearer.

Copy link
Member Author

Choose a reason for hiding this comment

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

I did consider that as well and I am open to using that, if it's what a majority prefers. Right now I would stick to the existing due to these reasons:

  1. Users of colors and chalk are used to it
  2. Passing a string to only the last call might also be confusing without a .write()/.format() similar function
  3. The performance should pretty much be identical and there should be room for improvement one way or the other (the implementation is already decent performance wise while chalk is still faster)

)

const info = colorize.italics.blue.bgYellow;
console.log(
info('italic blue with yellow background')
)
```

## `util.format(format[, args...])`

<!-- YAML
added: v0.5.3
Expand Down
7 changes: 5 additions & 2 deletions lib/internal/debugger/inspect_repl.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,10 @@ const vm = require('vm');
const { fileURLToPath } = require('internal/url');

const { customInspectSymbol } = require('internal/util');
const { inspect: utilInspect } = require('internal/util/inspect');
const {
inspect: utilInspect,
colorize
} = require('internal/util/inspect');
const debuglog = require('internal/util/debuglog').debuglog('inspect');

const SHORTCUTS = {
Expand Down Expand Up @@ -162,7 +165,7 @@ function markSourceColumn(sourceText, position, useColors) {
// Colourize char if stdout supports colours
if (useColors) {
tail = RegExpPrototypeSymbolReplace(/(.+?)([^\w]|$)/, tail,
'\u001b[32m$1\u001b[39m$2');
`${colorize.gray('$1')}$2`);
}

// Return source line with coloured char at `position`
Expand Down
4 changes: 2 additions & 2 deletions lib/internal/repl/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ function setupPreview(repl, contextSymbol, bufferSymbol, active) {
completionPreview = suffix;

const result = repl.useColors ?
`\u001b[90m${suffix}\u001b[39m` :
colorize.gray(suffix) :
` // ${suffix}`;

const { cursorPos, displayPos } = getPreviewPos();
Expand Down Expand Up @@ -443,7 +443,7 @@ function setupPreview(repl, contextSymbol, bufferSymbol, active) {
}

const result = repl.useColors ?
`\u001b[90m${inspected}\u001b[39m` :
colorize.gray(inspected) :
`// ${inspected}`;

const { cursorPos, displayPos } = getPreviewPos();
Expand Down
77 changes: 77 additions & 0 deletions lib/internal/util/inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,82 @@ defineColorAlias('inverse', 'swapColors');
defineColorAlias('inverse', 'swapcolors');
defineColorAlias('doubleunderline', 'doubleUnderline');

// TODO(BridgeAR): Consider using a class instead and require the user to instantiate it
// before using to declare their color support (or use a default, if none
// provided).
Comment on lines +442 to +444
Copy link
Member

Choose a reason for hiding this comment

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

Why wouldn’t or couldn’t these be simple static functions that require no initialization? I mean, aren’t they essentially just prepending and appending \u001b[90m and \u001b[39m and the like?

As a user, I’d prefer they be as terse as possible. I’d be more likely to use them the simpler they are.

Copy link
Member Author

Choose a reason for hiding this comment

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

Yes and no: if we add more colors such as hex colors later on, we'll need to check that the terminal does indeed support the colors. Currently there's no way to do this besides a best effort check and we sometimes detect colors when not being supported and the other way around. Therefore I would like to provide a way to define the support by the user:

const { Colorize } = require('formatter')

const colorize256 = new Colorize({ colors: 256 })

console.log(
  colorize256.bold.underline.hex('#123456')('bold underline fancy color')
)

Using Colorize.bold.underline.hex('#123456')('bold underline maybe fancy color') could try to auto detect the supported colors while using the instance would be fixed.

Copy link
Member

Choose a reason for hiding this comment

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

These feel like almost two use cases: a simple CLI tool like a test runner that needs only a handful of colors (or only green and red); and a more complicated CLI tool that wants lots of colors. The latter can call some kind of initialization function, since it’s somewhat expected that more work would be required to do something fancy; but ideally the simple case wouldn’t need much ceremony.

const colorize = {};

function defineColorGetter({ style, codes, enumerable }) {
function color(...strings) {
let result = '';
const ansiCodes = this.ansiCodes
let string = strings[0];
for (let i = 1; i < strings.length; i++) {
string += ' ' + strings[i];
}

// Fast path
const searchCode = ansiCodes.length === 1 ? ansiCodes[0].end : '\u001b[';
const ansiCodeStart = string.indexOf(searchCode);
if (ansiCodeStart === -1) {
for (const code of ansiCodes) {
result += code.start;
}
} else {
// Slow path
const start = string.slice(0, ansiCodeStart - 1);
let middle = string.slice(ansiCodeStart - 1, -4);
const end = string.slice(-4);

for (const code of ansiCodes) {
result += code.start;
// Continue former colors by finding end points and continuing from there.
middle = middle.replaceAll(code.end, `$&${code.start}`)
}
string = `${start}${middle}${end}`;
}

result += string;
for (let i = ansiCodes.length - 1; i >= 0; i--) {
result += ansiCodes[i].end;
}

return result;
}

Object.defineProperty(colorize, style, {
__proto__: null,
get: function () {
if (typeof this === 'function') {
this.ansiCodes.push(codes);
return this;
}
const ansiCodes = [codes];
const context = {
ansiCodes
};
let boundColor = color.bind(context);
// Enable chaining.
Object.setPrototypeOf(boundColor, colorize);
boundColor.ansiCodes = ansiCodes;
return boundColor;
},
enumerable,
});
}

for (const [style, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(inspect.colors))) {
Copy link
Member

Choose a reason for hiding this comment

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

Do we need to use primordials here? @aduh95

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 as important at the top level, but it'd probably be a good idea for consistency

const value = descriptor.value ?? descriptor.get.call(inspect.colors);
defineColorGetter({
style,
codes: {
start: `\u001b[${value[0]}m`,
end: `\u001b[${value[1]}m`
},
enumerable: descriptor.enumerable
});
}

// TODO(BridgeAR): Add function style support for more complex styles.
// Don't use 'blue' not visible on cmd.exe
inspect.styles = ObjectAssign(ObjectCreate(null), {
Expand Down Expand Up @@ -2290,6 +2366,7 @@ function stripVTControlCharacters(str) {
}

module.exports = {
colorize,
inspect,
format,
formatWithOptions,
Expand Down