From 524b230143e8824a54739f662b51aa40bad614c3 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Mon, 8 Jun 2020 20:30:20 +0200 Subject: [PATCH] util: gracefully handle unknown colors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This makes sure colors that are unknown won't cause an error. This is especially important in case a library wants to use colors defined by Node.js core, if available and fall back to the default otherwise. Signed-off-by: Ruben Bridgewater PR-URL: https://github.com/nodejs/node/pull/33797 Reviewed-By: Anna Henningsen Reviewed-By: Luigi Pinca Reviewed-By: Michaƫl Zasso Reviewed-By: James M Snell Reviewed-By: Evan Lucas Reviewed-By: Yongsheng Zhang Reviewed-By: Trivikram Kamat --- lib/internal/util/inspect.js | 3 ++- test/parallel/test-util-inspect.js | 6 ++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index 113ee6c9532f6c..87bf3435f96067 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -473,7 +473,8 @@ function stylizeWithColor(str, styleType) { const style = inspect.styles[styleType]; if (style !== undefined) { const color = inspect.colors[style]; - return `\u001b[${color[0]}m${str}\u001b[${color[1]}m`; + if (color !== undefined) + return `\u001b[${color[0]}m${str}\u001b[${color[1]}m`; } return str; } diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index 5aea50ba1d1c30..2c7a3a96fa93d2 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -2240,6 +2240,12 @@ assert.strictEqual( assert.deepStrictEqual(inspect.colors[bgColor], [40 + i, 49]); assert.deepStrictEqual(inspect.colors[`${bgColor}Bright`], [100 + i, 49]); }); + + // Unknown colors are handled gracefully: + const stringStyle = inspect.styles.string; + inspect.styles.string = 'UNKNOWN'; + assert.strictEqual(inspect('foobar', { colors: true }), "'foobar'"); + inspect.styles.string = stringStyle; } assert.strictEqual(