Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. // --------------
  2. // elxr
  3. // A cli tool for elixr.
  4. const { existsSync } = require('fs');
  5. const fs = require('fs')
  6. const { spawn, spawnSync } = require('child_process');
  7. const cliargs = require('../elxr/cliargs'); // Use minimist...
  8. const processedArgs = cliargs(process.argv.slice(2));
  9. console.dir(processedArgs)
  10. var path = require('path')
  11. // Serialize a set of functions that will execute to return a promises one after the other.
  12. // Will stop when any one fails.
  13. function any(iterable, continueOnFailure) {
  14. return iterable.reduce(
  15. (p, fn, i ,a) => {
  16. // console.log('accumulator :');
  17. // console.log(p);
  18. if(Promise.resolve(p) === p ) {
  19. return p.then((pVal) => {
  20. if(Promise.resolve(pVal) === pVal) {
  21. // Passed in function retured a promise. We still need to wait for it.
  22. pVal.then((pVal)=>{
  23. // console.log('Then --pVal = ' + pVal + ' bContinue = ' + continueOnFailure ); console.log(p);
  24. if(!pVal && !continueOnFailure) {
  25. console.error("E : pVal :" + pVal);
  26. // i==0 ? null : console.error("E :1 a[i-1] " + a[i-1]);
  27. // a.map((i)=>console.error(i.toString()));
  28. console.error('debugData 3 -------------------');
  29. // console.error(debugData);
  30. console.error('debugData 3 -------------------');
  31. console.log("Cancelling remaining...");
  32. throw 'Failed in reduce 1 '
  33. return false;
  34. }
  35. // console.log('calling fn : '+ fn);
  36. return (Promise.resolve(fn) === fn ) ? fn : fn() ;
  37. })
  38. }
  39. else {
  40. // console.log('Then --pVal = ' + pVal + ' bContinue = ' + continueOnFailure ); console.log(p);
  41. if(!pVal && !continueOnFailure) {
  42. console.error("E : pVal :" + pVal);
  43. // i==0 ? null : console.error("E :1 a[i-1] " + a[i-1]);
  44. // a.map((i)=>console.error(i.toString()));
  45. console.error('debugData 3 -------------------');
  46. // console.error(debugData);
  47. console.error('debugData 3 -------------------');
  48. console.log("Cancelling remaining...");
  49. throw 'Failed in reduce 1 '
  50. return false;
  51. }
  52. // console.log('calling fn : '+ fn);
  53. return (Promise.resolve(fn) === fn ) ? fn : fn() ;
  54. }
  55. }).catch((error) => {
  56. console.error("E : " + error);
  57. fn ? console.error("Fn : " + fn.toString()) : null;
  58. // i==0 ? null : console.error("E :2 a[i-1] " + a[i-1]);
  59. // a.map((i)=>console.error(i.toString()));
  60. console.error('debugData 4-------------------------');
  61. // console.error(debugData);
  62. console.error('debugData 4-------------------------');
  63. throw 'Failed in reduce 2 '
  64. return false;
  65. })
  66. }
  67. else if(!p) {
  68. console.log("Bypass on failure");
  69. return false;
  70. }
  71. }
  72. , Promise.resolve(true)
  73. );
  74. }
  75. var isRunningElevated = ()=>{
  76. return nodeShellExec( "fsutil", ["dirty", "query", "C:"], {
  77. inherit : true, shell: true
  78. , env: process.env
  79. , title : `check privileged execution mode using fsutil dirty query C:`
  80. }).then((exitcode)=>{
  81. console.log('Elevated')
  82. return true;
  83. }).catch(()=>{
  84. console.log('Not Elevated');
  85. throw false;
  86. });
  87. }
  88. var cli = 'elxr';
  89. var ver = '#unversioned';
  90. var help = '#unkown list of commands... please refer dveloper documentation for ' + cli;
  91. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  92. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  93. var dbForLabel = function(label){
  94. var dbsForLabel = {
  95. devmysql : 'mysql'
  96. , development : 'mssql'
  97. , production : 'mssql'
  98. }
  99. return dbsForLabel[label] || 'mysql'
  100. }
  101. // Relevant git repos
  102. var gitRepos = [
  103. 'ember-masonry-grid'
  104. , 'bbhverse'
  105. , 'clientverse'
  106. , 'serververse'
  107. , 'client'
  108. // , 'client/server'
  109. , 'elxr'
  110. , 'ember-searchable-select'
  111. , 'loopback-component-jsonapi'
  112. , 'elixir-config-development'
  113. , 'cihsr-config'
  114. , 'cihsr-data'
  115. , 'elixir-data'
  116. , 'loopback-connector-ds'
  117. , 'chess-server-lib'
  118. , 'setup'
  119. , 'elixir-client-todos'
  120. , 'elixir-client-unlinked'
  121. , 'elixir-client'
  122. , 'ember-service-worker'
  123. , 'ember-service-worker-asset-cache'
  124. , 'ember-service-worker-cache-fallback'
  125. , 'ember-service-worker-index'
  126. , 'ember-sw-client-route'
  127. , 'global-this'
  128. ]
  129. // Repositiories that have symlinks that required elevated priviletes in windows to create symlinks
  130. //
  131. var elevatedRunasRepos = [
  132. 'elixir-server'
  133. , 'cihsr-server'
  134. , 'chess-server'
  135. ]
  136. var env = Object.assign({}, process.env); // Shallow clone it.
  137. var __runcmd = function(label){
  138. var op = {
  139. 'h' : ()=>{ console.log(cli + ' ' + ver + ' ' + help); return '-h' }
  140. , 'upgrade' : ()=>{
  141. console.log('upgrade.......')
  142. var tasks = [
  143. ()=>{
  144. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  145. inherit : true, shell: true
  146. , env: process.env
  147. }).catch((e)=>{ console.error(e) })
  148. p.position = 1;
  149. console.log('One')
  150. return p;
  151. }
  152. , ()=>{
  153. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  154. inherit : true, shell: true
  155. , env: process.env
  156. }).catch((e)=>{ console.error(e) })
  157. p.position = 2;
  158. console.log('Two')
  159. return p;
  160. }
  161. , ()=>{
  162. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  163. inherit : true, shell: true
  164. , env: process.env
  165. }).catch((e)=>{ console.error(e) })
  166. p.position = 3;
  167. console.log('Three')
  168. return p;
  169. }
  170. , ()=>{
  171. var p = nodeShellExec('n', ['latest'], {
  172. inherit : true, shell: true
  173. , env: process.env
  174. }).catch((e)=>{ console.error(e) })
  175. p.position = 4;
  176. console.log('Four')
  177. return p;
  178. }
  179. ]
  180. any(tasks)
  181. console.log('.......done')
  182. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  183. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  184. console.info('Uninstalling existing ember globally') ;
  185. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  186. stdio: ['pipe', process.stdout, process.stderr],
  187. inherit : true,
  188. shell: true,
  189. cwd : path.dirname(__dirname),
  190. env: env
  191. })
  192. step1.on('close', ()=>{
  193. console.info('Installing ember globally') ;
  194. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  195. stdio: ['pipe', process.stdout, process.stderr],
  196. inherit : true,
  197. shell: true,
  198. cwd : path.dirname(__dirname),
  199. env: env
  200. })
  201. step2.on('close', ()=>{
  202. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  203. stdio: ['pipe', process.stdout, process.stderr],
  204. inherit : true,
  205. shell: true,
  206. cwd : path.dirname(__dirname),
  207. env: env
  208. })
  209. })
  210. })
  211. }
  212. , 'runas' : ()=>{
  213. return isRunningElevated().then(() => op[ processedArgs.label || processedArgs._[0] || 'h']() )
  214. .catch(()=>{
  215. console.log('Not Elevated');
  216. console.dir(processedArgs)
  217. // PB : TODO -- Convert all the cli args back to string.
  218. var namedArgs = [];
  219. Object.keys(processedArgs).forEach((v)=>{ v!='_' ? namedArgs.push('--'+v+'='+processedArgs[v]) : null; })
  220. var cargs = `${processedArgs.debug ? '--inspect-brk' : ''} --inspect-brk elxr ${processedArgs._.join(' ')} ${namedArgs.join(' ') } --runas=true`
  221. console.log('Requesting Elevated Privileges for : ' + `node ${cargs}`)
  222. // fs.writeFileSync('runas.js', `javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('node', '${cargs}', '', 'runas', 1);close();`)
  223. nodeShellExec('MSHTA', [`javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('node', '${cargs}', '', 'runas', 1);close();`]
  224. , {
  225. // inherit : true
  226. // , shell: true
  227. // cwd : process.env.pwd
  228. // ,
  229. env: process.env
  230. }
  231. );
  232. })
  233. }
  234. , 'push' : ()=>{
  235. if(!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  236. // init remote bare from local
  237. // pushandinitremotebare
  238. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  239. // connect to repo server -- net use 172.16.0.27
  240. // cd 172.16.0.27/repos/
  241. // mkdir repo.git
  242. // cd repo.git
  243. // git init --bare
  244. // cd localrepo
  245. // git remote rename origin githubclone
  246. // git remote add origin //172.16.0.27/repos/repo.git
  247. // git push origin master
  248. var repo = processedArgs._[1];
  249. var defaultRepoServer = '//172.16.0.27/repos'
  250. var sequentialTaskShellCommands = [];
  251. if(!existsSync(`Z:/${repo}.git`)){
  252. sequentialTaskShellCommands = [
  253. // ['net', ['use', 'Z:', defaultRepoServer.replace('/','\\')], {
  254. // inherit : true, shell: true
  255. // , env: process.env
  256. // }]
  257. ['pwd', { cwd : 'Z:', inherit : true}]
  258. , ['mkdir', [`${repo}.git`], {
  259. cwd : `Z:`
  260. , inherit : true, shell: true
  261. , env: process.env
  262. }]
  263. , ['pwd', { cwd : `Z:/${repo}.git`, inherit : true}]
  264. , ['git', ['init', '--bare'], { cwd : `Z:/${repo}.git`
  265. , inherit : true, shell: true
  266. , env: process.env
  267. }]
  268. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd : `${repo}`}, (err)=>{
  269. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  270. } ] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  271. , ['git', ['remote', 'add', 'origin', `${defaultRepoServer}/${repo}.git`], { cwd : `${repo}`}]
  272. ]
  273. if(!existsSync(`Z:`)){
  274. sequentialTaskShellCommands.splice(0,0, ['net', ['use', 'Z:', defaultRepoServer.replace(/\//gm,'\\')], {
  275. inherit : true, shell: true
  276. , env: process.env
  277. }])
  278. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  279. // throw 'done'
  280. }
  281. }
  282. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd : `${repo}`}])
  283. // console.dir(sequentialTaskShellCommands);
  284. var tasks = [];
  285. sequentialTaskShellCommands.forEach(shellcmd => {
  286. // console.log(shellcmd)
  287. tasks.push(()=>{
  288. var p = nodeShellExec.apply(null, shellcmd.slice(0,3)).catch((e)=>{ if(shellcmd[3]) { return shellcmd[3]() } else { console.error(e);} })
  289. return p;
  290. })
  291. })
  292. any(tasks);
  293. }
  294. , 'pull' : (label) => {
  295. var env = Object.assign({}, process.env); // Shallow clone it.
  296. // console.dir(env)
  297. console.log('Running exlr pull : ' + path.dirname(__dirname))
  298. // nodeShellExec('cmd', ['/c', 'setup\\utility\\chess.bat', 'pull'], {
  299. // // nodeShellExec('cmd', ['/c', '..\\setup\\utility\\chess.bat', 'pull'], {
  300. // stdio: ['pipe', process.stdout, process.stderr],
  301. // inherit : true,
  302. // shell: true,
  303. // cwd : path.dirname(__dirname),
  304. // env: env
  305. // })
  306. var performPull = repo => {
  307. if(existsSync(repo)) {
  308. console.log('pulling ' + repo)
  309. nodeShellExec('git', ['pull'], {
  310. inherit : true, shell: true,
  311. cwd : repo
  312. // , env: process.env
  313. , title : `git pull ${repo}`
  314. }).catch((e)=>{ console.error(e) })
  315. }
  316. else {
  317. console.log('cloning ' + repo)
  318. nodeShellExec('git', ['clone', '//172.16.0.27/repos/' + repo + '.git'],
  319. {
  320. inherit : true, shell: true,
  321. env: process.env
  322. , title : `git clone ${'//172.16.0.27/repos/' + repo + '.git'}`
  323. }).catch((e)=>{ console.error(e) })
  324. }
  325. }
  326. if(!processedArgs.runas) gitRepos.forEach(performPull)
  327. return isRunningElevated().then(
  328. ()=> elevatedRunasRepos.forEach(performPull))
  329. .catch(
  330. () => op['runas']()
  331. )
  332. }
  333. , 'npmi' : ()=>{
  334. var tasks = [];
  335. gitRepos.forEach(repo => {
  336. console.log('npm i for ' + repo)
  337. // nodeShellExec('pwd', [], {
  338. // // inherit : true, shell: true
  339. // cwd : repo
  340. // // , env: process.env
  341. // , title : `pwd for ${repo}`
  342. // }).catch((e)=>{ console.error(e) })
  343. nodeShellExec('rm', ['package-lock.json'], {
  344. inherit : true, shell: true
  345. , cwd : repo
  346. , env: process.env
  347. , title : `rm 'package-lock.json' for ${repo}`
  348. }).catch((e)=>{ console.error(e) })
  349. tasks.push(()=>{
  350. var p = nodeShellExec('npm', ['i'], {
  351. inherit : true, shell: true
  352. , cwd : repo
  353. , env: process.env
  354. , title : `npm i for ${repo}`
  355. }).catch((e)=>{ console.error(e) })
  356. return p;
  357. })
  358. })
  359. any(tasks);
  360. }
  361. , 'start' : (label)=>{
  362. console.log('Starting Elixir Server.');
  363. var env = Object.assign({}, process.env); // Shallow clone it.
  364. // console.dir(env)
  365. env.NODE_ENV = label || 'development';
  366. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  367. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  368. // cmd = 'node'
  369. var childPromise = nodeShellExec(cmd, ['--inspect=9228', 'elixir/server.js'], {
  370. // inherit : true,
  371. shell: true,
  372. detached: true,
  373. stdio: 'ignore',
  374. cwd : 'elixir-server'
  375. , env: env
  376. })
  377. var child = childPromise.process;
  378. if (typeof child.pid !== 'undefined') {
  379. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  380. encoding: 'utf8'
  381. })
  382. }
  383. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  384. // inherit : true,
  385. // shell: true, detached: true,
  386. // cwd : 'qms/server',
  387. // env: env,
  388. // shell : true
  389. // })
  390. // nodeShellExec('ember', ['s'], {
  391. // // inherit : true,
  392. // shell: true, detached: true,
  393. // cwd : 'client/',
  394. // env: env
  395. // })
  396. var childPromise = nodeShellExec('ember', ['s'], {
  397. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  398. // PB : TODO -- ember debugging.
  399. // inherit : true,
  400. shell: true,
  401. detached: true,
  402. stdio: 'ignore',
  403. cwd : 'client'
  404. , env: env
  405. })
  406. // .catch(e=>console.error(e))
  407. child = childPromise.process;
  408. if (typeof child.pid !== 'undefined') {
  409. fs.writeFileSync('.client.server.pid', child.pid, {
  410. encoding: 'utf8'
  411. })
  412. }
  413. }
  414. , 'stop' : (label)=>{
  415. const kill = require('tree-kill');
  416. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  417. encoding: 'utf8'
  418. })
  419. fs.unlinkSync('.elixir-server.elixir.server.pid')
  420. console.log(serverPid)
  421. kill(serverPid)
  422. serverPid = fs.readFileSync('.client.server.pid', {
  423. encoding: 'utf8'
  424. })
  425. fs.unlinkSync('.client.server.pid')
  426. console.log(serverPid)
  427. kill(serverPid)
  428. }
  429. , 'use' : ()=>{
  430. var runconfig = { NODE_ENV : process.env.NODE_ENV }
  431. try {
  432. runconfig = Object.assign(runconfig, require('../run.js'))
  433. } catch(e) { }
  434. if(runconfig.NODE_ENV === process.env.NODE_ENV && processedArgs._[1] && runconfig.use === processedArgs._[1]) return;
  435. var tasks = [
  436. ()=>{
  437. if(existsSync('config')) {
  438. var p = nodeShellExec('rmdir', ['config'], {inherit : true, shell: true, env: process.env }
  439. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  440. return p;
  441. }
  442. else return Promise.resolve(true);
  443. },
  444. ()=>{
  445. if(existsSync('data')) {
  446. var p = nodeShellExec('rmdir', ['data'], { inherit : true, shell: true, env: process.env }
  447. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  448. return p;
  449. }
  450. else return Promise.resolve(true);
  451. }
  452. ];
  453. any(tasks)
  454. if(!processedArgs.runas) return op['runas']()
  455. process.env.NODE_ENV = process.env.NODE_ENV || 'development';
  456. if(processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  457. if(!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  458. // console.log(process.env.cwd)
  459. fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
  460. tasks = [
  461. ()=>{
  462. // Use junctions to avoid npm package issues
  463. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-' + process.env.NODE_ENV + '-config'], {
  464. inherit : true, shell: true
  465. , env: process.env
  466. }).catch((e)=>{ console.error(e) })
  467. return p;
  468. }
  469. ];
  470. if(processedArgs._[1]) {
  471. tasks.concat(
  472. [
  473. ()=>{
  474. var p = nodeShellExec('mklink', ['/D', 'data', runconfig.use + '-data'], {
  475. inherit : true, shell: true
  476. , env: process.env
  477. }).catch((e)=>{ console.error(e) })
  478. return p;
  479. }
  480. ]
  481. )
  482. }
  483. any(tasks)
  484. // Antibiotic stewardship program.
  485. // 1st use is fine.
  486. // Max vials dispense
  487. // 2nd use Pharmacy needs justification Form.
  488. // Approval after a certain period of time.
  489. }
  490. , 'g' : ()=>{
  491. if(processedArgs.h) {
  492. console.log('elxr g [modelname] => generate a model named [modelname]');
  493. console.log('elxr g => regenerate all known models');
  494. return
  495. }
  496. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  497. // console.log('Starting directory: ' + process.cwd());
  498. // try {
  499. // child = child.on('close', () => { process.chdir(label) } );
  500. // console.log('New directory: ' + process.cwd());
  501. // }
  502. // catch (err) {
  503. // console.log('chdir: ' + err);
  504. // }
  505. // child.on('close', function(){
  506. // var options = {
  507. // shell : true
  508. // , inherit : true
  509. // // , cwd : '' + process.cwd
  510. // // , env : process.env
  511. // };
  512. // nodeShellExec('git', ['init'], { inherit : true});
  513. if(0){
  514. // PB : TODO -- Special google chrome profile for tests etc.
  515. nodeShellExec('pwd', { inherit : true});
  516. //$ "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 1" http://localhost:4200/tests/index.html?grep=loopback
  517. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  518. "--profile-directory=Profile 1"
  519. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  520. }
  521. // nodeShellExec('npm', ['init', '-y'], options);
  522. // nodeShellExec('npm', ['init', '-y'], options);
  523. // })
  524. var g = {
  525. 'client' : ()=>{
  526. console.info('Creating new ember client named : ' + processedArgs._[2] ) ;
  527. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  528. stdio: ['pipe', process.stdout, process.stderr],
  529. inherit : true,
  530. shell: true,
  531. cwd : path.dirname(__dirname),
  532. env: env
  533. })
  534. }
  535. }
  536. g[processedArgs._[1]]();
  537. }
  538. }
  539. return op[label] ? op[label]() : op['start'](label);
  540. }
  541. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  542. // mysql -u root -p db_name < drop_all_tables.sql
  543. var mysql = '../xampp/mysql/bin/mysql'
  544. var mysqldump = '../xampp/mysql/bin/mysqldump'
  545. __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  546. // nodeShellExec('git', ['status']);
  547. function nodeShellExec() {
  548. var args = Array.from(arguments);
  549. args[2] ? null : args[2] = {}
  550. args[2].title ? null : args[2].title = `${args[0]} ${args[1]}`
  551. const child = spawn(...arguments);
  552. var p = new Promise(function(resolve, reject){
  553. if(!args[2].detached) {
  554. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  555. // use child.stdout.setEncoding('utf8'); if you want text chunks
  556. child.stdout.setEncoding('utf8');
  557. child.stderr.setEncoding('utf8');
  558. child.stdout.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  559. child.on('error', (chunk) => { messages.push(chunk); /*console.error(chunk)*/ });
  560. child.stderr.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  561. // child.stderr.pipe(process.stderr);
  562. child.on('close', (code) => {
  563. console.log([` ${args[2].title} exited with code ${code}`])
  564. // console.log([ messages.join('') ])
  565. process.stdout.write( messages.join('') )
  566. if(code !== 0 ) return reject(code)
  567. resolve(true)
  568. });
  569. }
  570. else {
  571. child.unref()
  572. resolve(true);
  573. }
  574. });
  575. p.process = child;
  576. return p;
  577. }