eslint-plugin-sonarjs
Version:
220 lines (219 loc) • 9.81 kB
JavaScript
;
/*
* SonarQube JavaScript Plugin
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
// https://sonarsource.github.io/rspec/#/rspec/S9078/javascript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.rule = void 0;
const ast_js_1 = require("../helpers/ast.js");
const equivalence_js_1 = require("../helpers/equivalence.js");
const generate_meta_js_1 = require("../helpers/generate-meta.js");
const location_js_1 = require("../helpers/location.js");
const mocha_style_test_frameworks_js_1 = require("../helpers/testing/mocha-style-test-frameworks.js");
const meta = __importStar(require("./generated-meta.js"));
const messages = {
duplicate: 'Remove this duplicate test case.',
};
exports.rule = {
meta: (0, generate_meta_js_1.generateMeta)(meta, { messages, fixable: 'code' }),
create(context) {
const activeFrameworks = (0, mocha_style_test_frameworks_js_1.getParameterizedTestFrameworks)(context);
if (!Object.values(activeFrameworks).some(Boolean)) {
return {};
}
return {
CallExpression(node) {
const dataset = getDataset(node);
if (dataset === undefined ||
!(0, mocha_style_test_frameworks_js_1.hasSupportedParameterizedCallback)(context, node) ||
node.arguments.length < 2 ||
!(0, mocha_style_test_frameworks_js_1.isSupportedParameterizedDeclaration)(context, node, activeFrameworks)) {
return;
}
reportDuplicateRows(context, dataset);
},
};
},
};
function reportDuplicateRows(context, dataset) {
const rowGroups = [];
dataset.elements.forEach((element, index) => {
if (element === null || element.type === 'SpreadElement') {
return;
}
const group = rowGroups.find(row => (0, equivalence_js_1.areEquivalent)(row.original, element, context.sourceCode));
if (group === undefined) {
rowGroups.push({ original: element, duplicates: [] });
return;
}
group.duplicates.push({ index, node: element });
});
const duplicateGroups = rowGroups.filter(group => group.duplicates.length > 0);
for (const { original, duplicates } of duplicateGroups) {
const [firstDuplicate] = duplicates;
if (firstDuplicate === undefined) {
continue;
}
(0, location_js_1.report)(context, {
node: firstDuplicate.node,
message: messages.duplicate,
messageId: 'duplicate',
fix: fixer => removeDuplicateRows(fixer, context.sourceCode, duplicates),
}, [
(0, location_js_1.toSecondaryLocation)(original, 'Original test case.'),
...duplicates
.slice(1)
.map(duplicate => (0, location_js_1.toSecondaryLocation)(duplicate.node, 'Additional duplicate test case.')),
]);
}
}
function removeDuplicateRows(fixer, sourceCode, duplicates) {
const fixes = [];
for (let position = 0; position < duplicates.length;) {
const firstDuplicate = duplicates[position];
let lastDuplicate = firstDuplicate;
position++;
while (duplicates[position]?.index === lastDuplicate.index + 1) {
lastDuplicate = duplicates[position];
position++;
}
fixes.push(removeDuplicateRow(fixer, sourceCode, firstDuplicate.node, lastDuplicate.node));
}
return fixes;
}
function removeDuplicateRow(fixer, sourceCode, firstElement, lastElement) {
const firstElementRange = sourceCode.getRange(firstElement);
const lastElementRange = sourceCode.getRange(lastElement);
const previousToken = sourceCode.getTokenBefore(firstElement);
const removalStart = getRemovalStart(sourceCode, firstElement, firstElementRange);
const trailingCommentEnd = getTrailingCommentEnd(sourceCode, lastElement);
if (trailingCommentEnd !== undefined) {
const trailingNewline = /^\s*(\r?\n)/.exec(sourceCode.text.slice(trailingCommentEnd));
const end = trailingNewline
? trailingCommentEnd + trailingNewline[0].length
: trailingCommentEnd;
return fixer.removeRange([removalStart, end]);
}
if (hasCommentBefore(sourceCode, firstElement, previousToken)) {
const nextToken = sourceCode.getTokenAfter(lastElement);
const end = nextToken?.value === ',' ? nextToken.range[1] : lastElementRange[1];
const trailingNewline = /^\s*(\r?\n)/.exec(sourceCode.text.slice(end));
const endWithNewline = trailingNewline ? end + trailingNewline[0].length : end;
return fixer.removeRange([removalStart, endWithNewline]);
}
const start = previousToken?.value === ',' ? previousToken.range[0] : firstElementRange[0];
return fixer.removeRange([start, lastElementRange[1]]);
}
function getRemovalStart(sourceCode, firstElement, firstElementRange) {
const standaloneLeadingCommentStart = getStandaloneLeadingCommentStart(sourceCode, firstElement);
if (standaloneLeadingCommentStart !== undefined) {
return standaloneLeadingCommentStart;
}
const lineStart = sourceCode.getIndexFromLoc({
line: sourceCode.getLoc(firstElement).start.line,
column: 0,
});
const isOnlyElementOnLine = /^\s*$/.test(sourceCode.text.slice(lineStart, firstElementRange[0]));
return isOnlyElementOnLine ? lineStart : firstElementRange[0];
}
function hasCommentBefore(sourceCode, firstElement, previousToken) {
return sourceCode.getTokenBefore(firstElement, { includeComments: true }) !== previousToken;
}
function getTrailingCommentEnd(sourceCode, lastElement) {
const nextToken = sourceCode.getTokenAfter(lastElement, { includeComments: true });
const possibleTrailingComment = nextToken?.value === ','
? sourceCode.getTokenAfter(nextToken, { includeComments: true })
: nextToken;
if (possibleTrailingComment?.type !== 'Line' && possibleTrailingComment?.type !== 'Block') {
return undefined;
}
if (possibleTrailingComment.loc?.start.line !== sourceCode.getLoc(lastElement).end.line ||
possibleTrailingComment.range === undefined) {
return undefined;
}
return possibleTrailingComment.range[1];
}
function getStandaloneLeadingCommentStart(sourceCode, firstElement) {
const [comment] = sourceCode.getCommentsBefore(firstElement).slice(-1);
const firstElementRange = sourceCode.getRange(firstElement);
if (comment === undefined) {
return undefined;
}
if (comment.range === undefined ||
comment.loc?.start.line === undefined ||
comment.loc.end.line >= sourceCode.getLoc(firstElement).start.line) {
return undefined;
}
const commentLineStart = sourceCode.getIndexFromLoc({
line: comment.loc.start.line,
column: 0,
});
const beforeComment = sourceCode.text.slice(commentLineStart, comment.range[0]);
const afterComment = sourceCode.text.slice(comment.range[1], firstElementRange[0]);
return /^\s*$/.test(beforeComment) && /^\s*$/.test(afterComment) ? commentLineStart : undefined;
}
function getDataset(node) {
if (node.callee.type !== 'CallExpression') {
return undefined;
}
const { callee, arguments: args } = node.callee;
if (callee.type !== 'MemberExpression' ||
callee.computed ||
callee.property.type !== 'Identifier' ||
callee.property.name !== 'each' ||
args.length === 0) {
return undefined;
}
const [dataset] = args;
if (dataset === undefined || dataset.type === 'SpreadElement') {
return undefined;
}
const unwrapped = (0, ast_js_1.unwrapTypeScriptExpression)(dataset);
return unwrapped.type === 'ArrayExpression' ? unwrapped : undefined;
}