diff options
author | Nayeem Rahman <nayeemrmn99@gmail.com> | 2020-06-24 14:47:05 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-06-24 09:47:05 -0400 |
commit | 3314b463215a8e59ec46d722adb70a22cd3ef832 (patch) | |
tree | 222f16f6652998fa91393956bc9cc907a610d30c | |
parent | 702547d65a9cb60ca6672792c08225b1c3099bad (diff) |
fix(cli/js/web/console): Improve string quoting behaviour (#6457)
-rw-r--r-- | cli/js/web/console.ts | 20 | ||||
-rw-r--r-- | cli/tests/unit/console_test.ts | 7 |
2 files changed, 26 insertions, 1 deletions
diff --git a/cli/js/web/console.ts b/cli/js/web/console.ts index 9f166b373..f6ea7a0a7 100644 --- a/cli/js/web/console.ts +++ b/cli/js/web/console.ts @@ -300,6 +300,24 @@ function stringify( } } +// We can match Node's quoting behavior exactly by swapping the double quote and +// single quote in this array. That would give preference to single quotes. +// However, we prefer double quotes as the default. +const QUOTES = ['"', "'", "`"]; + +/** Surround the string in quotes. + * + * The quote symbol is chosen by taking the first of the `QUOTES` array which + * does not occur in the string. If they all occur, settle with `QUOTES[0]`. + * + * Insert a backslash before any occurrence of the chosen quote symbol and + * before any backslash. */ +function quoteString(string: string): string { + const quote = QUOTES.find((c) => !string.includes(c)) ?? QUOTES[0]; + const escapePattern = new RegExp(`(?=[${quote}\\\\])`, "g"); + return `${quote}${string.replace(escapePattern, "\\")}${quote}`; +} + // Print strings when they are inside of arrays or objects with quotes function stringifyWithQuotes( value: unknown, @@ -313,7 +331,7 @@ function stringifyWithQuotes( value.length > STR_ABBREVIATE_SIZE ? value.slice(0, STR_ABBREVIATE_SIZE) + "..." : value; - return green(`"${trunc}"`); // Quoted strings are green + return green(quoteString(trunc)); // Quoted strings are green default: return stringify(value, ctx, level, maxLevel); } diff --git a/cli/tests/unit/console_test.ts b/cli/tests/unit/console_test.ts index 7634ff0e1..d7281fbb2 100644 --- a/cli/tests/unit/console_test.ts +++ b/cli/tests/unit/console_test.ts @@ -64,6 +64,13 @@ unitTest(function consoleTestStringifyComplexObjects(): void { assertEquals(stringify({ foo: "bar" }), `{ foo: "bar" }`); }); +unitTest(function consoleTestStringifyQuotes(): void { + assertEquals(stringify(["\\"]), `[ "\\\\" ]`); + assertEquals(stringify(['\\,"']), `[ '\\\\,"' ]`); + assertEquals(stringify([`\\,",'`]), `[ \`\\\\,",'\` ]`); + assertEquals(stringify(["\\,\",',`"]), `[ "\\\\,\\",',\`" ]`); +}); + unitTest(function consoleTestStringifyLongStrings(): void { const veryLongString = "a".repeat(200); // If we stringify an object containing the long string, it gets abbreviated. |