Skip to content
This repository was archived by the owner on Oct 3, 2024. It is now read-only.

Commit 26d6838

Browse files
no-element-overwrite: provide secondary issue locations (#99)
1 parent 750c66c commit 26d6838

File tree

2 files changed

+35
-7
lines changed

2 files changed

+35
-7
lines changed

src/rules/no-element-overwrite.ts

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,20 @@ import {
3030
isIdentifier,
3131
isCallExpression,
3232
} from "../utils/nodes";
33+
import { report, issueLocation } from "../utils/locations";
34+
35+
const message = (index: string, line: string) =>
36+
`Verify this is the index that was intended; "${index}" was already set on line ${line}.`;
3337

3438
const rule: Rule.RuleModule = {
39+
meta: {
40+
schema: [
41+
{
42+
// internal parameter
43+
enum: ["sonar-runtime"],
44+
},
45+
],
46+
},
3547
create(context: Rule.RuleContext) {
3648
return {
3749
SwitchCase(node: estree.Node) {
@@ -61,14 +73,16 @@ const rule: Rule.RuleModule = {
6173
}
6274
const sameKeyWriteUsage = usedKeys.get(keyWriteUsage.indexOrKey);
6375
if (sameKeyWriteUsage && sameKeyWriteUsage.node.loc) {
64-
context.report({
65-
node: keyWriteUsage.node,
66-
message: 'Verify this is the index that was intended; "{{index}}" was already set on line {{line}}.',
67-
data: {
68-
index: keyWriteUsage.indexOrKey,
69-
line: String(sameKeyWriteUsage.node.loc.start.line),
76+
const sameKeyWriteUsageLoc = sameKeyWriteUsage.node.loc;
77+
const secondaryLocations = [issueLocation(sameKeyWriteUsageLoc, sameKeyWriteUsageLoc, "Original value")];
78+
report(
79+
context,
80+
{
81+
node: keyWriteUsage.node,
82+
message: message(keyWriteUsage.indexOrKey, String(sameKeyWriteUsage.node.loc.start.line)),
7083
},
71-
});
84+
secondaryLocations,
85+
);
7286
}
7387
usedKeys.set(keyWriteUsage.indexOrKey, keyWriteUsage);
7488
collection = keyWriteUsage.collectionNode;

tests/rules/no-element-overwrite.test.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,20 @@ ruleTester.run("no-element-overwrite", rule, {
105105
},
106106
],
107107
},
108+
{
109+
code: `
110+
fruits[1] = "banana";
111+
//^^^^^^^^^^^^^^^^^^^^>
112+
fruits[1] = "apple";
113+
//^^^^^^^^^^^^^^^^^^^`,
114+
options: ["sonar-runtime"],
115+
errors: [
116+
JSON.stringify({
117+
secondaryLocations: [{ line: 2, column: 6, endLine: 2, endColumn: 26, message: "Original value" }],
118+
message: `Verify this is the index that was intended; "1" was already set on line 2.`,
119+
}),
120+
],
121+
},
108122
{
109123
code: `
110124
fruits[1] = "banana";

0 commit comments

Comments
 (0)