import type { TSESTree , TSESLint } from '@typescript-eslint/experimental-utils' ; import { isIfStatement , isBlockStatement } from '../utils/nodes' ; import { report , issueLocation } from '../utils/locations' ; import docsUrl from '../utils/docs-url' ; const message = 'Merge this if statement with the nested one.' ; const rule = { meta : { messages : { mergeNestedIfStatement : message , sonarRuntime : '{{sonarRuntimeData}}' , } , type : 'suggestion' , docs : { description : 'Collapsible "if" statements should be merged' , recommended : 'error' , url : docsUrl ( __filename ) , } , schema : [ { enum : [ 'sonar-runtime' ] , } , ] , } , create ( context ) { return { IfStatement ( node ) { let { consequent } = node as TSESTree . IfStatement ; if ( isBlockStatement ( consequent ) && consequent . body . length === 1 ) { consequent = consequent . body [ 0 ] ; } if ( isIfStatementWithoutElse ( node ) && isIfStatementWithoutElse ( consequent ) ) { const ifKeyword = context . getSourceCode ( ) . getFirstToken ( consequent ) ; const enclosingIfKeyword = context . getSourceCode ( ) . getFirstToken ( node ) ; if ( ifKeyword && enclosingIfKeyword ) { report ( context , { messageId : 'mergeNestedIfStatement' , loc : enclosingIfKeyword . loc , } , [ issueLocation ( ifKeyword . loc , ifKeyword . loc , 'Nested "if" statement.' ) ] , message ) ; } } } , } ; function isIfStatementWithoutElse ( node ) { return isIfStatement ( node ) && ! node . alternate ; } } , } ; export = rule ;