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.

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