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

prefer-string-starts-ends-with: add suggestions for safely handling non-strings #1277

Merged
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 14 additions & 0 deletions docs/rules/prefer-string-starts-ends-with.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ Prefer [`String#startsWith()`](https://developer.mozilla.org/en/docs/Web/JavaScr

This rule is fixable.

Note: the autofixed code will throw an exception when the value being tested is not a string. Several safer but more verbose automatic suggestions are provided for this situation.
bmish marked this conversation as resolved.
Show resolved Hide resolved

## Fail

```js
Expand All @@ -24,6 +26,18 @@ const foo = baz.startsWith('bar');
const foo = baz.endsWith('bar');
```

```js
const foo = baz?.startsWith('bar');
```

```js
const foo = (baz ?? '').startsWith('bar');
```

```js
const foo = String(baz).startsWith('bar');
```

```js
const foo = /^bar/i.test(baz);
```
84 changes: 60 additions & 24 deletions rules/prefer-string-starts-ends-with.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,19 @@ const getDocumentationUrl = require('./utils/get-documentation-url');
const methodSelector = require('./utils/method-selector');
const quoteString = require('./utils/quote-string');
const shouldAddParenthesesToMemberExpressionObject = require('./utils/should-add-parentheses-to-member-expression-object');
const getParenthesizedText = require('./utils/get-parenthesized-text');

const MESSAGE_STARTS_WITH = 'prefer-starts-with';
const MESSAGE_ENDS_WITH = 'prefer-ends-with';
const SUGGEST_STRING_CAST = 'suggest-string-cast';
bmish marked this conversation as resolved.
Show resolved Hide resolved
const SUGGEST_OPTIONAL_CHAINING = 'suggest-optional-chaining';
const SUGGEST_NULLISH_COALESCING = 'suggest-nullish-coalescing';
const messages = {
[MESSAGE_STARTS_WITH]: 'Prefer `String#startsWith()` over a regex with `^`.',
[MESSAGE_ENDS_WITH]: 'Prefer `String#endsWith()` over a regex with `$`.'
[MESSAGE_ENDS_WITH]: 'Prefer `String#endsWith()` over a regex with `$`.',
[SUGGEST_STRING_CAST]: 'When testing against a value that may not be a string, use string casting.',
[SUGGEST_OPTIONAL_CHAINING]: 'When testing against a value that may not be a string, use optional chaining.',
[SUGGEST_NULLISH_COALESCING]: 'When testing against a value that may not be a string, use nullish coalescing.'
};

const doesNotContain = (string, characters) => characters.every(character => !string.includes(character));
Expand Down Expand Up @@ -64,33 +71,61 @@ const create = context => {
return;
}

context.report({
node,
messageId: result.messageId,
fix: fixer => {
const method = result.messageId === MESSAGE_STARTS_WITH ? 'startsWith' : 'endsWith';
const [target] = node.arguments;
let targetString = sourceCode.getText(target);

if (
// If regex is parenthesized, we can use it, so we don't need add again
!isParenthesized(regexNode, sourceCode) &&
(isParenthesized(target, sourceCode) || shouldAddParenthesesToMemberExpressionObject(target, sourceCode))
) {
function * fix(fixer, {useNullishCoalescing, useOptionalChaining, useStringCasting} = {}) {
const method = result.messageId === MESSAGE_STARTS_WITH ? 'startsWith' : 'endsWith';
const [target] = node.arguments;
let targetString = sourceCode.getText(target);
const isRegexParenthesized = isParenthesized(regexNode, sourceCode);
const isTargetParenthesized = isParenthesized(target, sourceCode);

if (useNullishCoalescing) {
// (target ?? '').startsWith(pattern)
targetString = targetString + ' ?? \'\'';
if (!isRegexParenthesized) {
targetString = `(${targetString})`;
}
} else if (useStringCasting) {
// String(target).startsWith(pattern)
targetString = 'String' + (isTargetParenthesized ? getParenthesizedText(target, sourceCode) : `(${targetString})`);
} else if (!isRegexParenthesized && (isTargetParenthesized || shouldAddParenthesesToMemberExpressionObject(target, sourceCode))) {
targetString = `(${targetString})`;
}

// The regex literal always starts with `/` or `(`, so we don't need check ASI
// The regex literal always starts with `/` or `(`, so we don't need check ASI

return [
// Replace regex with string
fixer.replaceText(regexNode, targetString),
// `.test` => `.startsWith` / `.endsWith`
fixer.replaceText(node.callee.property, method),
// Replace argument with result.string
fixer.replaceText(target, quoteString(result.string))
];
// Replace regex with string
yield fixer.replaceText(regexNode, targetString);

// `.test` => `.startsWith` / `.endsWith`
yield fixer.replaceText(node.callee.property, method);

// Optional chaining: target.startsWith => target?.startsWith
if (useOptionalChaining) {
yield fixer.replaceText(sourceCode.getTokenBefore(node.callee.property), '?.');
}

// Replace argument with result.string
yield fixer.replaceText(target, quoteString(result.string))
}

context.report({
node,
messageId: result.messageId,
suggest: [
{
messageId: SUGGEST_STRING_CAST,
fix: fixer => fix(fixer, {useStringCasting: true})
},
{
messageId: SUGGEST_OPTIONAL_CHAINING,
fix: fixer => fix(fixer, {useOptionalChaining: true})
},
{
messageId: SUGGEST_NULLISH_COALESCING,
fix: fixer => fix(fixer, {useNullishCoalescing: true})
}
],
fix
});
}
};
Expand All @@ -102,7 +137,8 @@ module.exports = {
type: 'suggestion',
docs: {
description: 'Prefer `String#startsWith()` & `String#endsWith()` over `RegExp#test()`.',
url: getDocumentationUrl(__filename)
url: getDocumentationUrl(__filename),
suggest: true
},
messages,
fixable: 'code',
Expand Down
20 changes: 5 additions & 15 deletions rules/prefer-ternary.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const extendFixRange = require('./utils/extend-fix-range');
const needsSemicolon = require('./utils/needs-semicolon');
const isSameReference = require('./utils/is-same-reference');
const getIndentString = require('./utils/get-indent-string');
const getParenthesizedText = require('./utils/get-parenthesized-text');

const messageId = 'prefer-ternary';

Expand Down Expand Up @@ -53,18 +54,7 @@ const create = context => {
return !generatedNames || !generatedNames.has(name);
});

const getParenthesizedText = node => {
const text = sourceCode.getText(node);
return (
isParenthesized(node, sourceCode) ||
node.type === 'AwaitExpression' ||
// Lower precedence, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table
node.type === 'AssignmentExpression' ||
node.type === 'YieldExpression' ||
node.type === 'SequenceExpression'
) ?
`(${text})` : text;
};


const isSingleLineNode = node => {
const [start, end] = node.range.map(index => sourceCode.getLocFromIndex(index));
Expand Down Expand Up @@ -206,13 +196,13 @@ const create = context => {
node,
messageId,
* fix(fixer) {
const testText = getParenthesizedText(node.test);
const testText = getParenthesizedText(node.test, sourceCode);
const consequentText = typeof result.consequent === 'string' ?
result.consequent :
getParenthesizedText(result.consequent);
getParenthesizedText(result.consequent, sourceCode);
const alternateText = typeof result.alternate === 'string' ?
result.alternate :
getParenthesizedText(result.alternate);
getParenthesizedText(result.alternate, sourceCode);

let {type, before, after} = result;

Expand Down
16 changes: 16 additions & 0 deletions rules/utils/get-parenthesized-text.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const {isParenthesized} = require('eslint-utils');

function getParenthesizedText (node, sourceCode) {
const text = sourceCode.getText(node);
return (
isParenthesized(node, sourceCode) ||
node.type === 'AwaitExpression' ||
// Lower precedence, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table
node.type === 'AssignmentExpression' ||
node.type === 'YieldExpression' ||
node.type === 'SequenceExpression'
) ?
`(${text})` : text;
};

module.exports = getParenthesizedText;
150 changes: 144 additions & 6 deletions test/prefer-string-starts-ends-with.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ const {test} = getTester(import.meta);

const MESSAGE_STARTS_WITH = 'prefer-starts-with';
const MESSAGE_ENDS_WITH = 'prefer-ends-with';
const SUGGEST_STRING_CAST = 'suggest-string-cast';
const SUGGEST_OPTIONAL_CHAINING = 'suggest-optional-chaining';
const SUGGEST_NULLISH_COALESCING = 'suggest-nullish-coalescing';

const validRegex = [
/foo/,
Expand Down Expand Up @@ -70,29 +73,109 @@ test({
return {
code: `${re}.test(bar)`,
output: `bar.${method}('${string}')`,
errors: [{messageId}]
errors: [{
messageId,
suggestions: [
{
messageId: SUGGEST_STRING_CAST,
output: `String(bar).${method}('${string}')`
},
{
messageId: SUGGEST_OPTIONAL_CHAINING,
output: `bar?.${method}('${string}')`
},
{
messageId: SUGGEST_NULLISH_COALESCING,
output: `(bar ?? '').${method}('${string}')`
}
]
}]
};
}),
// Parenthesized
{
code: '/^b/.test(("a"))',
output: '("a").startsWith((\'b\'))',
errors: [{messageId: MESSAGE_STARTS_WITH}]
errors: [{
messageId: MESSAGE_STARTS_WITH,
suggestions: [
{
messageId: SUGGEST_STRING_CAST,
output: 'String("a").startsWith((\'b\'))'
},
{
messageId: SUGGEST_OPTIONAL_CHAINING,
output: '("a")?.startsWith((\'b\'))'
},
{
messageId: SUGGEST_NULLISH_COALESCING,
output: '("a" ?? \'\').startsWith((\'b\'))'
}
]
}]
},
{
code: '(/^b/).test(("a"))',
output: '("a").startsWith((\'b\'))',
errors: [{messageId: MESSAGE_STARTS_WITH}]
errors: [{
messageId: MESSAGE_STARTS_WITH,
suggestions: [
{
messageId: SUGGEST_STRING_CAST,
output: '(String("a")).startsWith((\'b\'))'
},
{
messageId: SUGGEST_OPTIONAL_CHAINING,
output: '("a")?.startsWith((\'b\'))'
},
{
messageId: SUGGEST_NULLISH_COALESCING,
output: '("a" ?? \'\').startsWith((\'b\'))'
}
]
}]
},
{
code: 'const fn = async () => /^b/.test(await foo)',
output: 'const fn = async () => (await foo).startsWith(\'b\')',
errors: [{messageId: MESSAGE_STARTS_WITH}]
errors: [{
messageId: MESSAGE_STARTS_WITH,
suggestions: [
{
messageId: SUGGEST_STRING_CAST,
output: 'const fn = async () => String(await foo).startsWith(\'b\')'
},
{
messageId: SUGGEST_OPTIONAL_CHAINING,
output: 'const fn = async () => (await foo)?.startsWith(\'b\')'
},
{
messageId: SUGGEST_NULLISH_COALESCING,
output: 'const fn = async () => (await foo ?? \'\').startsWith(\'b\')'
}
]
}]
},
{
code: 'const fn = async () => (/^b/).test(await foo)',
output: 'const fn = async () => (await foo).startsWith(\'b\')',
errors: [{messageId: MESSAGE_STARTS_WITH}]
errors: [{
messageId: MESSAGE_STARTS_WITH,
suggestions: [
{
messageId: SUGGEST_STRING_CAST,
output: 'const fn = async () => (String(await foo)).startsWith(\'b\')'
},
{
messageId: SUGGEST_OPTIONAL_CHAINING,
output: 'const fn = async () => (await foo)?.startsWith(\'b\')'
},
{
messageId: SUGGEST_NULLISH_COALESCING,
output: 'const fn = async () => (await foo ?? \'\').startsWith(\'b\')'
}
]
}]
},
// Comments
{
Expand Down Expand Up @@ -124,7 +207,62 @@ test({
)
) {}
`,
errors: [{messageId: MESSAGE_STARTS_WITH}]
errors: [{
messageId: MESSAGE_STARTS_WITH,
suggestions: [
{
messageId: SUGGEST_STRING_CAST,
output: outdent`
if (
/* comment 1 */
String(foo)
/* comment 2 */
.startsWith
/* comment 3 */
(
/* comment 4 */
'b'
/* comment 5 */
)
) {}
`
},
{
messageId: SUGGEST_OPTIONAL_CHAINING,
output: outdent`
if (
/* comment 1 */
foo
/* comment 2 */
?.startsWith
/* comment 3 */
(
/* comment 4 */
'b'
/* comment 5 */
)
) {}
`
},
{
messageId: SUGGEST_NULLISH_COALESCING,
output: outdent`
if (
/* comment 1 */
(foo ?? '')
/* comment 2 */
.startsWith
/* comment 3 */
(
/* comment 4 */
'b'
/* comment 5 */
)
) {}
`
}
]
}]
}
]
});
Expand Down