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

Update: throw error when fix range is invalid #14142

Merged
merged 7 commits into from Mar 11, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
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
17 changes: 17 additions & 0 deletions lib/linter/report-translator.js
Expand Up @@ -115,6 +115,17 @@ function normalizeReportLoc(descriptor) {
return descriptor.node.loc;
}

/**
* Check that a fix has a valid range.
* @param {Fix|null} fix The fix to validate.
* @returns {void}
*/
function validateFix(fix) {
jtbandes marked this conversation as resolved.
Show resolved Hide resolved
if (fix) {
assert(typeof fix.range[0] === "number" && typeof fix.range[1] === "number", `Fix has invalid range: ${fix.range}`);
jtbandes marked this conversation as resolved.
Show resolved Hide resolved
}
}

/**
* Compares items in a fixes array by range.
* @param {Fix} a The first message.
Expand All @@ -133,6 +144,10 @@ function compareFixesByRange(a, b) {
* @returns {{text: string, range: number[]}} The merged fixes
*/
function mergeFixes(fixes, sourceCode) {
for (const fix of fixes) {
validateFix(fix);
}

if (fixes.length === 0) {
return null;
}
Expand Down Expand Up @@ -181,6 +196,8 @@ function normalizeFixes(descriptor, sourceCode) {
if (fix && Symbol.iterator in fix) {
return mergeFixes(Array.from(fix), sourceCode);
}

validateFix(fix);
return fix;
}

Expand Down
16 changes: 16 additions & 0 deletions tests/lib/linter/report-translator.js
Expand Up @@ -1028,5 +1028,21 @@ describe("createReportTranslator", () => {
"Node must be provided when reporting error if location is not provided"
);
});

it("should throw an error if fix range is invalid", () => {
for (const badRange of [[0], [0, null], [null, 0], []]) {
jtbandes marked this conversation as resolved.
Show resolved Hide resolved
assert.throws(
// eslint-disable-next-line no-loop-func
() => translateReport(
{
node,
messageId: "testMessage",
fix: () => ({ range: badRange, text: "foo" })
}
),
"Fix has invalid range"
);
}
});
jtbandes marked this conversation as resolved.
Show resolved Hide resolved
});
});