-
Notifications
You must be signed in to change notification settings - Fork 30.3k
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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 | ||
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') | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. There was a problem hiding this comment. Choose a reason for hiding this commentThe 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). There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. oh no, i meant There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I am somewhat puzzled: that exact API is the one implemented here? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. oh, maybe i'm confused. i'd prefer There was a problem hiding this comment. Choose a reason for hiding this commentThe 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:
|
||
) | ||
|
||
const info = colorize.italics.blue.bgYellow; | ||
console.log( | ||
info('italic blue with yellow background') | ||
) | ||
``` | ||
|
||
## `util.format(format[, args...])` | ||
|
||
<!-- YAML | ||
added: v0.5.3 | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 As a user, I’d prefer they be as terse as possible. I’d be more likely to use them the simpler they are. There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 There was a problem hiding this comment. Choose a reason for hiding this commentThe 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))) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do we need to use primordials here? @aduh95 There was a problem hiding this comment. Choose a reason for hiding this commentThe 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), { | ||
|
@@ -2290,6 +2366,7 @@ function stripVTControlCharacters(str) { | |
} | ||
|
||
module.exports = { | ||
colorize, | ||
inspect, | ||
format, | ||
formatWithOptions, | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A citation for “ANSI color codes” would be a good addition.