import { CodeBlock , insertContentsAtOffset } from '../utils/commonCodeMod' ; import { findMatchingBracketPosition } from '../utils/matchBrackets' ; param contents param classDeclaration param language returns export function findNewInstanceCodeBlock ( contents , classDeclaration , language ) { const isJava = language === 'java' ; let start = isJava ? contents . indexOf ( ` new ${ classDeclaration }(` ) : contents . search ( new RegExp ( ` (object\\s*:\\s*)?${ classDeclaration }\\(` ) ) ; if ( start < 0 ) { return null ; } start += 1 ; let end = findMatchingBracketPosition ( contents , '(' , start ) ; const nextBrace = contents . indexOf ( '{' , end + 1 ) ; const isAnonymousClass = nextBrace >= end && ! ! contents . substring ( end + 1 , nextBrace ) . match ( /^\s*$/m ) ; if ( isAnonymousClass ) { end = findMatchingBracketPosition ( contents , '{' , end ) ; } return { start , end , code : contents . substring ( start , end + 1 ) } ; } param srcContents param declaration param insertion returns export function appendContentsInsideDeclarationBlock ( srcContents , declaration , insertion ) { const start = srcContents . search ( new RegExp ( `\\s*${ declaration }.*?[\\(\\{]` ) ) ; if ( start < 0 ) { throw new Error ( `Unable to find code block - declaration[${ declaration }]` ) ; } const end = findMatchingBracketPosition ( srcContents , '{' , start ) ; return insertContentsAtOffset ( srcContents , insertion , end ) ; } export function addImports ( source , imports , isJava ) { const lines = source . split ( '\n' ) ; const lineIndexWithPackageDeclaration = lines . findIndex ( line => line . match ( /^package .*;?$/ ) ) ; for ( const javaImport of imports ) { if ( ! source . includes ( javaImport ) ) { const importStatement = `import ${ javaImport }${ isJava ? ';' : '' }` ; lines . splice ( lineIndexWithPackageDeclaration + 1 , 0 , importStatement ) ; } } return lines . join ( '\n' ) ; }