Skip to content
Merged
Show file tree
Hide file tree
Changes from 17 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
22 changes: 22 additions & 0 deletions docs/rules/prefer-string-raw.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Prefer using `String.raw` tag to avoid escaping `\`

💼 This rule is enabled in the ✅ `recommended` [config](https://github.com/sindresorhus/eslint-plugin-unicorn#preset-configs-eslintconfigjs).

🔧 This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix).

<!-- end auto-generated rule header -->
<!-- Do not manually modify this header. Run: `npm run fix:eslint-docs` -->

<!-- Remove this comment, add more detailed description. -->

## Fail

```js
const foo = 'unicorn';
```

## Pass

```js
const foo = '🦄';
```
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,9 @@
"test/integration/{fixtures,fixtures-local}/**"
],
"rules": {
"unicorn/escape-case": "off",
"unicorn/expiring-todo-comments": "off",
"unicorn/no-hex-escape": "off",
"unicorn/no-null": "error",
"unicorn/prefer-array-flat": [
"error",
Expand Down
1 change: 1 addition & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ If you don't use the preset, ensure you use the same `env` and `parserOptions` c
| [prefer-set-has](docs/rules/prefer-set-has.md) | Prefer `Set#has()` over `Array#includes()` when checking for existence or non-existence. | ✅ | 🔧 | 💡 |
| [prefer-set-size](docs/rules/prefer-set-size.md) | Prefer using `Set#size` instead of `Array#length`. | ✅ | 🔧 | |
| [prefer-spread](docs/rules/prefer-spread.md) | Prefer the spread operator over `Array.from(…)`, `Array#concat(…)`, `Array#{slice,toSpliced}()` and `String#split('')`. | ✅ | 🔧 | 💡 |
| [prefer-string-raw](docs/rules/prefer-string-raw.md) | Prefer using `String.raw` tag to avoid escaping `\`. | ✅ | 🔧 | |
| [prefer-string-replace-all](docs/rules/prefer-string-replace-all.md) | Prefer `String#replaceAll()` over regex searches with the global flag. | ✅ | 🔧 | |
| [prefer-string-slice](docs/rules/prefer-string-slice.md) | Prefer `String#slice()` over `String#substr()` and `String#substring()`. | ✅ | 🔧 | |
| [prefer-string-starts-ends-with](docs/rules/prefer-string-starts-ends-with.md) | Prefer `String#startsWith()` & `String#endsWith()` over `RegExp#test()`. | ✅ | 🔧 | 💡 |
Expand Down
1 change: 1 addition & 0 deletions rules/ast/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ module.exports = {
isArrowFunctionBody: require('./is-arrow-function-body.js'),
isCallExpression,
isCallOrNewExpression,
isDirective: require('./is-directive.js'),
isEmptyNode: require('./is-empty-node.js'),
isExpressionStatement: require('./is-expression-statement.js'),
isFunction: require('./is-function.js'),
Expand Down
7 changes: 7 additions & 0 deletions rules/ast/is-directive.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
'use strict';

const isDirective = node =>
node.type === 'ExpressionStatement'
&& typeof node.directive === 'string';

module.exports = isDirective;
3 changes: 1 addition & 2 deletions rules/no-empty-file.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
'use strict';
const {isEmptyNode} = require('./ast/index.js');
const {isEmptyNode, isDirective} = require('./ast/index.js');

const MESSAGE_ID = 'no-empty-file';
const messages = {
[MESSAGE_ID]: 'Empty files are not allowed.',
};

const isDirective = node => node.type === 'ExpressionStatement' && typeof node.directive === 'string';
const isEmpty = node => isEmptyNode(node, isDirective);

const isTripleSlashDirective = node =>
Expand Down
92 changes: 92 additions & 0 deletions rules/prefer-string-raw.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
'use strict';
const {isStringLiteral, isDirective} = require('./ast/index.js');
const {fixSpaceAroundKeyword} = require('./fix/index.js');

const MESSAGE_ID = 'prefer-string-raw';
const messages = {
[MESSAGE_ID]: '`String.raw` should be used to avoid escaping `\\`.',
};

const BACKSLASH = '\\';

function unescapeBackslash(raw) {
const quote = raw.charAt(0);

raw = raw.slice(1, -1);

let result = '';
for (let position = 0; position < raw.length; position++) {
const character = raw[position];
if (character === BACKSLASH) {
const nextCharacter = raw[position + 1];
if (nextCharacter === BACKSLASH || nextCharacter === quote) {
result += nextCharacter;
position++;
continue;
}
}

result += character;
}

return result;
}

/** @param {import('eslint').Rule.RuleContext} context */
const create = context => {
context.on('Literal', node => {
if (
!isStringLiteral(node)
|| isDirective(node.parent)
|| (
(
node.parent.type === 'ImportDeclaration'
|| node.parent.type === 'ExportNamedDeclaration'
|| node.parent.type === 'ExportAllDeclaration'
) && node.parent.source === node
)
|| (node.parent.type === 'Property' && !node.parent.computed && node.parent.key === node)
|| (node.parent.type === 'JSXAttribute' && node.parent.value === node)
) {
return;
}

const {raw} = node;
if (
!raw.includes(BACKSLASH + BACKSLASH)
|| raw.includes('`')
|| raw.includes('${')
|| node.loc.start.line !== node.loc.end.line
) {
return;
}

const unescaped = unescapeBackslash(raw);
if (unescaped.endsWith(BACKSLASH) || unescaped !== node.value) {
return;
}

return {
node,
messageId: MESSAGE_ID,
* fix(fixer) {
yield fixer.replaceText(node, `String.raw\`${unescaped}\``);
yield * fixSpaceAroundKeyword(fixer, node, context.sourceCode);
},
};
});
};

/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Prefer using `String.raw` tag to avoid escaping `\\`.',
recommended: true,
},
fixable: 'code',
messages,
},
};
40 changes: 40 additions & 0 deletions test/prefer-string-raw.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import outdent from 'outdent';
import {getTester} from './utils/test.mjs';

