From 38cbc11944b72825bc62e69a72cec2bd7ce04ee4 Mon Sep 17 00:00:00 2001 From: Ademar Seide <59055854+ademarsj@users.noreply.github.com> Date: Fri, 17 Feb 2023 10:25:13 -0300 Subject: [PATCH] feat: dont print escape backslash on strings containing escaped backslashes (#401) * feat: dont print escape backslash on strings containing escaped backslashes * fix: changing replace to work on node 14 * fix: grammar issues --- lib/utils.js | 7 ++++++- test/lib/utils.public.test.js | 10 ++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/utils.js b/lib/utils.js index d8aa3cc2..01335136 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -405,16 +405,21 @@ function prettifyObject ({ result += colorizer.greyMessage(stringifySafe(plain)) } result += eol + // Avoid printing the escape character on escaped backslashes. + result = result.replace(/\\\\/gi, '\\') } else { // Put each object entry on its own line Object.entries(plain).forEach(([keyName, keyValue]) => { // custom prettifiers are already applied above, so we can skip it now - const lines = typeof customPrettifiers[keyName] === 'function' + let lines = typeof customPrettifiers[keyName] === 'function' ? keyValue : stringifySafe(keyValue, null, 2) if (lines === undefined) return + // Avoid printing the escape character on escaped backslashes. + lines = lines.replace(/\\\\/gi, '\\') + const joinedLines = joinLinesWithIndentation({ input: lines, ident, eol }) result += `${ident}${keyName}:${joinedLines.startsWith(eol) ? '' : ' '}${joinedLines}${eol}` }) diff --git a/test/lib/utils.public.test.js b/test/lib/utils.public.test.js index ee7b0fa1..c6b20e2c 100644 --- a/test/lib/utils.public.test.js +++ b/test/lib/utils.public.test.js @@ -270,6 +270,16 @@ tap.test('prettifyObject', t => { t.equal(str, ' foo: "bar"\n') }) + t.test('ignores escaped backslashes in string values', async t => { + const str = prettifyObject({ input: { foo_regexp: '\\[^\\w\\s]\\' } }) + t.equal(str, ' foo_regexp: "\\[^\\w\\s]\\"\n') + }) + + t.test('ignores escaped backslashes in string values (singleLine option)', async t => { + const str = prettifyObject({ input: { foo_regexp: '\\[^\\w\\s]\\' }, singleLine: true }) + t.equal(str, '{"foo_regexp":"\\[^\\w\\s]\\"}\n') + }) + t.test('works with error props', async t => { const err = Error('Something went wrong') const serializedError = {