diff --git a/lib/rules/padded-blocks.js b/lib/rules/padded-blocks.js index 094ba0a715a..27657360e99 100644 --- a/lib/rules/padded-blocks.js +++ b/lib/rules/padded-blocks.js @@ -188,6 +188,9 @@ module.exports = { node, loc: { line: openBrace.loc.start.line, column: openBrace.loc.start.column }, fix(fixer) { + + // FIXME: The start of this range is sometimes larger than the end. + // https://github.com/eslint/eslint/issues/8116 return fixer.replaceTextRange([openBrace.end, nextToken.start - nextToken.loc.start.column], "\n"); }, message: NEVER_MESSAGE diff --git a/lib/util/source-code-fixer.js b/lib/util/source-code-fixer.js index 8b8936204c4..ab42e952924 100644 --- a/lib/util/source-code-fixer.js +++ b/lib/util/source-code-fixer.js @@ -108,7 +108,13 @@ SourceCodeFixer.applyFixes = function(sourceCode, messages) { // Make output to this fix. output += text.slice(Math.max(0, lastPos), Math.max(0, start)); output += fix.text; - lastPos = end; + + /* + * If the start of the range is larger than the end for some reason, make sure + * the text between the end and the start doesn't get duplicated. + * https://github.com/eslint/eslint/issues/8116 + */ + lastPos = Math.max(start, end); } output += text.slice(Math.max(0, lastPos)); diff --git a/tests/lib/rules/padded-blocks.js b/tests/lib/rules/padded-blocks.js index e38c7109c17..561ec3afac6 100644 --- a/tests/lib/rules/padded-blocks.js +++ b/tests/lib/rules/padded-blocks.js @@ -463,6 +463,12 @@ ruleTester.run("padded-blocks", rule, { line: 9 } ] + }, + { + code: "function foo() { // a\n\n b;\n}", + output: "function foo() {\n // a\n\n b;\n}", + options: ["never"], + errors: [NEVER_MESSAGE] } ] }); diff --git a/tests/lib/util/source-code-fixer.js b/tests/lib/util/source-code-fixer.js index dad6ece64ee..cb599c7b2cd 100644 --- a/tests/lib/util/source-code-fixer.js +++ b/tests/lib/util/source-code-fixer.js @@ -122,6 +122,13 @@ const INSERT_AT_END = { message: "nofix2", line: 1, column: 7 + }, + REVERSED_RANGE = { + message: "reversed range", + fix: { + range: [3, 0], + text: " " + } }; //------------------------------------------------------------------------------ @@ -407,6 +414,12 @@ describe("SourceCodeFixer", () => { assert.equal(result.messages.length, 0); }); + it("should handle reversed ranges gracefully", () => { + const result = SourceCodeFixer.applyFixes(sourceCode, [REVERSED_RANGE]); + + assert.equal(result.output, "\uFEFFvar answer = 6 * 7;"); + }); + }); describe("Text Replacement", () => {