import { Replacement } from "tslint" ; import { isImportDeclaration , isNamedImports } from "tsutils/typeguard/2.8" ; import * as ts from "typescript" ; export function addImportToFile ( file , imports , packageName ) { const packageToModify = file . statements . find ( statement => isImportDeclaration ( statement ) && statement . moduleSpecifier . getText ( ) === `"${ packageName }"` ) as ts . ImportDeclaration ; if ( packageToModify && packageToModify . importClause && packageToModify . importClause . namedBindings && isNamedImports ( packageToModify . importClause . namedBindings ) ) { const existingImports = packageToModify . importClause . namedBindings . elements . map ( el => el . name . getText ( ) ) ; const newImports = Array . from ( new Set ( existingImports . concat ( imports ) ) ) . sort ( ) ; const importString = `{ ${ newImports . join ( ", " ) } }` ; return Replacement . replaceNode ( packageToModify . importClause . namedBindings , importString ) ; } else { const allImports = file . statements . filter ( isImportDeclaration ) ; const newImportIndex = allImports . findIndex ( imp => { return compare ( imp . moduleSpecifier . getText ( ) . slice ( 1 , - 1 ) , packageName ) === 1 ; } ) ; const startIndex = newImportIndex === - 1 ? 0 : allImports [ newImportIndex ] . getStart ( ) ; return Replacement . appendText ( startIndex , `import { ${ imports . sort ( ) . join ( ", " ) } } from "${ packageName }";\n` ) ; } } function isLow ( value ) { return value [ 0 ] === "." || value [ 0 ] === "/" ; } function compare ( a , b ) { if ( isLow ( a ) && ! isLow ( b ) ) { return 1 ; } else if ( ! isLow ( a ) && isLow ( b ) ) { return - 1 ; } else if ( a > b ) { return 1 ; } else if ( a < b ) { return - 1 ; } return 0 ; }