Skip to content

Commit

Permalink
Fix templateElement escape
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker committed Feb 15, 2020
1 parent 0a85ac9 commit a3af945
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
12 changes: 10 additions & 2 deletions rules/string-content.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ const defaultPatterns = {

const defaultMessage = 'Prefer `{{suggest}}` over `{{match}}`.';

const escapeTemplateElementRaw = string => string.replace(
/(?<=(?:^|[^\\])(?:\\\\)*)(?<symbol>(?:`|\$(?={)))/g,
'\\$<symbol>'
);

function getReplacements(patterns) {
return Object.entries({
...defaultPatterns,
Expand Down Expand Up @@ -88,8 +93,11 @@ const create = context => {
const fixRange = [start + 1, end - 1];
problem.fix = fixer => fixer.replaceTextRange(fixRange, fixed);
} else {
fixed = fixed.replace(/`/g, '\\`').replace(/\$(?={)/g, '\\$');
problem.fix = fixer => replaceTemplateElement(fixer, node, fixed);
problem.fix = fixer => replaceTemplateElement(
fixer,
node,
escapeTemplateElementRaw(fixed)
);
}

context.report(problem);
Expand Down
26 changes: 21 additions & 5 deletions test/string-content.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,12 @@ ruleTester.run('string-content', rule, {
code: 'const foo = \'\\\'\'',
options: [{patterns: {'\'': false}}]
},
/* eslint-disable no-template-curly-in-string */
// `TemplateLiteral`
'const foo = `🦄`'
'const foo = `🦄`',
// Should not escape
'const foo = `\\`\\${1}`'
/* eslint-enable no-template-curly-in-string */
],
invalid: [
// `Literal` string
Expand Down Expand Up @@ -144,16 +148,28 @@ ruleTester.run('string-content', rule, {
},
// Escape
{
code: 'const foo = `foo`',
output: 'const foo = `bar\\`bar`',
code: 'const foo = `foo_foo`',
output: 'const foo = `bar\\`bar_bar\\`bar`',
options: [{patterns: {foo: 'bar`bar'}}],
errors: createError('foo', 'bar`bar')
},
{
code: 'const foo = `foo`',
output: 'const foo = `\\${bar}`',
code: 'const foo = `foo_foo`',
output: 'const foo = `\\${bar}_\\${bar}`',
options: [{patterns: {foo: '${bar}'}}],
errors: createError('foo', '${bar}')
},
{
code: 'const foo = `$foo`', // <-- not escaped $
output: 'const foo = `\\${bar}`',
options: [{patterns: {foo: '{bar}'}}],
errors: createError('foo', '{bar}')
},
{
code: 'const foo = `\\$foo`', // <-- escaped $
output: 'const foo = `\\${bar}`',
options: [{patterns: {foo: '{bar}'}}],
errors: createError('foo', '{bar}')
}
/* eslint-enable no-template-curly-in-string */
]
Expand Down

0 comments on commit a3af945

Please sign in to comment.