/* eslint-disable no-await-in-loop */ /* eslint-disable no-console */ import path from 'path' import fs, { existsSync } from 'fs-extra' import chalk from 'chalk' import { Command } from '@oclif/command' import { runInitialStructureCompilation } from '../utils/createInitialStructure' import { salesAppCoreDir, salesAppMonorepoSrcDir, salesAppMonorepoDir, } from '../utils/directory' export default class Init extends Command { static description = 'Initialize project structure inside sales-app' public async run() { try { if (existsSync(salesAppMonorepoSrcDir)) { console.log( `${chalk.red('Error')} - Sales App project already initialized` ) return } console.log( `${chalk.blue( 'Info' )} - Initializing project structure in ${salesAppMonorepoDir}...` ) runInitialStructureCompilation() await fs.ensureDir(salesAppMonorepoDir) await this.copyDirectory( path.join(salesAppCoreDir, 'src'), salesAppMonorepoSrcDir ) console.log( `${chalk.green('Success')} - Project structure created successfully` ) } catch (error) { this.handleError(error) } } private async copyDirectory(sourceDir: string, targetDir: string) { try { const items = await fs.readdir(sourceDir, { withFileTypes: true }) for (const item of items) { const srcItemPath = path.join(sourceDir, item.name) const destItemPath = path.join(targetDir, item.name) if (item.isDirectory()) { await this.ensureDir(destItemPath) await this.copyDirectory(srcItemPath, destItemPath) } else if (item.isFile()) { await this.copyFile(srcItemPath, destItemPath) } } } catch (error) { this.handleError( error, `Error copying directory from ${sourceDir} to ${targetDir}` ) } } private async ensureDir(targetPath: string) { try { await fs.ensureDir(targetPath) console.log(`${chalk.green('Created directory')}: ${targetPath}`) } catch (error) { this.handleError(error, `Error creating directory: ${targetPath}`) } } private async copyFile(srcPath: string, destPath: string) { try { await fs.access(srcPath) await fs.copyFile(srcPath, destPath) console.log(`${chalk.green('Created file')}: ${destPath}`) } catch (error) { this.handleError(error, `Error copying file: ${srcPath}`) } } private handleError(error: unknown, message = 'An error occurred') { if (error instanceof Error) { this.error(`${chalk.red(message)}: ${error.message}`) } else { this.error(`${chalk.red(message)}: ${error}`) } } }