import { Command } from "@enzsft/cli" ; import chalk from "chalk" ; import { exec } from "child_process" ; import { EOL } from "os" ; import { applyRandomColor } from "../colors" ; import { createConsoleLogger } from "../logger" ; import { includeOption } from "../options/include" ; import { filterPackages } from "../packages" ; import { MonoRepo , Package , RunCommandOptions } from "../types" ; param { Object [ ] } packages param { Object } monoRepo returns { Object } export const createRunCommand = ( packages , monoRepo ) : Command < RunCommandOptions > => { return { description : "Run NPM scripts." , handler : async ( values , options ) : Promise < void > => { const logger = createConsoleLogger ( ) ; if ( ! monoRepo ) { logger . warn ( "Unable to locate your mono repo 😰" ) ; return ; } const [ script , ... forwardedArgs ] = values ; const targetPackages = filterPackages ( packages , options . include ) . filter ( p => p . scripts && Object . keys ( p . scripts ) . includes ( script ) ) ; if ( targetPackages . length === 0 ) { logger . warn ( "No packages found 😰" ) ; return ; } logger . log ( `${ chalk . greenBright ( "Target packages:" ) }${ EOL }${ chalk . cyanBright ( targetPackages . map ( p => p . name ) . join ( EOL ) ) }` ) ; const executors = targetPackages . map ( p => async ( ) : Promise < void > => { const runner = exec ( `yarn run ${ script } ${ forwardedArgs . join ( " " ) }` , { cwd : p . __dir } ) ; const packageLoger = createConsoleLogger ( { prefix : applyRandomColor ( `[${ p . name }]: ` ) } ) ; runner . stdout . on ( "data" , data => { packageLoger . log ( data . toString ( ) ) ; } ) ; runner . stderr . on ( "data" , data => { packageLoger . error ( data . toString ( ) ) ; } ) ; return new Promise ( ( resolve , reject ) : void => { runner . on ( "close" , code => { if ( code !== 0 ) { logger . error ( `Script ${ chalk . greenBright ( script ) } in package ${ chalk . cyanBright ( p . name ) } exited with code ${ code } 🤕` ) ; return reject ( { code } ) ; } logger . log ( `Script ${ chalk . greenBright ( script ) } in package ${ chalk . cyanBright ( p . name ) } is done 🎉` ) ; return resolve ( ) ; } ) ; } ) ; } ) ; for ( const executor of executors ) { await executor ( ) ; } logger . log ( "All done ✌️" ) ; } , name : "run" , options : [ includeOption ] } ; } ;