Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Fix suggestion for "no-template-curly-in-string" #15574

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 24 additions & 4 deletions lib/rules/no-template-curly-in-string.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,43 @@ module.exports = {
schema: [],

messages: {
unexpectedTemplateExpression: "Unexpected template string expression."
}
unexpectedTemplateExpression: "Unexpected template string expression.",
convertToTemplate: "Convert to ES6 `template`."
},
hasSuggestions: true
},

create(context) {
const regex = /\$\{[^}]+\}/u;
const sourceCode = context.getSourceCode();

return {
Literal(node) {
if (typeof node.value === "string" && regex.test(node.value)) {
context.report({
node,
messageId: "unexpectedTemplateExpression"
messageId: "unexpectedTemplateExpression",
suggest: [
{
messageId: "convertToTemplate",
fix: fixer => {
const text = sourceCode.getText(node);
const oldQuote = text[0];
const textNoQuotes = text.slice(1, -1);
const escapeBackticks = textNoQuotes.replaceAll("`", "\\`");
const unescapeQuotes = escapeBackticks.replaceAll(`\\${oldQuote}`, oldQuote);
// eslint-disable-next-line require-unicode-regexp -- Needs fixing, adding the unicode flag results in "Incomplete quantifier" parsing error
const backTicksInsideCurly = /(?<=\${)\\`([^`]*)\\`(?=})/gi;
ajuanjojjj marked this conversation as resolved.
Show resolved Hide resolved
const unescapeTemplates = unescapeQuotes.replaceAll(backTicksInsideCurly, "`$1`");
const newText = `\`${unescapeTemplates}\``;

return fixer.replaceText(node, newText);
}
}
]
});
}
}
};

}
};
30 changes: 30 additions & 0 deletions tests/lib/rules/no-template-curly-in-string.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,36 @@ ruleTester.run("no-template-curly-in-string", rule, {
code: "'Hello, ${{foo: \"bar\"}.foo}'",
parserOptions,
errors: [{ messageId }]
},
{
code: "'\\'Hello\\', ${\\'name\\'}'",
parserOptions,
errors: [{ messageId }]
},
{
code: "'\"Hello\", ${\"name\"}'",
parserOptions,
errors: [{ messageId }]
},
{
code: "'`Hello`, ${`name`}'",
parserOptions,
errors: [{ messageId }]
},
{
code: "\"'Hello', ${'name'}\"",
parserOptions,
errors: [{ messageId }]
},
{
code: "\"\\\"Hello\\\", ${\\\"name\\\"}\"",
parserOptions,
errors: [{ messageId }]
},
{
code: "\"`Hello`, ${`name`}\"",
parserOptions,
errors: [{ messageId }]
}
]
});