import * as vscode from 'vscode' ; import { mkdirSync , readFileSync , writeFileSync , renameSync } from 'fs' ; import { Context , Option } from './types' ; import { getOptions } from './options' ; import { stringRegex , importRegex , firstEmptyLineRegex } from './regex' ; import { formatIndexFile , formatImportPath , formatCssImport } from './format' ; const createEmptyFolder = ( c ) => { mkdirSync ( c . folderPath ) ; } ; const moveFileIntoFolder = ( c ) => { renameSync ( c . path , c . newPath ) ; } ; const createIndexFile = ( c , o ) => { const indexPath = c . folderPath + '/index.' + c . filePath ; const indexText = formatIndexFile ( c . fileName ) ; writeFileSync ( indexPath , indexText ) ; } ; const updateLocalImports = ( c , o ) => { const text = readFileSync ( c . newPath , 'utf-8' ) ; let updatedText = text . replace ( importRegex , ( match ) => { const newPath = match . replace ( stringRegex , formatImportPath ) ; return newPath ; } ) ; const importCss = o . some ( option => option . id === 'css_module' ) ; if ( importCss ) { updatedText = updatedText . replace ( firstEmptyLineRegex , ( ) => { return formatCssImport ( c . fileName ) ; } ) ; } writeFileSync ( c . newPath , updatedText ) ; } ; const createOptionalFiles = ( c , o ) => { o . forEach ( ( option ) => { if ( option . createFile ) { const name = option . createFile ; const path = c . folderPath + '/' + name ; writeFileSync ( path , '' ) ; } } ) ; } ; const createFolder = ( context , options ) => { createEmptyFolder ( context ) ; createIndexFile ( context , options ) ; createOptionalFiles ( context , options ) ; moveFileIntoFolder ( context ) ; updateLocalImports ( context , options ) ; } ; const showOptions = ( context ) => { return vscode . window . showQuickPick ( getOptions ( context ) , { placeHolder : 'generate additional files' , canPickMany : true , ignoreFocusOut : false } ) ; } ; export const init = ( event ) => { const path = event . fsPath ; const filePath = path . split ( '.' ) . pop ( ) || '' ; const folderPath = path . split ( '.' ) . slice ( 0 , - 1 ) . join ( '.' ) ; const fileName = folderPath . split ( '/' ) . pop ( ) || '' ; const newPath = folderPath + '/' + fileName + '.' + filePath ; const context = { path , filePath , folderPath , fileName , newPath } ; showOptions ( context ) . then ( ( selectedOptions ) => { if ( selectedOptions ) { createFolder ( context , selectedOptions ) ; } } ) ; } ;