const {test} = getTester(import.meta);

test.snapshot({
valid: [
String.raw`a = '\''`,
// Cannot use `String.raw`
String.raw`'a\\b'`,
String.raw`import foo from "./foo\\bar.js";`,
String.raw`export {foo} from "./foo\\bar.js";`,
String.raw`export * from "./foo\\bar.js";`,
String.raw`a = {'a\\b': ''}`,
outdent`
a = "\\\\a \\
b"
`,
String.raw`a = 'a\\b\u{51}c'`,
'a = "a\\\\b`"',
// eslint-disable-next-line no-template-curly-in-string
'a = "a\\\\b${foo}"',
{
code: String.raw`<Component attribute="a\\b" />`,
languageOptions: {
parserOptions: {
ecmaFeatures: {
jsx: true,
},
},
},
},
],
invalid: [
String.raw`a = 'a\\b'`,
String.raw`a = {['a\\b']: b}`,
String.raw`function a() {return'a\\b'}`,
String.raw`const foo = "foo \\x46";`,
],
});
6 changes: 6 additions & 0 deletions test/run-rules-on-codebase/lint.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ const configs = [
unicorn: eslintPluginUnicorn,
},
rules: eslintPluginUnicorn.configs.all.rules,
linterOptions: {
reportUnusedDisableDirectives: false,
},
},
{
ignores: [
Expand All @@ -44,6 +47,9 @@ const configs = [
rules: {
// https://github.com/sindresorhus/eslint-plugin-unicorn/issues/1109#issuecomment-782689255
'unicorn/consistent-destructuring': 'off',
// https://github.com/sindresorhus/eslint-plugin-unicorn/issues/2341
'unicorn/escape-case': 'off',
'unicorn/no-hex-escape': 'off',
// Buggy
'unicorn/custom-error-definition': 'off',
'unicorn/consistent-function-scoping': 'off',
Expand Down
89 changes: 89 additions & 0 deletions test/snapshots/prefer-string-raw.mjs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# Snapshot report for `test/prefer-string-raw.mjs`

The actual snapshot is saved in `prefer-string-raw.mjs.snap`.

Generated by [AVA](https://avajs.dev).

## invalid(1): a = 'a\\b'

> Input

`␊
1 | a = 'a\\\\b'␊
`

> Output

`␊
1 | a = String.raw\`a\\b\`␊
`

> Error 1/1

`␊
> 1 | a = 'a\\\\b'␊
| ^^^^^^ \`String.raw\` should be used to avoid escaping \`\\\`.␊
`

## invalid(2): a = {['a\\b']: b}

> Input

`␊
1 | a = {['a\\\\b']: b}␊
`

> Output

`␊
1 | a = {[String.raw\`a\\b\`]: b}␊
`

> Error 1/1

`␊
> 1 | a = {['a\\\\b']: b}␊
| ^^^^^^ \`String.raw\` should be used to avoid escaping \`\\\`.␊
`

## invalid(3): function a() {return'a\\b'}

> Input

`␊
1 | function a() {return'a\\\\b'}␊
`

> Output

`␊
1 | function a() {return String.raw\`a\\b\`}␊
`

> Error 1/1

`␊
> 1 | function a() {return'a\\\\b'}␊
| ^^^^^^ \`String.raw\` should be used to avoid escaping \`\\\`.␊
`

## invalid(4): const foo = "foo \\x46";

> Input

`␊
1 | const foo = "foo \\\\x46";␊
`

> Output

`␊
1 | const foo = String.raw\`foo \\x46\`;␊
`

> Error 1/1

`␊
> 1 | const foo = "foo \\\\x46";␊
| ^^^^^^^^^^^ \`String.raw\` should be used to avoid escaping \`\\\`.␊
`
Binary file added test/snapshots/prefer-string-raw.mjs.snap
Binary file not shown.