// -------------- // elxr // A cli tool for elixr. // PB : TODO -- // runas bypass non elevated tasks when we request privelege // runas message is always error needs to be fixed. // runas wait needs to be parallelized. // suppress elevation check error messages // support runas lauched directly from shell. // pass in environment in hta to shellexecute. const { existsSync } = require('fs'); const fs = require('fs') const { spawn, spawnSync } = require('child_process'); const cliargs = require('../elxr/cliargs'); // Use minimist... const processedArgs = cliargs(process.argv.slice(2)); console.dir(processedArgs) var globSync = require('glob').sync; var path = require('path'); const { isMaster } = require('cluster'); // Serialize a set of functions that will execute to return a promises one after the other. // Will stop when any one fails unless continueOnFailure is true. // All tasks in iterables can be functions or promises. // promises as usual can return other promises or resolve to either truthy or falsy values. // functions must return a promise function any(iterable, continueOnFailure) { return iterable.reduce( (p, fn, i ,a) => { // console.log('accumulator :'); // console.log(p); if(Promise.resolve(p) === p ) { return p.then((pVal) => { // Falsy values are task failure. if(!pVal) { console.warn('Possible failure for result : ' + pVal) console.warn(a[i-1]) fn ? console.error("Fn : " + fn.toString()) : null; } // Truthy values are failures if obj has error=true. if(pVal && pVal.error) { console.error('Failed : ' + pVal.message + ' ' + pVal) } if(Promise.resolve(pVal) === pVal) { // Passed in function retured a promise. We still need to wait for it. pVal.then((pVal)=>{ // console.log('Then --pVal = ' + pVal + ' bContinue = ' + continueOnFailure ); console.log(p); if(!pVal && !continueOnFailure) { console.error(`E1 : i = ${i} : pVal :` + pVal); console.error('debugData 2 -------------------'); console.log("Cancelling remaining..."); throw 'Failed in reduce 1 ' } if(!fn && !continueOnFailure) { console.error('Error : No task specified.'); throw false;} else if(!fn) return false; return (Promise.resolve(fn) === fn ) ? fn : fn() ; }) } else { // We will stop on null resolved values on any one task unless continueOnFailure is true. // console.log('Then --pVal = ' + pVal + ' bContinue = ' + continueOnFailure ); console.log(p); if(!pVal && !continueOnFailure) { console.error(`E2 : i = ${i} : pVal :` + pVal); console.error('debugData 2 -------------------'); console.log("Cancelling remaining..."); throw 'Failed in reduce 2 ' } if(!fn && !continueOnFailure) { console.error('Error : No task specified.'); throw false;} else if(!fn) return false; return (Promise.resolve(fn) === fn ) ? fn : fn() ; } }).catch((error) => { console.error(`E3 : i = ${i} `); fn ? console.error("Fn : " + fn.toString()) : null; console.error('debugData 3-------------------------'); throw 'Failed in reduce 3 ' }) } else if(!p) { console.log("Bypass on failure"); return false; } } , Promise.resolve(true) ); } var __isElevated = null; var isRunningElevated = ()=>{ if(__isElevated === null) { return nodeShellExec( "fsutil", ["dirty", "query", "C:"], { inherit : true // , shell: true , stdio: 'ignore' , env: process.env , title : `check privileged execution mode using "fsutil dirty query C:"` }).then((exitcode)=>{ console.log('Elevated') __isElevated = true; return true; }).catch(()=>{ __isElevated = false; console.log('Not Elevated'); throw false; }); } else return Promise.resolve(__isElevated); } var cli = 'elxr'; var ver = '#unversioned'; var help = '#unkown list of commands... please refer dveloper documentation for ' + cli; // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"} var dbForLabel = function(label){ var dbsForLabel = { devmysql : 'mysql' , development : 'mssql' , production : 'mssql' } return dbsForLabel[label] || 'mysql' } // Relevant git repos var gitRepos = [ 'ember-masonry-grid' , 'bbhverse' , 'clientverse' , 'serververse' , 'client' // , 'client/server' , 'elxr' , 'ember-searchable-select' , 'loopback-component-jsonapi' , 'elixir-config-development' , 'elixir-config-test' , 'cihsr-config' , 'cihsr-data' , 'elixir-data' , 'loopback-connector-ds' , 'chess-server-lib' , 'setup' , 'elixir-client-todos' , 'elixir-client-unlinked' , 'elixir-client' , 'ember-service-worker' , 'ember-service-worker-asset-cache' , 'ember-service-worker-cache-fallback' , 'ember-service-worker-index' , 'ember-sw-client-route' , 'global-this' ] // Repositiories that have symlinks that required elevated priviletes in windows to create symlinks // var elevatedRunasRepos = [ 'elixir-server' , 'cihsr-server' , 'chess-server' ] var productionRepos = [ 'elixir-config-production' ] var productionIsAllowed = true; if(productionIsAllowed) gitRepos = gitRepos.concat(productionRepos) var env = Object.assign({}, process.env); // Shallow clone it. var __runcmd = function(label){ var op = { 'h' : ()=>{ console.log(cli + ' ' + ver + ' ' + help); return '-h' } , 'undefined' : ()=>{ return op.h(); } , 'upgrade' : ()=>{ console.log('upgrade.......') var tasks = [ ()=>{ var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], { inherit : true, shell: true , env: process.env }).catch((e)=>{ console.error(e) }) p.position = 1; console.log('One') return p; } , ()=>{ var p = nodeShellExec('npm', ['cache', 'clean', '-f'], { inherit : true, shell: true , env: process.env }).catch((e)=>{ console.error(e) }) p.position = 2; console.log('Two') return p; } , ()=>{ var p = nodeShellExec('npm', ['install', '-g', 'n'], { inherit : true, shell: true , env: process.env }).catch((e)=>{ console.error(e) }) p.position = 3; console.log('Three') return p; } , ()=>{ var p = nodeShellExec('n', ['latest'], { inherit : true, shell: true , env: process.env }).catch((e)=>{ console.error(e) }) p.position = 4; console.log('Four') return p; } ] any(tasks) console.log('.......done') console.log('Running exlr upgrade in : ' + path.dirname(__dirname)) console.log('Currently only upgrades ember : ' + path.dirname(__dirname)); console.info('Uninstalling existing ember globally') ; var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], { stdio: ['pipe', process.stdout, process.stderr], inherit : true, shell: true, cwd : path.dirname(__dirname), env: env }) step1.on('close', ()=>{ console.info('Installing ember globally') ; var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], { stdio: ['pipe', process.stdout, process.stderr], inherit : true, shell: true, cwd : path.dirname(__dirname), env: env }) step2.on('close', ()=>{ nodeShellExec('cmd', ['/c', 'ember', '--version'], { stdio: ['pipe', process.stdout, process.stderr], inherit : true, shell: true, cwd : path.dirname(__dirname), env: env }) }) }) } , 'runas' : ()=>{ return isRunningElevated().then( (isElevated) => { if(isElevated) { try { op[ processedArgs.label || processedArgs._[0] || 'h']() } catch(e){ console.error('Error Invalid command : ' + e) fs.writeFileSync('run.done', 'success') } finally { } } else throw false; } ) .catch(()=>{ console.log('Requesting Elevated Privileges'); // Wait for the runas to complete before we read it. try { fs.unlinkSync('run.done') fs.unlinkSync('run.log') } catch(e) { } //Ignore // PB : TODO -- Convert all the cli args back to string. var namedArgs = []; Object.keys(processedArgs).forEach((v)=>{ v!='_' ? namedArgs.push('--'+v+'='+processedArgs[v]) : null; }) //console.log(' namedArgs : ' + namedArgs) process.env.NODE_ENV = process.env.NODE_ENV || 'development'; var args = [__dirname + '/windowselevate.hta'].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self'); nodeShellExec('MSHTA', [`"${args.join('" "')}"`] , { inherit : true , shell: true , env: process.env , runas : 'self' , title : `runas` } ).then(()=>{ // runas returned. var runaslog = JSON.parse('[ { "success" : true, "result" : "runas Log" }' + fs.readFileSync('run.log', { flags : 'a+'}) + ']'); runaslog.forEach((logEntry)=>{ logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')) }) }) .catch(err => console.error('Elevation failed : ' + err)); }) } , 'push' : ()=>{ if(!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return } // init remote bare from local // pushandinitremotebare // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories // connect to repo server -- net use 172.16.0.27 // cd 172.16.0.27/repos/ // mkdir repo.git // cd repo.git // git init --bare // cd localrepo // git remote rename origin githubclone // git remote add origin //172.16.0.27/repos/repo.git // git push origin master var repo = processedArgs._[1]; var defaultRepoServer = '//172.16.0.27/repos' var sequentialTaskShellCommands = []; if(!existsSync(`Z:/${repo}.git`)){ sequentialTaskShellCommands = [ // ['net', ['use', 'Z:', defaultRepoServer.replace('/','\\')], { // inherit : true, shell: true // , env: process.env // }] ['pwd', { cwd : 'Z:', inherit : true}] , ['mkdir', [`${repo}.git`], { cwd : `Z:` , inherit : true, shell: true , env: process.env }] , ['pwd', { cwd : `Z:/${repo}.git`, inherit : true}] , ['git', ['init', '--bare'], { cwd : `Z:/${repo}.git` , inherit : true, shell: true , env: process.env }] , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd : `${repo}`}, (err)=>{ console.log('Ignoring origin rename error : ' + err); return true; //return true to continue. } ] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure. , ['git', ['remote', 'add', 'origin', `${defaultRepoServer}/${repo}.git`], { cwd : `${repo}`}] ] if(!existsSync(`Z:`)){ sequentialTaskShellCommands.splice(0,0, ['net', ['use', 'Z:', defaultRepoServer.replace(/\//gm,'\\')], { inherit : true, shell: true , env: process.env }]) console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0]) // throw 'done' } } sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd : `${repo}`}]) // console.dir(sequentialTaskShellCommands); var tasks = []; sequentialTaskShellCommands.forEach(shellcmd => { // console.log(shellcmd) tasks.push(()=>{ var p = nodeShellExec.apply(null, shellcmd.slice(0,3)).catch((e)=>{ if(shellcmd[3]) { return shellcmd[3]() } else { console.error(e);} }) return p; }) }) any(tasks); } , 'pull' : (label) => { // Usage : // elxr pull -- Defaults to run config var env = Object.assign({}, process.env); // Shallow clone it. // console.dir(env) console.log('Running exlr pull : ' + path.dirname(__dirname)) // nodeShellExec('cmd', ['/c', 'setup\\utility\\chess.bat', 'pull'], { // // nodeShellExec('cmd', ['/c', '..\\setup\\utility\\chess.bat', 'pull'], { // stdio: ['pipe', process.stdout, process.stderr], // inherit : true, // shell: true, // cwd : path.dirname(__dirname), // env: env // }) var performPull = repo => { if(existsSync(repo)) { console.log('pulling ' + repo) return nodeShellExec('git', ['pull'], { inherit : true, shell: true, cwd : repo // , env: process.env , runas : processedArgs.runas , title : `git pull ${repo}` }).catch((e)=>{ console.error(e) }) } else { console.log('cloning ' + repo) return nodeShellExec('git', ['clone', '//172.16.0.27/repos/' + repo + '.git'], { inherit : true, shell: true, env: process.env , runas : processedArgs.runas , title : `git clone ${'//172.16.0.27/repos/' + repo + '.git'}` }).catch((e)=>{ console.error(e) }) } } if(!processedArgs.runas) gitRepos.forEach(performPull) return isRunningElevated().then( (isElevated) => { if(isElevated) { any(elevatedRunasRepos.map((repo)=>performPull(repo))).then(()=>{ fs.writeFileSync('run.done', 'success') }).catch(()=>{ fs.writeFileSync('run.done', 'error') }) } else throw false; } ).catch( () => { op['runas']() } ) } , 'npmi' : ()=>{ var tasks = []; gitRepos.forEach(repo => { console.log('npm i for ' + repo) // nodeShellExec('pwd', [], { // // inherit : true, shell: true // cwd : repo // // , env: process.env // , title : `pwd for ${repo}` // }).catch((e)=>{ console.error(e) }) nodeShellExec('rm', ['package-lock.json'], { inherit : true, shell: true , cwd : repo , env: process.env , title : `rm 'package-lock.json' for ${repo}` }).catch((e)=>{ console.error(e) }) tasks.push(()=>{ var p = nodeShellExec('npm', ['i'], { inherit : true, shell: true , cwd : repo , env: process.env , title : `npm i for ${repo}` }).catch((e)=>{ console.error(e) }) return p; }) }) any(tasks); } , 'start' : (label)=>{ console.log('Starting Elixir Server.'); var env = Object.assign({}, process.env); // Shallow clone it. // console.dir(env) env.NODE_ENV = process.env.NODE_ENV || 'development'; env.DEBUG = 'loopback:connector:' + dbForLabel(label) var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node'; // cmd = 'node' var childPromise = nodeShellExec(cmd, ['--inspect=9228', 'elixir/server.js'], { // inherit : true, shell: true, detached: true, stdio: 'ignore', cwd : 'elixir-server' , env: env }) var child = childPromise.process; if (typeof child.pid !== 'undefined') { fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, { encoding: 'utf8' }) } // nodeShellExec('node', ['--inspect=9226', ' bin/www'], { // inherit : true, // shell: true, detached: true, // cwd : 'qms/server', // env: env, // shell : true // }) // nodeShellExec('ember', ['s'], { // // inherit : true, // shell: true, detached: true, // cwd : 'client/', // env: env // }) var childPromise = nodeShellExec('ember', ['s'], { // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], { // PB : TODO -- ember debugging. // inherit : true, shell: true, detached: true, stdio: 'ignore', cwd : 'client' , env: env }) // .catch(e=>console.error(e)) child = childPromise.process; if (typeof child.pid !== 'undefined') { fs.writeFileSync('.client.server.pid', child.pid, { encoding: 'utf8' }) } } , 'stop' : (label)=>{ const kill = require('tree-kill'); var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', { encoding: 'utf8' }) fs.unlinkSync('.elixir-server.elixir.server.pid') console.log(serverPid) kill(serverPid) serverPid = fs.readFileSync('.client.server.pid', { encoding: 'utf8' }) fs.unlinkSync('.client.server.pid') console.log(serverPid) kill(serverPid) } , 'use' : ()=>{ // use a certain named instance. // Eg : // 1) elxr use elixir // 2) elxr use cihsr // If environment is not specified defaults to development. // 1) NODE=test elxr use elixir var runconfig = { NODE_ENV : process.env.NODE_ENV } try { runconfig = Object.assign(runconfig, require('../run.js')) } catch(e) { } if((!processedArgs.runas || processedArgs.runas !== 'self') && runconfig.NODE_ENV && runconfig.NODE_ENV === (process.env.NODE_ENV || runconfig.NODE_ENV) && processedArgs._[1] && runconfig.use === processedArgs._[1]) { console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`) if(processedArgs.runas) { fs.writeFileSync('run.done', 'success') } return } var tasks = [ ()=>{ if(existsSync('config')) { var p = nodeShellExec('rmdir', ['config'], {inherit : true, shell: true, env: process.env } ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; }) return p; } else return Promise.resolve(true); }, ()=>{ if(existsSync('data')) { var p = nodeShellExec('rmdir', ['data'], { inherit : true, shell: true, env: process.env } ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; }) return p; } else return Promise.resolve(true); }, ]; runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development'; if(processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1]; if(!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' } // console.log(process.env.cwd) fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig)) var checkoutMap = { 'development' : 'master', } // cant use git checkout -b it fails with branch already exists. var performCheckout = (repo)=>{ if(excludeCheckouts[repo]) return Promise.resolve({ 'skipped' : true }) return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], { inherit : true, shell: true, cwd : repo , runas : processedArgs.runas , title : `git switch -C -m ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${repo}` }).catch((e)=>{ console.error(e); return { error : true, message : repo} }) } var performPullAll = (repo)=>{ if(excludeCheckouts[repo]) return Promise.resolve({ 'skipped' : true }) return nodeShellExec('git', ['pull', '--all'], { inherit : true, shell: true, cwd : repo , runas : processedArgs.runas , title : `git switch -C -m ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${repo}` }).catch((e)=>{ console.error(e); return { error : true, message : repo} }) } var mergeSources = { 'development' : null, 'test' : 'master', 'production' : 'test' } var exludeMergeRepos = { 'elixir-config-development' : true, 'elixir-config-test': true, 'elixir-config-production' : true } var excludeCheckouts = Object.assign(exludeMergeRepos) delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`] var mergeSource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV] var performMerge = (repo)=>{ if(exludeMergeRepos[repo]) return Promise.resolve({ 'skipped' : true }) return nodeShellExec('git', ['merge', mergeSource], { inherit : true, shell: true, cwd : repo , runas : processedArgs.runas }).catch((e)=>{ console.error(e) }) } if(runconfig.NODE_ENV === 'development') performMerge = ()=>{ return Promise.resolve(true) } any(tasks).then(()=>{ if(!processedArgs.runas) return op['runas']() tasks = [ ()=>{ // Use junctions to avoid npm package issues var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV ], { inherit : true, shell: true , env: process.env }).catch((e)=>{ console.error(e) }) return p; } ]; if(processedArgs._[1]) { tasks = tasks.concat( [ ()=>{ var p = nodeShellExec('mklink', ['/D', 'data', runconfig.use + '-data'], { inherit : true, shell: true , env: process.env }).catch((e)=>{ console.error(e) }) return p; } ] ) } return any(tasks) .then( () => any([ any(gitRepos.map((repo)=>performPullAll(repo))), any(elevatedRunasRepos.map((repo)=>performPullAll(repo)))]) ) .then( () => any([ any(gitRepos.map((repo)=>performCheckout(repo))), any(elevatedRunasRepos.map((repo)=>performCheckout(repo)))]) ) .then( () => any([ any(gitRepos.map((repo)=>performMerge(repo))).catch(err=>{ console.error('error in performMerge ' + err)}) , any(elevatedRunasRepos.map((repo)=>performMerge(repo))).catch(err=>{ console.error('error in performMerge ' + err)})]) ) .then( () => { // Move test config from dev. if(process.env.NODE_ENV === 'test'){ var devcfgreponame = runconfig.use + '-config' + '-development'; var testcfgreponame = runconfig.use + '-config' + '-test'; var testcfgdir = path.dirname(__dirname) + '/' + testcfgreponame + '/' var devcfgdir = path.dirname(__dirname) + '/' + devcfgreponame + '/' //eg (elxr/../elixir-config.development) return any([ ()=>{ return nodeShellExec('git', ['checkout', 'test'], { inherit : true, shell: true, cwd : testcfgdir // , env: process.env , runas : processedArgs.runas , title : `git checkout test for ${testcfgreponame}` }).catch((e)=>{ console.error(e) }) } , ()=> { return nodeShellExec('git', ['checkout', 'master'], { inherit : true, shell: true, cwd : devcfgdir // , env: process.env , runas : processedArgs.runas , title : `git checkout master for ${devcfgreponame}` }).catch((e)=>{ console.error(e) }) } , ()=> { globSync( '**/*.test.js', {cwd : devcfgdir}).map((filename) => { console.log('File found : ' + devcfgdir + filename) fs.copyFileSync(devcfgdir + filename, testcfgdir+ filename); }) return nodeShellExec('git', ['checkout', 'test'], { inherit : true, shell: true, cwd : devcfgdir // , env: process.env , runas : processedArgs.runas , title : `git checkout test for ${devcfgreponame}` }).catch((e)=>{ console.error(e) }) } ]) } else return Promise.resolve(true) }) .then(()=>{ fs.writeFileSync('run.done', 'success') }).catch(()=>{ fs.writeFileSync('run.done', 'error') }) }).catch(()=>{ fs.writeFileSync('run.done', 'error') }) // Antibiotic stewardship program. // 1st use is fine. // Max vials dispense // 2nd use Pharmacy needs justification Form. // Approval after a certain period of time. } , 'g' : ()=>{ if(processedArgs.h) { console.log('elxr g [modelname] => generate a model named [modelname]'); console.log('elxr g => regenerate all known models'); return } // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} ); // console.log('Starting directory: ' + process.cwd()); // try { // child = child.on('close', () => { process.chdir(label) } ); // console.log('New directory: ' + process.cwd()); // } // catch (err) { // console.log('chdir: ' + err); // } // child.on('close', function(){ // var options = { // shell : true // , inherit : true // // , cwd : '' + process.cwd // // , env : process.env // }; // nodeShellExec('git', ['init'], { inherit : true}); if(0){ // PB : TODO -- Special google chrome profile for tests etc. nodeShellExec('pwd', { inherit : true}); //$ "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 1" http://localhost:4200/tests/index.html?grep=loopback nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [ "--profile-directory=Profile 1" , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]); } // nodeShellExec('npm', ['init', '-y'], options); // nodeShellExec('npm', ['init', '-y'], options); // }) var g = { 'client' : ()=>{ console.info('Creating new ember client named : ' + processedArgs._[2] ) ; var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], { stdio: ['pipe', process.stdout, process.stderr], inherit : true, shell: true, cwd : path.dirname(__dirname), env: env }) } } g[processedArgs._[1]](); } } return op[label] ? op[label]() : null; } // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql // mysql -u root -p db_name < drop_all_tables.sql var mysql = '../xampp/mysql/bin/mysql' var mysqldump = '../xampp/mysql/bin/mysqldump' // --runas if(processedArgs.runas) { // Weve been asked to run in priviledged mode. Check if we already are privileged. __runcmd('runas') } else __runcmd(processedArgs.label || processedArgs._[0] || 'h'); function nodeShellExec() { var args = Array.from(arguments); var opts = args[2] = args[2] || {} opts.title ? null : opts.title = `${args[0]} ${args[1] }` const child = spawn(...arguments); var p = new Promise(function(resolve, reject){ if(!opts.detached) { var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks... var success = true; if(opts.stdio !== 'ignore') { child.stdout.setEncoding('utf8'); child.stderr.setEncoding('utf8'); child.stdout.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/}); child.on('error', (chunk) => { success = false; messages.push(chunk); /*console.error(chunk)*/ }); child.stderr.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/}); } child.on('close', (code) => { if(+code !== 0) success = false; if(opts.stdio !== 'ignore') { if(opts.runas){ var logEntry = { result: `${opts.title} exited with code ${code}`, messages : messages } success ? logEntry.success = true : null; fs.writeFileSync('run.log', ', ' + JSON.stringify(logEntry), {'flag':'a+'} ) } else { success ? console.log(['success : ' + ` ${opts.title} exited with code ${code}`]) : console.error([`error : ${opts.title} exited with code ${code}`]) // console.log( messages.join('') ) process.stdout.write( messages.join('') ) } } if(code !== 0) return reject(code) resolve(true) }); } else { child.unref() resolve(true); } }); p.process = child; return p; }