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 all 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 assertValidFix(fix) {
if (fix) {
assert(fix.range && typeof fix.range[0] === "number" && typeof fix.range[1] === "number", `Fix has invalid range: ${JSON.stringify(fix, null, 2)}`);
}
}

/**
* 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) {
assertValidFix(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);
}

assertValidFix(fix);
return fix;
}

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

it("should throw an error if fix range is invalid", () => {
assert.throws(
() => translateReport({ node, messageId: "testMessage", fix: () => ({ text: "foo" }) }),
"Fix has invalid range"
);

for (const badRange of [[0], [0, null], [null, 0], [void 0, 1], [0, void 0], [void 0, void 0], []]) {
assert.throws(
// eslint-disable-next-line no-loop-func
() => translateReport(
{ node, messageId: "testMessage", fix: () => ({ range: badRange, text: "foo" }) }
),
"Fix has invalid range"
);

assert.throws(
// eslint-disable-next-line no-loop-func
() => translateReport(
{
node,
messageId: "testMessage",
fix: () => [
{ range: [0, 0], text: "foo" },
{ range: badRange, text: "bar" },
{ range: [1, 1], text: "baz" }
]
}
),
"Fix has invalid range"
);
}
});
jtbandes marked this conversation as resolved.
Show resolved Hide resolved
});
});