Support colors array in util.styleText (#15872)

This commit is contained in:
Jarred Sumner
2024-12-18 23:23:42 -08:00
committed by GitHub
parent 10990f5213
commit ebc2eb5c5b
2 changed files with 29 additions and 2 deletions

View File

@@ -206,7 +206,28 @@ function styleText(format, text) {
e.code = "ERR_INVALID_ARG_TYPE";
throw e;
}
const formatCodes = inspect.colors[format];
if ($isJSArray(format)) {
let left = "";
let right = "";
for (const key of format) {
const formatCodes = inspect.colors[key];
if (formatCodes == null) {
const e = new Error(
`The value "${typeof key === "symbol" ? key.description : key}" is invalid for argument 'format'. Reason: must be one of: ${Object.keys(inspect.colors).join(", ")}`,
);
e.code = "ERR_INVALID_ARG_VALUE";
throw e;
}
left += `\u001b[${formatCodes[0]}m`;
right = `\u001b[${formatCodes[1]}m${right}`;
}
return `${left}${text}${right}`;
}
let formatCodes = inspect.colors[format];
if (formatCodes == null) {
const e = new Error(
`The value "${typeof format === "symbol" ? format.description : format}" is invalid for argument 'format'. Reason: must be one of: ${Object.keys(inspect.colors).join(", ")}`,

View File

@@ -341,7 +341,13 @@ describe("util", () => {
});
it("styleText", () => {
[undefined, null, false, 5n, 5, Symbol(), () => {}, {}, []].forEach(invalidOption => {
it("multiplecolors", () => {
expect(util.styleText(["bold", "red"], "test")).toBe("\u001b[1m\u001b[31mtest\u001b[39m\u001b[22m");
expect(util.styleText("bold"), "test").toBe("\u001b[1mtest\u001b[22m");
expect(util.styleText("red", "test")).toBe("\u001b[31mtest\u001b[39m");
});
[undefined, null, false, 5n, 5, Symbol(), () => {}, {}].forEach(invalidOption => {
assert.throws(
() => {
util.styleText(invalidOption, "test");