import glob from 'glob' ; import { argv } from 'yargs' ; import { flatten , keyBy } from 'lodash' ; export type Command = { title : string ; signature : string ; description : string ; run : ( argv ? : Record < string , any > ) => Promise < void > ; } ; const commandFiles = glob . sync ( './**/*.cmd.ts' , { cwd : __dirname , realpath : true } ) ; const commandImports = commandFiles . map ( ( file ) : any => Object . values ( require ( file ) ) ) ; const commands = flatten ( commandImports ) ; const commandSignatures = keyBy ( commands , 'signature' ) ; function exitWithHelp ( exitCode = 0 ) { console . log ( ':: Available list of commands ::' ) ; Object . keys ( commandSignatures ) . map ( ( command ) => console . info ( `↳  yarn command ${ command }` ) ) ; console . log ( ) ; process . exit ( exitCode ) ; } const [ , , givenSignature ] = process . argv ; if ( ! givenSignature ) { exitWithHelp ( ) ; } if ( ! commandSignatures [ givenSignature ] ) { console . error ( `✖ Invalid command ${ givenSignature }` ) ; exitWithHelp ( 1 ) ; } const foundCommand = commandSignatures [ givenSignature ] ; console . info ( '✔ Command found' ) ; console . info ( '::::::::::::::::::::::::::::::::::::::::::' ) ; console . info ( `:: ${ foundCommand . title }` ) ; console . info ( `:: ${ foundCommand . description }` ) ; console . info ( '::::::::::::::::::::::::::::::::::::::::::' ) ; ( async ( ) : Promise < void > => { console . info ( 'Running the command' ) ; foundCommand . run ( argv ) . then ( async ( ) => { console . info ( 'Command ran successfully' ) ; } ) . catch ( async ( e ) => { console . info ( '!!! Error occurred while running the command' ) ; console . error ( `!!! ${ e . message }` ) ; console . error ( e . stack ) ; } ) ; } ) ( ) ;