You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 42KB

6 vuotta sitten
4 vuotta sitten
4 vuotta sitten
5 vuotta sitten
6 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
6 vuotta sitten
5 vuotta sitten
6 vuotta sitten
5 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
6 vuotta sitten
5 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
5 vuotta sitten
5 vuotta sitten
5 vuotta sitten
4 vuotta sitten
4 vuotta sitten
5 vuotta sitten
5 vuotta sitten
4 vuotta sitten
5 vuotta sitten
5 vuotta sitten
4 vuotta sitten
5 vuotta sitten
4 vuotta sitten
5 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
5 vuotta sitten
4 vuotta sitten
5 vuotta sitten
4 vuotta sitten
5 vuotta sitten
4 vuotta sitten
5 vuotta sitten
6 vuotta sitten
5 vuotta sitten
6 vuotta sitten
5 vuotta sitten
6 vuotta sitten
4 vuotta sitten
4 vuotta sitten
4 vuotta sitten
6 vuotta sitten
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  1. 
  2. // 'use strict';
  3. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  4. // --------------
  5. // elxr
  6. // A cli tool for elixr.
  7. // PB : TODO --
  8. // runas bypass non elevated tasks when we request privelege
  9. // runas message is always error needs to be fixed.
  10. // runas wait needs to be parallelized.
  11. // suppress elevation check error messages
  12. // support runas lauched directly from shell.
  13. // pass in environment in hta to shellexecute.
  14. const { existsSync } = require('fs');
  15. const fs = require('fs')
  16. const { spawn, spawnSync } = require('child_process');
  17. const cliargs = require('../elxr/cliargs'); // Use minimist...
  18. const processedArgs = cliargs(process.argv.slice(2));
  19. console.dir(processedArgs)
  20. var globSync = require('glob').sync;
  21. var path = require('path');
  22. const { isMaster } = require('cluster');
  23. // Default Config...
  24. var reposervers = [
  25. 'http://git.bbh'
  26. , '//172.16.0.27/repos'
  27. ]
  28. var defaultRepoServer = reposervers[0]
  29. var currentGitAuthUser ; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current gittea username
  30. var defaultRepoOwner = 'chess';
  31. // Serialize a set of functions that will execute to return a promises one after the other.
  32. // Will stop when any one fails unless continueOnFailure is true.
  33. // All tasks in iterables can be functions or promises.
  34. // promises as usual can return other promises or resolve to either truthy or falsy values.
  35. // functions must return a promise
  36. function any(iterable, continueOnFailure) {
  37. return iterable.reduce(
  38. (p, fn, i ,a) => {
  39. // console.log('accumulator :');
  40. // console.log(p);
  41. if(Promise.resolve(p) === p ) {
  42. return p.then((pVal) => {
  43. // Falsy values are task failure.
  44. if(!pVal) {
  45. console.warn('Possible failure for result : ' + pVal)
  46. console.warn(a[i-1])
  47. fn ? console.error("Fn : " + fn.toString()) : null;
  48. }
  49. // Truthy values are failures if obj has error=true.
  50. if(pVal && pVal.error) { console.error('Failed : ' + pVal.message + ' ' + pVal) }
  51. if(Promise.resolve(pVal) === pVal) {
  52. // Passed in function retured a promise. We still need to wait for it.
  53. pVal.then((pVal)=>{
  54. // console.log('Then --pVal = ' + pVal + ' bContinue = ' + continueOnFailure ); console.log(p);
  55. if(!pVal && !continueOnFailure) {
  56. console.error(`E1 : i = ${i} : pVal :` + pVal);
  57. console.error('debugData 2 -------------------');
  58. console.log("Cancelling remaining...");
  59. throw 'Failed in reduce 1 '
  60. }
  61. if(!fn && !continueOnFailure) { console.error('Error : No task specified.'); throw false;}
  62. else if(!fn) return false;
  63. return (Promise.resolve(fn) === fn ) ? fn : fn() ;
  64. })
  65. }
  66. else {
  67. // We will stop on null resolved values on any one task unless continueOnFailure is true.
  68. // console.log('Then --pVal = ' + pVal + ' bContinue = ' + continueOnFailure ); console.log(p);
  69. if(!pVal && !continueOnFailure) {
  70. console.error(`E2 : i = ${i} : pVal :` + pVal);
  71. console.error('debugData 2 -------------------');
  72. console.log("Cancelling remaining...");
  73. throw 'Failed in reduce 2 '
  74. }
  75. if(!fn && !continueOnFailure) { console.error('Error : No task specified.'); throw false;}
  76. else if(!fn) return false;
  77. return (Promise.resolve(fn) === fn ) ? fn : fn() ;
  78. }
  79. }).catch((error) => {
  80. console.error(`E3 : i = ${i} `);
  81. fn ? console.error("Fn : " + fn.toString()) : null;
  82. console.error('debugData 3-------------------------');
  83. throw 'Failed in reduce 3 '
  84. })
  85. }
  86. else if(!p) {
  87. console.log("Bypass on failure");
  88. return false;
  89. }
  90. }
  91. , Promise.resolve(true)
  92. );
  93. }
  94. var __isElevated = null;
  95. var isRunningElevated = ()=>{
  96. if(__isElevated === null) {
  97. return nodeShellExec( "fsutil", ["dirty", "query", "C:"], {
  98. inherit : true
  99. // , shell: true
  100. , stdio: 'ignore'
  101. , env: process.env
  102. , title : `check privileged execution mode using "fsutil dirty query C:"`
  103. }).then((exitcode)=>{
  104. console.log('Elevated')
  105. __isElevated = true;
  106. return true;
  107. }).catch(()=>{
  108. __isElevated = false;
  109. console.log('Not Elevated');
  110. throw false;
  111. });
  112. }
  113. else return Promise.resolve(__isElevated);
  114. }
  115. var cli = 'elxr';
  116. var ver = '#unversioned';
  117. var help = '#unkown list of commands... please refer dveloper documentation for ' + cli;
  118. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  119. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  120. var dbForLabel = function(label){
  121. var dbsForLabel = {
  122. devmysql : 'mysql'
  123. , development : 'mssql'
  124. , production : 'mssql'
  125. }
  126. return dbsForLabel[label] || 'mysql'
  127. }
  128. var gitInstallDir = "C:\\Program Files\\Git\\bin\\sh.exe"
  129. // var gitInstallDir = "G:\\Installed\\Git\\bin\\sh.exe"
  130. // Relevant git repos
  131. var gitRepos = [
  132. 'ember-masonry-grid'
  133. , 'bbhverse'
  134. , 'clientverse'
  135. , 'serververse'
  136. , 'client'
  137. // , 'client/server'
  138. , 'elxr'
  139. , 'ember-searchable-select'
  140. , 'loopback-component-jsonapi'
  141. , 'loopback-jsonapi-model-serializer'
  142. , 'elixir-config-development'
  143. , 'elixir-config-test'
  144. , 'cihsr-config'
  145. , 'cihsr-data'
  146. , 'elixir-data'
  147. , 'loopback-connector-ds'
  148. , 'chess-server-lib'
  149. , 'setup'
  150. , 'elixir-client-todos'
  151. , 'elixir-client-unlinked'
  152. , 'elixir-client'
  153. , 'ember-service-worker'
  154. , 'ember-service-worker-asset-cache'
  155. , 'ember-service-worker-cache-fallback'
  156. , 'ember-service-worker-index'
  157. , 'ember-sw-client-route'
  158. , 'global-this'
  159. ]
  160. // Repositiories that have symlinks that required elevated priviletes in windows to create symlinks
  161. //
  162. var elevatedRunasRepos = [
  163. 'elixir-server'
  164. , 'cihsr-server'
  165. , 'chess-server'
  166. ]
  167. var productionRepos = [
  168. 'elixir-config-production'
  169. ]
  170. var productionIsAllowed = true;
  171. if(productionIsAllowed) gitRepos = gitRepos.concat(productionRepos)
  172. var env = Object.assign({}, process.env); // Shallow clone it.
  173. var __runcmd = function(label){
  174. var op = {
  175. 'h' : ()=>{ console.log(cli + ' ' + ver + ' ' + help); return '-h' }
  176. , 'undefined' : ()=>{ return op.h(); }
  177. , 'reset' : ()=>{
  178. // Reset NPM packages semver so major versions can be updated.
  179. const fs = require('fs')
  180. const wipeDependencies = (package) => {
  181. const file = fs.readFileSync(package + '/package.json')
  182. const content = JSON.parse(file)
  183. for (var devDep in content.devDependencies) {
  184. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  185. content.devDependencies[devDep] = '*';
  186. }
  187. }
  188. for (var dep in content.dependencies) {
  189. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  190. content.dependencies[dep] = '*';
  191. }
  192. }
  193. fs.writeFileSync(package + '/package.json', JSON.stringify(content))
  194. }
  195. var repos = ['client'];
  196. // repos = gitRepos;
  197. repos.forEach(wipeDependencies)
  198. // if (require.main === module) {
  199. // } else {
  200. // module.exports = wipeDependencies
  201. // }
  202. }
  203. , 'upgrade' : ()=>{
  204. console.log('upgrade.......')
  205. var tasks = [
  206. ()=>{
  207. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  208. inherit : true, shell: true
  209. , env: process.env
  210. }).catch((e)=>{ console.error(e) })
  211. p.position = 1;
  212. console.log('One')
  213. return p;
  214. }
  215. , ()=>{
  216. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  217. inherit : true, shell: true
  218. , env: process.env
  219. }).catch((e)=>{ console.error(e) })
  220. p.position = 2;
  221. console.log('Two')
  222. return p;
  223. }
  224. , ()=>{
  225. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  226. inherit : true, shell: true
  227. , env: process.env
  228. }).catch((e)=>{ console.error(e) })
  229. p.position = 3;
  230. console.log('Three')
  231. return p;
  232. }
  233. , ()=>{
  234. var p = nodeShellExec('n', ['latest'], {
  235. inherit : true, shell: true
  236. , env: process.env
  237. }).catch((e)=>{ console.error(e) })
  238. p.position = 4;
  239. console.log('Four')
  240. return p;
  241. }
  242. ]
  243. any(tasks)
  244. console.log('.......done')
  245. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  246. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  247. console.info('Uninstalling existing ember globally') ;
  248. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  249. stdio: ['pipe', process.stdout, process.stderr],
  250. inherit : true,
  251. shell: true,
  252. cwd : path.dirname(__dirname),
  253. env: env
  254. })
  255. step1.on('close', ()=>{
  256. console.info('Installing ember globally') ;
  257. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  258. stdio: ['pipe', process.stdout, process.stderr],
  259. inherit : true,
  260. shell: true,
  261. cwd : path.dirname(__dirname),
  262. env: env
  263. })
  264. step2.on('close', ()=>{
  265. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  266. stdio: ['pipe', process.stdout, process.stderr],
  267. inherit : true,
  268. shell: true,
  269. cwd : path.dirname(__dirname),
  270. env: env
  271. })
  272. })
  273. })
  274. }
  275. , 'runas' : ()=>{
  276. console.log('Testing Elevation')
  277. return isRunningElevated().then(
  278. (isElevated) => {
  279. if(isElevated) {
  280. try {
  281. op[ processedArgs.label || processedArgs._[0] || 'h']()
  282. }
  283. catch(e){
  284. console.error('Error Invalid command : ' + e)
  285. fs.writeFileSync('run.done', 'success')
  286. }
  287. finally {
  288. }
  289. } else throw false;
  290. }
  291. )
  292. .catch(()=>{
  293. console.log('Requesting Elevated Privileges');
  294. // Wait for the runas to complete before we read it.
  295. try {
  296. fs.unlinkSync('run.done')
  297. fs.unlinkSync('run.log')
  298. }
  299. catch(e) { } //Ignore
  300. // Find node path to send to hta.
  301. nodeShellExec('where', ['node']).then(r => {
  302. console.log('result : ' + r)
  303. // throw 'rrrrrrrrrrrrrrrrr'
  304. // PB : TODO -- Convert all the cli args back to string.
  305. var namedArgs = [];
  306. Object.keys(processedArgs).forEach((v)=>{ v!='_' ? namedArgs.push('--'+v+'='+processedArgs[v]) : null; })
  307. //console.log(' namedArgs : ' + namedArgs)
  308. process.env.NODE_ENV = process.env.NODE_ENV || 'development';
  309. var args = [__dirname + '/windowselevate.hta'].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  310. args.push('--nodepath='+r[r.length-1])
  311. nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  312. , {
  313. inherit : true
  314. , shell: true
  315. , env: process.env
  316. , runas : 'self'
  317. , title : `runas`
  318. }
  319. ).then(()=>{
  320. // runas returned.
  321. try {
  322. var runaslog = JSON.parse('[ { "success" : true, "result" : "runas Log" }' + fs.readFileSync('run.log', { flags : 'a+'}) + ']');
  323. runaslog.forEach((logEntry)=>{
  324. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  325. })
  326. }
  327. catch(e){
  328. // Ignore nonexistent log
  329. console.warn('Run log error probably was not created by runas : ' + e)
  330. }
  331. })
  332. .catch(err => console.error('Elevation failed : ' + err));
  333. })
  334. })
  335. }
  336. , 'push' : ()=>{
  337. if(!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  338. // init remote bare from local
  339. // pushandinitremotebare
  340. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  341. // connect to repo server -- net use 172.16.0.27
  342. // cd 172.16.0.27/repos/
  343. // mkdir repo.git
  344. // cd repo.git
  345. // git init --bare
  346. // cd localrepo
  347. // git remote rename origin githubclone
  348. // git remote add origin //172.16.0.27/repos/repo.git
  349. // git push origin master
  350. var repo = processedArgs._[1];
  351. var sequentialTaskShellCommands = [];
  352. if(!existsSync(`Z:/${repo}.git`)){
  353. sequentialTaskShellCommands = [
  354. // ['net', ['use', 'Z:', defaultRepoServer.replace('/','\\')], {
  355. // inherit : true, shell: true
  356. // , env: process.env
  357. // }]
  358. ['pwd', { cwd : 'Z:', inherit : true}]
  359. , ['mkdir', [`${repo}.git`], {
  360. cwd : `Z:`
  361. , inherit : true, shell: true
  362. , env: process.env
  363. }]
  364. , ['pwd', { cwd : `Z:/${repo}.git`, inherit : true}]
  365. , ['git', ['init', '--bare'], { cwd : `Z:/${repo}.git`
  366. , inherit : true, shell: true
  367. , env: process.env
  368. }]
  369. // PB : TODO -- Do this conditionally only...
  370. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd : `${repo}`}, (err)=>{
  371. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  372. } ] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  373. , ['git', ['remote', 'add', 'origin', `${defaultRepoServer}/${repo}.git`], { cwd : `${repo}`}]
  374. // PB : TODO -- If threre is a gitbubclone origin
  375. // Set the master to pull from the local repo.
  376. ]
  377. if(!existsSync(`Z:`)){
  378. sequentialTaskShellCommands.splice(0,0, ['net', ['use', 'Z:', defaultRepoServer.replace(/\//gm,'\\')], {
  379. inherit : true, shell: true
  380. , env: process.env
  381. }])
  382. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  383. // throw 'done'
  384. }
  385. }
  386. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd : `${repo}`}])
  387. // console.dir(sequentialTaskShellCommands);
  388. var tasks = [];
  389. sequentialTaskShellCommands.forEach(shellcmd => {
  390. // console.log(shellcmd)
  391. tasks.push(()=>{
  392. var p = nodeShellExec.apply(null, shellcmd.slice(0,3)).catch((e)=>{ if(shellcmd[3]) { return shellcmd[3]() } else { console.error(e);} })
  393. return p;
  394. })
  395. })
  396. any(tasks);
  397. }
  398. , 'is-git-repo' : (dir)=>{
  399. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio : 'ignore'})
  400. }
  401. , 'add' : (remotename, url, branch) => {
  402. var pushable = processedArgs.pushable || false;
  403. remotename = remotename || processedArgs._[1]
  404. url = url || processedArgs._[2]
  405. branch = branch || processedArgs._[3]
  406. var serial_perform_git_add = (repo)=>{
  407. var options = { cwd : repo }
  408. // console.log(repo)
  409. if(pushable) {
  410. return [
  411. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd : repo }]
  412. , ['git', ['pull', remotename, branch], { cwd : repo }]
  413. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd : repo }]
  414. ]
  415. }
  416. else {
  417. return [
  418. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd : repo }]
  419. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd : repo }]
  420. , ['git', ['pull', remotename, branch], { cwd : repo }]
  421. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd : repo }]
  422. ]
  423. }
  424. }
  425. var x = (args)=>{
  426. return ()=>{
  427. // console.log(args)
  428. return nodeShellExec.apply(null, args)
  429. }
  430. // return Promise.resolve(true)
  431. }
  432. var perform_git_add = (dir)=>{
  433. op['is-git-repo'](dir).then((code)=>{
  434. // console.log(code)
  435. if(code) {
  436. nodeShellExec('git',['remote', 'get-url', remotename], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  437. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  438. })
  439. .catch((e)=>{
  440. any( serial_perform_git_add(dir.name).map(x) )
  441. })
  442. }
  443. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  444. }).catch((e)=>{
  445. // console.log('Failed : ' + dir.name)
  446. })
  447. }
  448. const { readdir } = require("fs").promises
  449. const dirs = async (perform, path) => {
  450. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  451. if (dir.isDirectory()) perform(dir)
  452. }
  453. }
  454. dirs(perform_git_add)
  455. }
  456. , 'remove' : (remotename) => {
  457. remotename = remotename || processedArgs._[1]
  458. var serial_perform_git_remove = (repo)=>{
  459. var options = { cwd : repo }
  460. // console.log(repo)
  461. return [
  462. ['git', ['remote', 'remove', remotename], { cwd : repo }]
  463. ]
  464. }
  465. var x = (args)=>{
  466. return ()=>{
  467. // console.log(args)
  468. return nodeShellExec.apply(null, args)
  469. }
  470. // return Promise.resolve(true)
  471. }
  472. var perform_git_remove = (dir)=>{
  473. op['is-git-repo'](dir).then((code)=>{
  474. // console.log(code)
  475. if(code) {
  476. nodeShellExec('git',['remote', 'get-url', remotename], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  477. any( serial_perform_git_remove(dir.name).map(x) )
  478. })
  479. .catch((e)=>{
  480. console.log('skipped : ' + dir.name + ', reason : No remote named origin')
  481. })
  482. }
  483. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  484. }).catch((e)=>{
  485. // console.log('Failed : ' + dir.name)
  486. })
  487. }
  488. const { readdir } = require("fs").promises
  489. const dirs = async (perform, path) => {
  490. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  491. if (dir.isDirectory()) perform(dir)
  492. }
  493. }
  494. dirs(perform_git_remove)
  495. }
  496. , 'init-gitea' : (user) => {
  497. user = user || processedArgs._[1]
  498. if(!user) throw 'User name required'
  499. var serial_perform_init_gitea = (repo)=>{
  500. var options = { cwd : repo }
  501. // console.log(repo)
  502. return [
  503. ['git', ['remote', 'add', 'chess', 'http://git.bbh/chess/elxr.git'], { cwd : repo }]
  504. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd : repo }]
  505. , ['git', ['remote', 'set-url', 'origin', `http://git.bbh/${user}/${repo}.git`], { cwd : repo }]
  506. ]}
  507. var x = (args)=>{
  508. return ()=>{
  509. // console.log(args)
  510. return nodeShellExec.apply(null, args)
  511. }
  512. // return Promise.resolve(true)
  513. }
  514. var perform_init_gitea = (dir)=>{
  515. op['is-git-repo'](dir).then((code)=>{
  516. // console.log(code)
  517. if(code) {
  518. nodeShellExec('git',['remote', 'get-url', 'chess'], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  519. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  520. })
  521. .catch((e)=>{
  522. any( serial_perform_init_gitea(dir.name).map(x) )
  523. })
  524. }
  525. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  526. }).catch((e)=>{
  527. // console.log('Failed : ' + dir.name)
  528. })
  529. }
  530. const { readdir } = require("fs").promises
  531. const dirs = async (perform, path) => {
  532. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  533. if (dir.isDirectory()) perform(dir)
  534. }
  535. }
  536. dirs(perform_init_gitea)
  537. }
  538. , 'pull' : (label) => {
  539. // Usage :
  540. // elxr pull -- Defaults to run config
  541. var env = Object.assign({}, process.env); // Shallow clone it.
  542. // console.dir(env)
  543. console.log('Running exlr pull : ' + path.dirname(__dirname))
  544. // nodeShellExec('cmd', ['/c', 'setup\\utility\\chess.bat', 'pull'], {
  545. // // nodeShellExec('cmd', ['/c', '..\\setup\\utility\\chess.bat', 'pull'], {
  546. // stdio: ['pipe', process.stdout, process.stderr],
  547. // inherit : true,
  548. // shell: true,
  549. // cwd : path.dirname(__dirname),
  550. // env: env
  551. // })
  552. var useGitPull = processedArgs.useGitPull || false;
  553. var getPullCmd = (repo)=>{
  554. // console.log(useGitPull)
  555. var pullCmd = [ gitInstallDir
  556. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  557. , { cwd : repo, title : 'pull all origins for ' + repo }]
  558. // var pullCmd = ['pullall', [], { cwd : repo }]
  559. if(useGitPull) pullCmd = ['git', ['pull'], {
  560. inherit : true, shell: true,
  561. cwd : repo
  562. // , env: process.env
  563. , runas : processedArgs.runas
  564. , title : `git pull ${repo}`
  565. }]
  566. return pullCmd
  567. }
  568. var performPull = (repo) => {
  569. if(existsSync(repo)) {
  570. console.log('pulling ' + repo)
  571. return nodeShellExec.apply(null, getPullCmd(repo)).catch((e)=>{ console.error(e) })
  572. }
  573. else {
  574. console.log('cloning ' + repo)
  575. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  576. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', defaultRepoServer + `/${defaultRepoOwner}/` + repo + '.git'],
  577. {
  578. inherit : true, shell: true,
  579. env: process.env
  580. , runas : processedArgs.runas
  581. }).catch((e)=>{ console.error(e) }).then(()=>{
  582. return nodeShellExec('git', ['config', '--replace-all' , 'core.symlinks', true],
  583. {
  584. inherit : true, shell: true,
  585. env: process.env
  586. , cwd : repo
  587. , runas : processedArgs.runas
  588. , title : `git core.symlinks --replace-all true for ${defaultRepoServer + `/${defaultRepoOwner}/` + repo + '.git'}`
  589. })
  590. })
  591. }
  592. }
  593. if(!processedArgs.runas) gitRepos.forEach(performPull)
  594. return isRunningElevated().then(
  595. (isElevated) => {
  596. if(isElevated) {
  597. any(elevatedRunasRepos.map((repo)=>performPull(repo))).then(()=>{
  598. fs.writeFileSync('run.done', 'success')
  599. }).catch(()=>{
  600. fs.writeFileSync('run.done', 'error')
  601. })
  602. }
  603. else throw false;
  604. }
  605. ).catch(
  606. () => {
  607. op['runas']()
  608. }
  609. )
  610. }
  611. , 'isInstalled' : ()=>{
  612. return nodeShellExec('where', [processedArgs._[1]], { inherit : true} ).then(()=>{
  613. console.log(processedArgs._[1] + ' exists.')
  614. return true;
  615. });
  616. }
  617. , 'npmi' : ()=>{
  618. var tasks = [];
  619. gitRepos.forEach(repo => {
  620. console.log('npm i for ' + repo)
  621. // nodeShellExec('pwd', [], {
  622. // // inherit : true, shell: true
  623. // cwd : repo
  624. // // , env: process.env
  625. // , title : `pwd for ${repo}`
  626. // }).catch((e)=>{ console.error(e) })
  627. nodeShellExec('rm', ['package-lock.json'], {
  628. inherit : true, shell: true
  629. , cwd : repo
  630. , env: process.env
  631. , title : `rm 'package-lock.json' for ${repo}`
  632. }).catch((e)=>{ console.error(e) })
  633. tasks.push(()=>{
  634. var p = nodeShellExec('npm', ['i'], {
  635. inherit : true, shell: true
  636. , cwd : repo
  637. , env: process.env
  638. , title : `npm i for ${repo}`
  639. }).catch((e)=>{ console.error(e) })
  640. return p;
  641. })
  642. })
  643. any(tasks);
  644. }
  645. , 'start' : (label)=>{
  646. console.log('Starting Elixir Server.');
  647. var env = Object.assign({}, process.env); // Shallow clone it.
  648. // console.dir(env)
  649. env.NODE_ENV = process.env.NODE_ENV || 'development';
  650. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  651. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  652. // cmd = 'node'
  653. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
  654. var childPromise = nodeShellExec(...cmd, {
  655. // inherit : true,
  656. shell: true,
  657. detached: true,
  658. stdio: 'ignore',
  659. cwd : 'elixir-server'
  660. , env: env
  661. })
  662. var child = childPromise.process;
  663. if (typeof child.pid !== 'undefined') {
  664. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  665. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  666. encoding: 'utf8'
  667. })
  668. }
  669. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  670. // inherit : true,
  671. // shell: true, detached: true,
  672. // cwd : 'qms/server',
  673. // env: env,
  674. // shell : true
  675. // })
  676. // nodeShellExec('ember', ['s'], {
  677. // // inherit : true,
  678. // shell: true, detached: true,
  679. // cwd : 'client/',
  680. // env: env
  681. // })
  682. console.log('Starting Elixir Client Host.');
  683. var cmd = ['ember', ['s']]
  684. var childPromise = nodeShellExec(...cmd, {
  685. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  686. // PB : TODO -- ember debugging.
  687. // inherit : true,
  688. shell: true,
  689. detached: true,
  690. stdio: 'ignore',
  691. cwd : 'client'
  692. , env: env
  693. })
  694. // .catch(e=>console.error(e))
  695. child = childPromise.process;
  696. if (typeof child.pid !== 'undefined') {
  697. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  698. fs.writeFileSync('.client.server.pid', child.pid, {
  699. encoding: 'utf8'
  700. })
  701. }
  702. }
  703. , 'stop' : (label)=>{
  704. const kill = require('tree-kill');
  705. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  706. encoding: 'utf8'
  707. })
  708. fs.unlinkSync('.elixir-server.elixir.server.pid')
  709. console.log(serverPid)
  710. kill(serverPid)
  711. serverPid = fs.readFileSync('.client.server.pid', {
  712. encoding: 'utf8'
  713. })
  714. fs.unlinkSync('.client.server.pid')
  715. console.log(serverPid)
  716. kill(serverPid)
  717. }
  718. , 'use' : ()=>{
  719. // use a certain named instance.
  720. // Eg :
  721. // 1) elxr use elixir
  722. // 2) elxr use cihsr
  723. // If environment is not specified defaults to development.
  724. // 1) NODE=test elxr use elixir
  725. /*// Steps
  726. 1) Delete Config and Data symlinks
  727. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  728. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  729. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  730. 5) Iterates all repos and merge from source configured in mergeSource. 'git', ['merge', mergeSource],
  731. */
  732. var runconfig = { NODE_ENV : process.env.NODE_ENV }
  733. try { runconfig = Object.assign(runconfig, require('../run.js')) } catch(e) { }
  734. if((!processedArgs.runas || processedArgs.runas !== 'self') &&
  735. runconfig.NODE_ENV && runconfig.NODE_ENV === (process.env.NODE_ENV || runconfig.NODE_ENV) &&
  736. processedArgs._[1] && runconfig.use === processedArgs._[1]) {
  737. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  738. if(processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  739. return
  740. }
  741. var tasks = [
  742. ()=>{
  743. if(existsSync('config')) {
  744. var p = nodeShellExec('rmdir', ['config'], {inherit : true, shell: true, env: process.env }
  745. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  746. return p;
  747. }
  748. else return Promise.resolve(true);
  749. },
  750. ()=>{
  751. if(existsSync('data')) {
  752. var p = nodeShellExec('rmdir', ['data'], { inherit : true, shell: true, env: process.env }
  753. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  754. return p;
  755. }
  756. else return Promise.resolve(true);
  757. },
  758. ];
  759. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  760. if(processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  761. if(!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  762. // console.log(process.env.cwd)
  763. fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
  764. var checkoutMap = {
  765. 'development' : 'master',
  766. }
  767. // cant use git checkout -b it fails with branch already exists.
  768. var performCheckout = (repo, branch)=>{
  769. if(!branch) return Promise.resolve({ 'skipped' : true })
  770. if(excludeCheckouts[repo]) return Promise.resolve({ 'skipped' : true })
  771. return nodeShellExec('git', ['checkout', branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  772. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  773. // inherit : true, shell: true,
  774. cwd : repo
  775. // , stdio : ignore // Use when we want to silcence output completely.
  776. , runas : processedArgs.runas
  777. , title : `git checkout ${branch ||checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${repo}`
  778. }).catch((e)=>{ console.error(e); return { error : true, message : repo} })
  779. }
  780. if(runconfig.NODE_ENV === 'development') performCheckout = ()=>{ return Promise.resolve(true) }
  781. var performPullAll = (repo)=>{
  782. if(excludeCheckouts[repo]) return Promise.resolve({ 'skipped' : true })
  783. return nodeShellExec('git', ['pull', '--all'], {
  784. // inherit : true, shell: true,
  785. cwd : repo
  786. , runas : processedArgs.runas
  787. , title : `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${repo}`
  788. }).catch((e)=>{ console.error(e); return { error : true, message : repo} })
  789. }
  790. var mergeSources = {
  791. 'development' : null,
  792. 'test' : 'master',
  793. 'production' : 'master'
  794. }
  795. var exludeMergeRepos = {
  796. 'elixir-config-development' : true, 'elixir-config-test': true, 'elixir-config-production' : true
  797. , 'elixir-data' : true
  798. ,'cihsr-config-development' : true, 'cihsr-config-test': true, 'cihsr-config-production' : true
  799. , 'cihsr-data' : true
  800. }
  801. var excludeCheckouts = Object.assign(exludeMergeRepos)
  802. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  803. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  804. var mergeSource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  805. var performMerge = (repo)=>{
  806. if(exludeMergeRepos[repo]) return Promise.resolve({ 'skipped' : true })
  807. return nodeShellExec('git', ['merge', mergeSource], {
  808. inherit : true, shell: true,
  809. cwd : repo
  810. , runas : processedArgs.runas
  811. }).catch((e)=>{ console.error(e) })
  812. }
  813. if(runconfig.NODE_ENV === 'development') performMerge = ()=>{ return Promise.resolve(true) }
  814. any(tasks).then(()=>{
  815. if(!processedArgs.runas) return op['runas']()
  816. tasks = [
  817. ()=>{
  818. // Use junctions to avoid npm package issues
  819. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV ], {
  820. inherit : true, shell: true
  821. , env: process.env
  822. }).catch((e)=>{ console.error(e) })
  823. return p;
  824. }
  825. ];
  826. if(processedArgs._[1]) {
  827. tasks = tasks.concat(
  828. [
  829. ()=>{
  830. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  831. inherit : true, shell: true
  832. , env: process.env
  833. }).catch((e)=>{ console.error(e) })
  834. return p;
  835. }
  836. ]
  837. )
  838. }
  839. return any(tasks)
  840. //target is the env is we specify in elxr use command. Default is dev
  841. .then( //Switch to target branch
  842. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))
  843. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))]) )
  844. .then( //PULL from target branch
  845. () => any([ any(gitRepos.map((repo)=>performPullAll(repo))), any(elevatedRunasRepos.map((repo)=>performPullAll(repo)))]) )
  846. .then( //Switch to merge source branch
  847. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'] )))
  848. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'])))]) )
  849. .then( //Pull on merge source branch
  850. () => any([ any(gitRepos.map((repo)=>performPullAll(repo))), any(elevatedRunasRepos.map((repo)=>performPullAll(repo)))]) )
  851. .then( //Switch to target branch
  852. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))
  853. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))]) )
  854. .then( //Merge source branch to target branch
  855. () => any([ any(gitRepos.map((repo)=>performMerge(repo))).catch(err=>{ console.error('error in performMerge ' + err)}) ,
  856. any(elevatedRunasRepos.map((repo)=>performMerge(repo))).catch(err=>{ console.error('error in performMerge ' + err)})]) )
  857. .then( () => {
  858. // Move test config from dev.
  859. // if(process.env.NODE_ENV === 'test'){
  860. // var devcfgreponame = runconfig.use + '-config' + '-development';
  861. // var testcfgreponame = runconfig.use + '-config' + '-test';
  862. // var testcfgdir = path.dirname(__dirname) + '/' + testcfgreponame + '/'
  863. // var devcfgdir = path.dirname(__dirname) + '/' + devcfgreponame + '/' //eg (elxr/../elixir-config.development)
  864. // return any([
  865. // ()=>{
  866. // return nodeShellExec('git', ['checkout', 'test'], {
  867. // inherit : true, shell: true,
  868. // cwd : testcfgdir
  869. // // , env: process.env
  870. // , runas : processedArgs.runas
  871. // , title : `git checkout test for ${testcfgreponame}`
  872. // }).catch((e)=>{ console.error(e) })
  873. // }
  874. // , ()=> {
  875. // return nodeShellExec('git', ['checkout', 'master'], {
  876. // inherit : true, shell: true,
  877. // cwd : devcfgdir
  878. // // , env: process.env
  879. // , runas : processedArgs.runas
  880. // , title : `git checkout master for ${devcfgreponame}`
  881. // }).catch((e)=>{ console.error(e) })
  882. // }
  883. // , ()=> {
  884. // globSync( '**/*.test.js', {cwd : devcfgdir}).map((filename) => {
  885. // console.log('File found : ' + devcfgdir + filename)
  886. // fs.copyFileSync(devcfgdir + filename, testcfgdir+ filename);
  887. // })
  888. // return nodeShellExec('git', ['checkout', 'test'], {
  889. // inherit : true, shell: true,
  890. // cwd : devcfgdir
  891. // // , env: process.env
  892. // , runas : processedArgs.runas
  893. // , title : `git checkout test for ${devcfgreponame}`
  894. // }).catch((e)=>{ console.error(e) })
  895. // }
  896. // ])
  897. // }
  898. // else {
  899. return Promise.resolve(true)
  900. // }
  901. })
  902. .then(()=>{
  903. fs.writeFileSync('run.done', 'success')
  904. }).catch(()=>{
  905. fs.writeFileSync('run.done', 'error')
  906. })
  907. }).catch(()=>{
  908. fs.writeFileSync('run.done', 'error')
  909. })
  910. // Antibiotic stewardship program.
  911. // 1st use is fine.
  912. // Max vials dispense
  913. // 2nd use Pharmacy needs justification Form.
  914. // Approval after a certain period of time.
  915. }
  916. , 'g' : ()=>{
  917. if(processedArgs.h) {
  918. console.log('elxr g [modelname] => generate a model named [modelname]');
  919. console.log('elxr g => regenerate all known models');
  920. return
  921. }
  922. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  923. // console.log('Starting directory: ' + process.cwd());
  924. // try {
  925. // child = child.on('close', () => { process.chdir(label) } );
  926. // console.log('New directory: ' + process.cwd());
  927. // }
  928. // catch (err) {
  929. // console.log('chdir: ' + err);
  930. // }
  931. // child.on('close', function(){
  932. // var options = {
  933. // shell : true
  934. // , inherit : true
  935. // // , cwd : '' + process.cwd
  936. // // , env : process.env
  937. // };
  938. // nodeShellExec('git', ['init'], { inherit : true});
  939. if(0){
  940. // PB : TODO -- Special google chrome profile for tests etc.
  941. nodeShellExec('pwd', { inherit : true});
  942. //$ "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 1" http://localhost:4200/tests/index.html?grep=loopback
  943. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  944. "--profile-directory=Profile 1"
  945. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  946. }
  947. // nodeShellExec('npm', ['init', '-y'], options);
  948. // nodeShellExec('npm', ['init', '-y'], options);
  949. // })
  950. var g = {
  951. 'client' : ()=>{
  952. console.info('Creating new ember client named : ' + processedArgs._[2] ) ;
  953. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  954. stdio: ['pipe', process.stdout, process.stderr],
  955. inherit : true,
  956. shell: true,
  957. cwd : path.dirname(__dirname),
  958. env: env
  959. })
  960. }
  961. }
  962. g[processedArgs._[1]]();
  963. }
  964. }
  965. return op[label] ? op[label]() : null;
  966. }
  967. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  968. // mysql -u root -p db_name < drop_all_tables.sql
  969. var mysql = '../xampp/mysql/bin/mysql'
  970. var mysqldump = '../xampp/mysql/bin/mysqldump'
  971. // --runas
  972. if(processedArgs.runas) {
  973. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  974. __runcmd('runas')
  975. }
  976. else __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  977. function nodeShellExec() {
  978. var args = Array.from(arguments);
  979. var opts = args[2] = args[2] || {}
  980. opts.title ? null : opts.title = `${args[0]} ${args[1] }`
  981. const child = spawn(...arguments);
  982. var p = new Promise(function(resolve, reject){
  983. if(!opts.detached) {
  984. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  985. var success = true;
  986. if(opts.stdio !== 'ignore') {
  987. child.stdout.setEncoding('utf8');
  988. child.stderr.setEncoding('utf8');
  989. child.stdout.on('data', (chunk) => { chunk.trim() === '' ? null : messages.push(chunk); /* console.log('d: ' + chunk) */ });
  990. child.on('error', (chunk) => { success = false; messages.push(chunk); /* console.error('e: ' + chunk) */ } );
  991. child.stderr.on('data', (chunk) => { messages.push(chunk);
  992. // console.error('stderr e: ' + chunk)
  993. });
  994. }
  995. child.on('close', (code) => {
  996. if(+code !== 0) success = false;
  997. if(opts.stdio !== 'ignore') {
  998. if(opts.runas){
  999. var logEntry = { result: `${opts.title} exited with code ${code}`, messages : messages }
  1000. success ? logEntry.success = true : null;
  1001. fs.writeFileSync('run.log', ', ' + JSON.stringify(logEntry), {'flag':'a+'} )
  1002. }
  1003. else {
  1004. success ? console.log(['success : ' + ` ${opts.title} exited with code ${code}`]) : console.error([`error : ${opts.title} exited with code ${code}`])
  1005. // console.log( messages.join('') )
  1006. process.stdout.write( messages.join('') )
  1007. }
  1008. }
  1009. if(code !== 0) return reject(code)
  1010. resolve(messages)
  1011. });
  1012. }
  1013. else {
  1014. child.unref()
  1015. resolve(true);
  1016. }
  1017. });
  1018. p.process = child;
  1019. return p;
  1020. }