import type { TSESTree , TSESLint } from '@typescript-eslint/experimental-utils' ; import { isIfStatement } from '../utils/nodes' ; import { areEquivalent } from '../utils/equivalence' ; import { report , issueLocation } from '../utils/locations' ; import docsUrl from '../utils/docs-url' ; const message = 'This branch duplicates the one on line {{line}}' ; const rule = { meta : { messages : { duplicatedBranch : message , sonarRuntime : '{{sonarRuntimeData}}' , } , type : 'problem' , docs : { description : 'Related "if/else if" statements should not have the same condition' , recommended : 'error' , url : docsUrl ( __filename ) , } , schema : [ { enum : [ 'sonar-runtime' ] , } , ] , } , create ( context ) { return { IfStatement ( node ) { const ifStmt = node as TSESTree . IfStatement ; const condition = ifStmt . test ; let statement = ifStmt . alternate ; while ( statement ) { if ( isIfStatement ( statement ) ) { if ( areEquivalent ( condition , statement . test , context . getSourceCode ( ) ) ) { const line = ifStmt . loc && ifStmt . loc . start . line ; if ( line && condition . loc ) { report ( context , { messageId : 'duplicatedBranch' , data : { line , } , node : statement . test , } , [ issueLocation ( condition . loc , condition . loc , 'Original' ) ] , message ) ; } } statement = statement . alternate ; } else { break ; } } } , } ; } , } ; export = rule ;