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
master
Christopher Chedeau 2017-01-11 20:36:47 -08:00
parent d25881530f
commit afca3d7e7a
3 changed files with 16 additions and 7 deletions

View File

@ -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);

View File

@ -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 } });

View File

@ -26,9 +26,9 @@ exports[`test strings.js 1`] = `
\"\'\";
\"\\\"\";
\"\\\"\";
\"\\\\\\\"\";
\'\"\';
\'\"\';
\'\\\\\"\';
\"\'\";
\"\'\";