const path = require('path'); const fs = require('fs'); const util = require('util'); import i18n from '../utils/i18n'; const exec = util.promisify(require('child_process').exec); import { PluginExeCute } from '../plugin'; import * as logger from '../utils/logger'; export interface HookConfig { Pre: boolean; Plugin?: string; Hook?: string; Path?: string; } export class Hook { preHooks: Array = []; afterHooks: Array = []; constructor(extendsParams: Array = []) { extendsParams.forEach((_extend: HookConfig) => { if (_extend.Pre) { this.preHooks.push(_extend); } else { this.afterHooks.push(_extend); } }); } async executePreHook() { if (this.preHooks.length > 0) { logger.info(i18n.__('Start the pre-hook')); const prePromises = this.preHooks.map(async (hookConfig: HookConfig) => await this.executeByConfig(hookConfig)); await Promise.all(prePromises); logger.info(i18n.__('End the pre-hook')); } } async executeAfterHook() { if (this.afterHooks.length > 0) { logger.info(i18n.__('Start the after-hook')); const afterPromises = this.afterHooks.map( async (hookConfig: HookConfig) => await this.executeByConfig(hookConfig) ); await Promise.all(afterPromises); logger.info(i18n.__('End the after-hook')); } } async commandExecute(command: string, executePath: string | undefined) { const currentDir = process.cwd(); const cwdPath = executePath ? path.resolve(currentDir, executePath) : currentDir; if (fs.existsSync(cwdPath) && fs.lstatSync(cwdPath).isDirectory()) { const { stdout, stderr } = await exec(command, { cwd: cwdPath }); if (stderr) { logger.error(i18n.__('Execute:'), stderr); } else { logger.info(i18n.__('Execute:'), stdout); } } } async pluginExecute(name: string) { const pluginInstance = new PluginExeCute({ name }); await pluginInstance.init(); const pluginModule = await pluginInstance.loadPlugin(); pluginModule.apply(null, []); } async executeByConfig(hookConfig: HookConfig) { if (hookConfig.Hook) { await this.commandExecute(hookConfig.Hook, hookConfig.Path); } else if (hookConfig.Plugin) { await this.pluginExecute(hookConfig.Plugin); } } }