Skip to content

Commit

Permalink
Fix: no-multiple-empty-lines crash on space after last \n (fixes #8401)…
Browse files Browse the repository at this point in the history
… (#8402)

* Fix: no-multiple-empty-lines crash on space after last \n (fixes #8401)

Previously, no-multiple-empty-lines would crash if it tried to remove a trailing newline followed by a space from the end of a file. This commit fixes the crash.

* Fix code duplication
  • Loading branch information
not-an-aardvark authored and gyandeeps committed Apr 4, 2017
1 parent e395919 commit 936af66
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
17 changes: 13 additions & 4 deletions lib/rules/no-multiple-empty-lines.js
Expand Up @@ -111,10 +111,19 @@ module.exports = {
message,
data: { max: maxAllowed, pluralizedLines: maxAllowed === 1 ? "line" : "lines" },
fix(fixer) {
return fixer.removeRange([
sourceCode.getIndexFromLoc({ line: lastLineNumber + 1, column: 0 }),
sourceCode.getIndexFromLoc({ line: lineNumber - maxAllowed, column: 0 })
]);
const rangeStart = sourceCode.getIndexFromLoc({ line: lastLineNumber + 1, column: 0 });

/*
* The end of the removal range is usually the start index of the next line.
* However, at the end of the file there is no next line, so the end of the
* range is just the length of the text.
*/
const lineNumberAfterRemovedLines = lineNumber - maxAllowed;
const rangeEnd = lineNumberAfterRemovedLines <= allLines.length
? sourceCode.getIndexFromLoc({ line: lineNumberAfterRemovedLines, column: 0 })
: sourceCode.text.length;

return fixer.removeRange([rangeStart, rangeEnd]);
}
});
}
Expand Down
8 changes: 8 additions & 0 deletions tests/lib/rules/no-multiple-empty-lines.js
Expand Up @@ -316,6 +316,14 @@ ruleTester.run("no-multiple-empty-lines", rule, {
code: `a\n\n\n\n${"a".repeat(1e5)}`,
output: `a\n\n\n${"a".repeat(1e5)}`,
errors: [getExpectedError(2)]
},
{

// https://github.com/eslint/eslint/issues/8401
code: "foo\n ",
output: "foo\n",
options: [{ max: 1, maxEOF: 0 }],
errors: [getExpectedErrorEOF(0)]
}
]
});

0 comments on commit 936af66

Please sign in to comment.