From afca3d7e7adc0fb30da048ad4ffcf058c831311a Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Wed, 11 Jan 2017 20:36:47 -0800 Subject: [PATCH] Minimize string escapes If there you are opting in for double quote but there's a string with a double quote in it, it's better to swap to a single quote to avoid having too many `\`. Note that if there are both single and double quotes in the string, we should use the default string instead. Fixes #139 --- src/printer.js | 13 ++++++++++++- .../child_process/__snapshots__/jsfmt.spec.js.snap | 4 +--- tests/strings/__snapshots__/jsfmt.spec.js.snap | 6 +++--- 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/printer.js b/src/printer.js index 78d2d64d..1edaebaa 100644 --- a/src/printer.js +++ b/src/printer.js @@ -2059,7 +2059,18 @@ function swapQuotes(str) { function nodeStr(str, options) { isString.assert(str); - if (options.singleQuote) { + const containsSingleQuote = str.indexOf("'") !== -1; + const containsDoubleQuote = str.indexOf('"') !== -1; + + let shouldUseSingleQuote = options.singleQuote; + if (options.singleQuote && containsSingleQuote && !containsDoubleQuote) { + shouldUseSingleQuote = false; + } + if (!options.singleQuote && !containsSingleQuote && containsDoubleQuote) { + shouldUseSingleQuote = true; + } + + if (shouldUseSingleQuote) { return swapQuotes(JSON.stringify(swapQuotes(str))); } else { return JSON.stringify(str); diff --git a/tests/node_tests/child_process/__snapshots__/jsfmt.spec.js.snap b/tests/node_tests/child_process/__snapshots__/jsfmt.spec.js.snap index 2b00c505..630144e9 100644 --- a/tests/node_tests/child_process/__snapshots__/jsfmt.spec.js.snap +++ b/tests/node_tests/child_process/__snapshots__/jsfmt.spec.js.snap @@ -164,9 +164,7 @@ var ls = child_process.spawn(\"ls\"); var wc = child_process.spawn(\"wc\", [ \"-l\" ]); // args + options. -child_process.spawn(\"echo\", [ \"-n\", \"\\\"Testing...\\\"\" ], { - env: { TEST: \"foo\" } -}); +child_process.spawn(\"echo\", [ \"-n\", \'\"Testing...\"\' ], { env: { TEST: \"foo\" } }); // options only. child_process.spawn(\"echo\", { env: { FOO: 2 } }); diff --git a/tests/strings/__snapshots__/jsfmt.spec.js.snap b/tests/strings/__snapshots__/jsfmt.spec.js.snap index 288c13f8..2edc67b5 100644 --- a/tests/strings/__snapshots__/jsfmt.spec.js.snap +++ b/tests/strings/__snapshots__/jsfmt.spec.js.snap @@ -26,9 +26,9 @@ exports[`test strings.js 1`] = ` \"\'\"; -\"\\\"\"; -\"\\\"\"; -\"\\\\\\\"\"; +\'\"\'; +\'\"\'; +\'\\\\\"\'; \"\'\"; \"\'\";