All files / src/class hook.ts

90.91% Statements 20/22
75% Branches 3/4
100% Functions 6/6
90% Lines 18/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 5215x 15x 15x       15x       15x                   16x   16x 8x 5x   5x 5x   5x 5x         8x 8x 2x 2x               16x          
import childProcess from 'child_process'
import { promisify } from 'util'
import { logger } from '@/utils'
import { EventEmitter } from 'events'
 
 
const exec = promisify(childProcess.exec)
 
export type Listener = (...arg: any[]) => void
 
export class Hook {
  public eventName: string
 
  public listener: Listener
 
  /*
   * constructor(eventName: string, listener: string)
   * constructor(eventName: string, listener: Listener)
   */
  constructor(eventName: string, listener: Listener | string) {
    this.eventName = eventName
 
    if (typeof listener === 'string') {
      this.listener = async() => {
        logger.info(`run ${eventName} hook...`)
 
        try {
          const { stdout, stderr } = await exec(listener)
 
          process.stdout.write(stdout)
          process.stderr.write(stderr)
        } catch (error) {
          logger.error('hook exec error', error)
        }
      }
    } else Eif (typeof listener === 'function') {
      this.listener = async(...arg) => {
        logger.info(`run ${eventName} hook...`)
        await listener(...arg)
      }
    } else {
      throw new Error('Hook should be a string or function')
    }
  }
 
  public appendTo(eventEmitter: EventEmitter): void {
    eventEmitter.addListener(this.eventName, this.listener)
  }
}
 
export type Hooks = Hook[]