UNPKG

3.29 kBJavaScriptView Raw
1"use strict";
2/*
3 * eslint-plugin-sonarjs
4 * Copyright (C) 2018-2021 SonarSource SA
5 * mailto:info AT sonarsource DOT com
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 3 of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with this program; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 */
21// https://sonarsource.github.io/rspec/#/rspec/S3923
22const nodes_1 = require("../utils/nodes");
23const equivalence_1 = require("../utils/equivalence");
24const conditions_1 = require("../utils/conditions");
25const docs_url_1 = require("../utils/docs-url");
26const MESSAGE = "Remove this conditional structure or edit its code blocks so that they're not all the same.";
27const MESSAGE_CONDITIONAL_EXPRESSION = 'This conditional operation returns the same value whether the condition is "true" or "false".';
28const rule = {
29 meta: {
30 type: 'problem',
31 docs: {
32 description: 'All branches in a conditional structure should not have exactly the same implementation',
33 category: 'Possible Errors',
34 recommended: 'error',
35 url: docs_url_1.default(__filename),
36 },
37 },
38 create(context) {
39 return {
40 IfStatement(node) {
41 const ifStmt = node;
42 // don't visit `else if` statements
43 if (!nodes_1.isIfStatement(node.parent)) {
44 const { branches, endsWithElse } = conditions_1.collectIfBranches(ifStmt);
45 if (endsWithElse && allDuplicated(branches)) {
46 context.report({ message: MESSAGE, node: ifStmt });
47 }
48 }
49 },
50 SwitchStatement(node) {
51 const switchStmt = node;
52 const { branches, endsWithDefault } = conditions_1.collectSwitchBranches(switchStmt);
53 if (endsWithDefault && allDuplicated(branches)) {
54 context.report({ message: MESSAGE, node: switchStmt });
55 }
56 },
57 ConditionalExpression(node) {
58 const conditional = node;
59 const branches = [conditional.consequent, conditional.alternate];
60 if (allDuplicated(branches)) {
61 context.report({ message: MESSAGE_CONDITIONAL_EXPRESSION, node: conditional });
62 }
63 },
64 };
65 function allDuplicated(branches) {
66 return (branches.length > 1 &&
67 branches.slice(1).every((branch, index) => {
68 return equivalence_1.areEquivalent(branch, branches[index], context.getSourceCode());
69 }));
70 }
71 },
72};
73module.exports = rule;
74//# sourceMappingURL=no-all-duplicated-branches.js.map
\No newline at end of file