Skip to content

Commit

Permalink
Fix issue with no-semi style
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker committed Dec 14, 2020
1 parent 1d85f4f commit d9a5d71
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 1 deletion.
14 changes: 13 additions & 1 deletion rules/no-lonely-if.js
Expand Up @@ -52,7 +52,19 @@ const create = context => {
yield fixer.replaceText(outer.test, `${getTestNodeText(outer.test)} && ${getTestNodeText(inner.test)}`);

// Replace `consequent`
yield fixer.replaceText(outer.consequent, getText(inner.consequent));
const {consequent} = inner;
let consequentText = getText(consequent);
// If the `if` statement has no block, and is not followed by a semicolon,
// make sure that fixing the issue would not change semantics due to ASI.
// Similar logic https://github.com/eslint/eslint/blob/2124e1b5dad30a905dc26bde9da472bf622d3f50/lib/rules/no-lonely-if.js#L61-L77
if (consequent.type !== 'BlockStatement' && !consequentText.endsWith(';')) {
const nextToken = sourceCode.getTokenAfter(outer);
if (/^[([/+`-]/u.test(nextToken.value)) {
consequentText += ';';
}
}

yield fixer.replaceText(outer.consequent, consequentText);
}
});
}
Expand Down
12 changes: 12 additions & 0 deletions test/no-lonely-if.js
Expand Up @@ -111,5 +111,17 @@ test.visualize([
}
/* will remove */
}
`,
// Semicolon
outdent`
if (a) {
if (b) foo()
}
[].forEach(bar)
`,
outdent`
if (a)
if (b) foo()
;[].forEach(bar)
`
]);
46 changes: 46 additions & 0 deletions test/snapshots/no-lonely-if.js.md
Expand Up @@ -429,3 +429,49 @@ Generated by [AVA](https://avajs.dev).
17 | /* will remove */␊
18 | }␊
`

## no-lonely-if - #11

> Snapshot 1
`␊
Input:␊
1 | if (a) {␊
2 | if (b) foo()␊
3 | }␊
4 | [].forEach(bar)␊
Output:␊
1 | if (a && b) foo();␊
2 | [].forEach(bar)␊
Error 1/1:␊
1 | if (a) {␊
> 2 | if (b) foo()␊
| ^^^^^^^^^^^^ Unexpected `if` as the only statement in a `if` block without `else`.␊
3 | }␊
4 | [].forEach(bar)␊
`

## no-lonely-if - #12

> Snapshot 1
`␊
Input:␊
1 | if (a)␊
2 | if (b) foo()␊
3 | ;[].forEach(bar)␊
Output:␊
1 | if (a && b)␊
2 | foo()␊
3 | ;[].forEach(bar)␊
Error 1/1:␊
1 | if (a)␊
> 2 | if (b) foo()␊
| ^^^^^^^^^^^^␊
> 3 | ;[].forEach(bar)␊
| ^^ Unexpected `if` as the only statement in a `if` block without `else`.␊
`
Binary file modified test/snapshots/no-lonely-if.js.snap
Binary file not shown.

0 comments on commit d9a5d71

Please sign in to comment.