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 46KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253
  1. // 'use strict';
  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. , 'https://git.bbh.org.in'
  26. , '//172.16.0.27/repos'
  27. ]
  28. var defaultRepoServer = reposervers[1]
  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 exludeMergeRepos = {
  168. 'elixir-config-development' : true, 'elixir-config-test': true, 'elixir-config-production' : true
  169. , 'elixir-data' : true
  170. ,'cihsr-config-development' : true, 'cihsr-config-test': true, 'cihsr-config-production' : true
  171. , 'cihsr-data' : true
  172. }
  173. var productionRepos = [
  174. 'elixir-config-production'
  175. ]
  176. var productionIsAllowed = true;
  177. if(productionIsAllowed) gitRepos = gitRepos.concat(productionRepos)
  178. var env = Object.assign({}, process.env); // Shallow clone it.
  179. var __runcmd = function(label){
  180. var op = {
  181. 'h' : ()=>{ console.log(cli + ' ' + ver + ' ' + help); return '-h' }
  182. , 'undefined' : ()=>{ return op.h(); }
  183. , 'reset' : ()=>{
  184. // Reset NPM packages semver so major versions can be updated.
  185. const fs = require('fs')
  186. const wipeDependencies = (package) => {
  187. const file = fs.readFileSync(package + '/package.json')
  188. const content = JSON.parse(file)
  189. for (var devDep in content.devDependencies) {
  190. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  191. content.devDependencies[devDep] = '*';
  192. }
  193. }
  194. for (var dep in content.dependencies) {
  195. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  196. content.dependencies[dep] = '*';
  197. }
  198. }
  199. fs.writeFileSync(package + '/package.json', JSON.stringify(content))
  200. }
  201. var repos = ['client'];
  202. // repos = gitRepos;
  203. repos.forEach(wipeDependencies)
  204. // if (require.main === module) {
  205. // } else {
  206. // module.exports = wipeDependencies
  207. // }
  208. }
  209. , 'upgrade' : ()=>{
  210. console.log('upgrade.......')
  211. var tasks = [
  212. ()=>{
  213. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  214. inherit : true, shell: true
  215. , env: process.env
  216. }).catch((e)=>{ console.error(e) })
  217. p.position = 1;
  218. console.log('One')
  219. return p;
  220. }
  221. , ()=>{
  222. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  223. inherit : true, shell: true
  224. , env: process.env
  225. }).catch((e)=>{ console.error(e) })
  226. p.position = 2;
  227. console.log('Two')
  228. return p;
  229. }
  230. , ()=>{
  231. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  232. inherit : true, shell: true
  233. , env: process.env
  234. }).catch((e)=>{ console.error(e) })
  235. p.position = 3;
  236. console.log('Three')
  237. return p;
  238. }
  239. , ()=>{
  240. var p = nodeShellExec('n', ['latest'], {
  241. inherit : true, shell: true
  242. , env: process.env
  243. }).catch((e)=>{ console.error(e) })
  244. p.position = 4;
  245. console.log('Four')
  246. return p;
  247. }
  248. ]
  249. any(tasks)
  250. console.log('.......done')
  251. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  252. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  253. console.info('Uninstalling existing ember globally') ;
  254. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  255. stdio: ['pipe', process.stdout, process.stderr],
  256. inherit : true,
  257. shell: true,
  258. cwd : path.dirname(__dirname),
  259. env: env
  260. })
  261. step1.on('close', ()=>{
  262. console.info('Installing ember globally') ;
  263. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  264. stdio: ['pipe', process.stdout, process.stderr],
  265. inherit : true,
  266. shell: true,
  267. cwd : path.dirname(__dirname),
  268. env: env
  269. })
  270. step2.on('close', ()=>{
  271. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  272. stdio: ['pipe', process.stdout, process.stderr],
  273. inherit : true,
  274. shell: true,
  275. cwd : path.dirname(__dirname),
  276. env: env
  277. })
  278. })
  279. })
  280. }
  281. , 'runas' : ()=>{
  282. console.log('Testing Elevation')
  283. return isRunningElevated().then(
  284. (isElevated) => {
  285. if(isElevated) {
  286. try {
  287. op[ processedArgs.label || processedArgs._[0] || 'h']()
  288. }
  289. catch(e){
  290. console.error('Error Invalid command : ' + e)
  291. fs.writeFileSync('run.done', 'success')
  292. }
  293. finally {
  294. }
  295. } else throw false;
  296. }
  297. )
  298. .catch(()=>{
  299. console.log('Requesting Elevated Privileges');
  300. // Wait for the runas to complete before we read it.
  301. try {
  302. fs.unlinkSync('run.done')
  303. fs.unlinkSync('run.log')
  304. }
  305. catch(e) { } //Ignore
  306. // Find node path to send to hta.
  307. nodeShellExec('where', ['node']).then(r => {
  308. console.log('result : ' + r)
  309. // throw 'rrrrrrrrrrrrrrrrr'
  310. // PB : TODO -- Convert all the cli args back to string.
  311. var namedArgs = [];
  312. Object.keys(processedArgs).forEach((v)=>{ v!='_' ? namedArgs.push('--'+v+'='+processedArgs[v]) : null; })
  313. //console.log(' namedArgs : ' + namedArgs)
  314. process.env.NODE_ENV = process.env.NODE_ENV || 'development';
  315. var args = [__dirname + '/windowselevate.hta'].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  316. args.push('--nodepath='+r[r.length-1])
  317. nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  318. , {
  319. inherit : true
  320. , shell: true
  321. , env: process.env
  322. , runas : 'self'
  323. , title : `runas`
  324. }
  325. ).then(()=>{
  326. // runas returned.
  327. try {
  328. var runaslog = JSON.parse('[ { "success" : true, "result" : "runas Log" }' + fs.readFileSync('run.log', { flags : 'a+'}) + ']');
  329. runaslog.forEach((logEntry)=>{
  330. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  331. })
  332. }
  333. catch(e){
  334. // Ignore nonexistent log
  335. console.warn('Run log error probably was not created by runas : ' + e)
  336. }
  337. })
  338. .catch(err => console.error('Elevation failed : ' + err));
  339. })
  340. })
  341. }
  342. , 'push' : ()=>{
  343. if(!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  344. // init remote bare from local
  345. // pushandinitremotebare
  346. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  347. // connect to repo server -- net use 172.16.0.27
  348. // cd 172.16.0.27/repos/
  349. // mkdir repo.git
  350. // cd repo.git
  351. // git init --bare
  352. // cd localrepo
  353. // git remote rename origin githubclone
  354. // git remote add origin //172.16.0.27/repos/repo.git
  355. // git push origin master
  356. var repo = processedArgs._[1];
  357. var sequentialTaskShellCommands = [];
  358. if(!existsSync(`Z:/${repo}.git`)){
  359. sequentialTaskShellCommands = [
  360. // ['net', ['use', 'Z:', defaultRepoServer.replace('/','\\')], {
  361. // inherit : true, shell: true
  362. // , env: process.env
  363. // }]
  364. ['pwd', { cwd : 'Z:', inherit : true}]
  365. , ['mkdir', [`${repo}.git`], {
  366. cwd : `Z:`
  367. , inherit : true, shell: true
  368. , env: process.env
  369. }]
  370. , ['pwd', { cwd : `Z:/${repo}.git`, inherit : true}]
  371. , ['git', ['init', '--bare'], { cwd : `Z:/${repo}.git`
  372. , inherit : true, shell: true
  373. , env: process.env
  374. }]
  375. // PB : TODO -- Do this conditionally only...
  376. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd : `${repo}`}, (err)=>{
  377. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  378. } ] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  379. , ['git', ['remote', 'add', 'origin', `${defaultRepoServer}/${repo}.git`], { cwd : `${repo}`}]
  380. // PB : TODO -- If threre is a gitbubclone origin
  381. // Set the master to pull from the local repo.
  382. ]
  383. if(!existsSync(`Z:`)){
  384. sequentialTaskShellCommands.splice(0,0, ['net', ['use', 'Z:', defaultRepoServer.replace(/\//gm,'\\')], {
  385. inherit : true, shell: true
  386. , env: process.env
  387. }])
  388. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  389. // throw 'done'
  390. }
  391. }
  392. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd : `${repo}`}])
  393. // console.dir(sequentialTaskShellCommands);
  394. var tasks = [];
  395. sequentialTaskShellCommands.forEach(shellcmd => {
  396. // console.log(shellcmd)
  397. tasks.push(()=>{
  398. var p = nodeShellExec.apply(null, shellcmd.slice(0,3)).catch((e)=>{ if(shellcmd[3]) { return shellcmd[3]() } else { console.error(e);} })
  399. return p;
  400. })
  401. })
  402. any(tasks);
  403. }
  404. , 'is-git-repo' : (dir)=>{
  405. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio : 'ignore'})
  406. }
  407. , 'set-url' : (remotename, url) => {
  408. var pushable = processedArgs.pushable || false;
  409. remotename = remotename || processedArgs._[1]
  410. url = url || processedArgs._[2]
  411. var serial_perform_git_seturl = (repo)=>{
  412. var options = { cwd : repo }
  413. // console.log(repo)
  414. if(pushable) {
  415. return [
  416. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd : repo }]
  417. ]
  418. }
  419. else {
  420. console.error('not supported for non-pushable')
  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_seturl = (dir)=>{
  431. op['is-git-repo'](dir).then((code)=>{
  432. any( serial_perform_git_seturl(dir.name).map(x) )
  433. }).catch((e)=>{
  434. // console.log('Failed : ' + dir.name)
  435. })
  436. }
  437. const { readdir } = require("fs").promises
  438. const dirs = async (perform, path) => {
  439. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  440. if (dir.isDirectory()) perform(dir)
  441. }
  442. }
  443. dirs( perform_git_seturl)
  444. }
  445. , 'add' : (remotename, url, branch) => {
  446. var pushable = processedArgs.pushable || false;
  447. remotename = remotename || processedArgs._[1]
  448. url = url || processedArgs._[2]
  449. branch = branch || processedArgs._[3]
  450. var serial_perform_git_add = (repo)=>{
  451. var options = { cwd : repo }
  452. // console.log(repo)
  453. if(pushable) {
  454. return [
  455. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd : repo }]
  456. , ['git', ['pull', remotename, branch], { cwd : repo }]
  457. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd : repo }]
  458. ]
  459. }
  460. else {
  461. return [
  462. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd : repo }]
  463. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd : repo }]
  464. , ['git', ['pull', remotename, branch], { cwd : repo }]
  465. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd : repo }]
  466. ]
  467. }
  468. }
  469. var x = (args)=>{
  470. return ()=>{
  471. // console.log(args)
  472. return nodeShellExec.apply(null, args)
  473. }
  474. // return Promise.resolve(true)
  475. }
  476. var perform_git_add = (dir)=>{
  477. op['is-git-repo'](dir).then((code)=>{
  478. // console.log(code)
  479. if(code) {
  480. nodeShellExec('git',['remote', 'get-url', remotename], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  481. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  482. })
  483. .catch((e)=>{
  484. any( serial_perform_git_add(dir.name).map(x) )
  485. })
  486. }
  487. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  488. }).catch((e)=>{
  489. // console.log('Failed : ' + dir.name)
  490. })
  491. }
  492. const { readdir } = require("fs").promises
  493. const dirs = async (perform, path) => {
  494. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  495. if (dir.isDirectory()) perform(dir)
  496. }
  497. }
  498. dirs(perform_git_add)
  499. }
  500. , 'remove' : (remotename) => {
  501. remotename = remotename || processedArgs._[1]
  502. var serial_perform_git_remove = (repo)=>{
  503. var options = { cwd : repo }
  504. // console.log(repo)
  505. return [
  506. ['git', ['remote', 'remove', remotename], { cwd : repo }]
  507. ]
  508. }
  509. var x = (args)=>{
  510. return ()=>{
  511. // console.log(args)
  512. return nodeShellExec.apply(null, args)
  513. }
  514. // return Promise.resolve(true)
  515. }
  516. var perform_git_remove = (dir)=>{
  517. op['is-git-repo'](dir).then((code)=>{
  518. // console.log(code)
  519. if(code) {
  520. nodeShellExec('git',['remote', 'get-url', remotename], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  521. any( serial_perform_git_remove(dir.name).map(x) )
  522. })
  523. .catch((e)=>{
  524. console.log('skipped : ' + dir.name + ', reason : No remote named origin')
  525. })
  526. }
  527. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  528. }).catch((e)=>{
  529. // console.log('Failed : ' + dir.name)
  530. })
  531. }
  532. const { readdir } = require("fs").promises
  533. const dirs = async (perform, path) => {
  534. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  535. if (dir.isDirectory()) perform(dir)
  536. }
  537. }
  538. dirs(perform_git_remove)
  539. }
  540. , 'init-gitea' : (user) => {
  541. user = user || processedArgs._[1]
  542. if(!user) throw 'User name required'
  543. var serial_perform_init_gitea = (repo)=>{
  544. var options = { cwd : repo }
  545. // console.log(repo)
  546. return [
  547. ['git', ['remote', 'add', 'chess', 'http://git.bbh/chess/elxr.git'], { cwd : repo }]
  548. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd : repo }]
  549. , ['git', ['remote', 'set-url', 'origin', `http://git.bbh/${user}/${repo}.git`], { cwd : repo }]
  550. ]}
  551. var x = (args)=>{
  552. return ()=>{
  553. // console.log(args)
  554. return nodeShellExec.apply(null, args)
  555. }
  556. // return Promise.resolve(true)
  557. }
  558. var perform_init_gitea = (dir)=>{
  559. op['is-git-repo'](dir).then((code)=>{
  560. // console.log(code)
  561. if(code) {
  562. nodeShellExec('git',['remote', 'get-url', 'chess'], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  563. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  564. })
  565. .catch((e)=>{
  566. any( serial_perform_init_gitea(dir.name).map(x) )
  567. })
  568. }
  569. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  570. }).catch((e)=>{
  571. // console.log('Failed : ' + dir.name)
  572. })
  573. }
  574. const { readdir } = require("fs").promises
  575. const dirs = async (perform, path) => {
  576. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  577. if (dir.isDirectory()) perform(dir)
  578. }
  579. }
  580. dirs(perform_init_gitea)
  581. }
  582. , 'syncmaster' : (label) => {
  583. // Usage :
  584. // elxr pull -- Defaults to run config
  585. var env = Object.assign({}, process.env); // Shallow clone it.
  586. // console.dir(env)
  587. console.log('Running exlr pull : ' + path.dirname(__dirname))
  588. // nodeShellExec('cmd', ['/c', 'setup\\utility\\chess.bat', 'pull'], {
  589. // // nodeShellExec('cmd', ['/c', '..\\setup\\utility\\chess.bat', 'pull'], {
  590. // stdio: ['pipe', process.stdout, process.stderr],
  591. // inherit : true,
  592. // shell: true,
  593. // cwd : path.dirname(__dirname),
  594. // env: env
  595. // })
  596. var useGitPull = processedArgs.useGitPull || false;
  597. var getPullCmd = (repo)=>{
  598. // console.log(useGitPull)
  599. var pullCmd = [ gitInstallDir
  600. , ['-c', 'for i in `git remote`; do git pull $i master; done;']
  601. , { cwd : repo, title : 'pull all origins for ' + repo }]
  602. // var pullCmd = ['pullall', [], { cwd : repo }]
  603. if(useGitPull) pullCmd = ['git', ['pull'], {
  604. inherit : true, shell: true,
  605. cwd : repo
  606. // , env: process.env
  607. , runas : processedArgs.runas
  608. , title : `git pull ${repo}`
  609. }]
  610. return pullCmd
  611. }
  612. var performPull = (repo) => {
  613. if(exludeMergeRepos[repo]) return Promise.resolve({ 'skipped' : true })
  614. if(existsSync(repo)) {
  615. console.log('pulling ' + repo)
  616. return nodeShellExec.apply(null, getPullCmd(repo)).catch((e)=>{ console.error(e) })
  617. }
  618. else {
  619. console.log('cloning ' + repo)
  620. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  621. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', defaultRepoServer + `/${defaultRepoOwner}/` + repo + '.git'],
  622. {
  623. inherit : true, shell: true,
  624. env: process.env
  625. , runas : processedArgs.runas
  626. }).catch((e)=>{ console.error(e) }).then(()=>{
  627. return nodeShellExec('git', ['config', '--replace-all' , 'core.symlinks', true],
  628. {
  629. inherit : true, shell: true,
  630. env: process.env
  631. , cwd : repo
  632. , runas : processedArgs.runas
  633. , title : `git core.symlinks --replace-all true for ${defaultRepoServer + `/${defaultRepoOwner}/` + repo + '.git'}`
  634. })
  635. })
  636. }
  637. }
  638. if(!processedArgs.runas) gitRepos.forEach(performPull)
  639. return isRunningElevated().then(
  640. (isElevated) => {
  641. if(isElevated) {
  642. any(elevatedRunasRepos.map((repo)=>performPull(repo))).then(()=>{
  643. fs.writeFileSync('run.done', 'success')
  644. }).catch(()=>{
  645. fs.writeFileSync('run.done', 'error')
  646. })
  647. }
  648. else throw false;
  649. }
  650. ).catch(
  651. () => {
  652. op['runas']()
  653. }
  654. )
  655. }
  656. , 'pull' : (label) => {
  657. // Usage :
  658. // elxr pull -- Defaults to run config
  659. var env = Object.assign({}, process.env); // Shallow clone it.
  660. // console.dir(env)
  661. console.log('Running exlr pull : ' + path.dirname(__dirname))
  662. // nodeShellExec('cmd', ['/c', 'setup\\utility\\chess.bat', 'pull'], {
  663. // // nodeShellExec('cmd', ['/c', '..\\setup\\utility\\chess.bat', 'pull'], {
  664. // stdio: ['pipe', process.stdout, process.stderr],
  665. // inherit : true,
  666. // shell: true,
  667. // cwd : path.dirname(__dirname),
  668. // env: env
  669. // })
  670. var useGitPull = processedArgs.useGitPull || false;
  671. var getPullCmd = (repo)=>{
  672. // console.log(useGitPull)
  673. var pullCmd = [ gitInstallDir
  674. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  675. , { cwd : repo, title : 'pull all origins for ' + repo }]
  676. // var pullCmd = ['pullall', [], { cwd : repo }]
  677. if(useGitPull) pullCmd = ['git', ['pull'], {
  678. inherit : true, shell: true,
  679. cwd : repo
  680. // , env: process.env
  681. , runas : processedArgs.runas
  682. , title : `git pull ${repo}`
  683. }]
  684. return pullCmd
  685. }
  686. var errors = [];
  687. var performPull = (repo) => {
  688. if(existsSync(repo)) {
  689. console.log('pulling ' + repo)
  690. return nodeShellExec.apply(null, getPullCmd(repo)).catch((e)=>{
  691. errors.push({ repo , e})
  692. console.error(e) })
  693. }
  694. else {
  695. console.log('cloning ' + repo)
  696. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  697. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', defaultRepoServer + `/${defaultRepoOwner}/` + repo + '.git'],
  698. {
  699. inherit : true, shell: true,
  700. env: process.env
  701. , runas : processedArgs.runas
  702. }).catch((e)=>{
  703. errors.push({ repo , e})
  704. console.error(e)
  705. }).then(()=>{
  706. return nodeShellExec('git', ['config', '--replace-all' , 'core.symlinks', true],
  707. {
  708. inherit : true, shell: true,
  709. env: process.env
  710. , cwd : repo
  711. , runas : processedArgs.runas
  712. , title : `git core.symlinks --replace-all true for ${defaultRepoServer + `/${defaultRepoOwner}/` + repo + '.git'}`
  713. })
  714. })
  715. }
  716. }
  717. if(!processedArgs.runas) gitRepos.forEach(performPull)
  718. return isRunningElevated().then(
  719. (isElevated) => {
  720. if(isElevated) {
  721. any(elevatedRunasRepos.map((repo)=>performPull(repo))).then(()=>{
  722. fs.writeFileSync('run.done', 'success')
  723. }).catch(()=>{
  724. fs.writeFileSync('run.done', 'error')
  725. })
  726. }
  727. else throw false;
  728. }
  729. ).catch(
  730. () => {
  731. op['runas']()
  732. }
  733. )
  734. }
  735. , 'isInstalled' : ()=>{
  736. return nodeShellExec('where', [processedArgs._[1]], { inherit : true} ).then(()=>{
  737. console.log(processedArgs._[1] + ' exists.')
  738. return true;
  739. });
  740. }
  741. , 'npmi' : ()=>{
  742. var tasks = [];
  743. gitRepos.forEach(repo => {
  744. console.log('npm i for ' + repo)
  745. // nodeShellExec('pwd', [], {
  746. // // inherit : true, shell: true
  747. // cwd : repo
  748. // // , env: process.env
  749. // , title : `pwd for ${repo}`
  750. // }).catch((e)=>{ console.error(e) })
  751. nodeShellExec('rm', ['package-lock.json'], {
  752. inherit : true, shell: true
  753. , cwd : repo
  754. , env: process.env
  755. , title : `rm 'package-lock.json' for ${repo}`
  756. }).catch((e)=>{ console.error(e) })
  757. tasks.push(()=>{
  758. var p = nodeShellExec('npm', ['i'], {
  759. inherit : true, shell: true
  760. , cwd : repo
  761. , env: process.env
  762. , title : `npm i for ${repo}`
  763. }).catch((e)=>{ console.error(e) })
  764. return p;
  765. })
  766. })
  767. any(tasks);
  768. }
  769. , 'start' : (label)=>{
  770. console.log('Starting Elixir Server.');
  771. var env = Object.assign({}, process.env); // Shallow clone it.
  772. // console.dir(env)
  773. env.NODE_ENV = process.env.NODE_ENV || 'development';
  774. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  775. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  776. // cmd = 'node'
  777. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
  778. var childPromise = nodeShellExec(...cmd, {
  779. // inherit : true,
  780. shell: true,
  781. detached: true,
  782. stdio: 'ignore',
  783. cwd : 'elixir-server'
  784. , env: env
  785. })
  786. var child = childPromise.process;
  787. if (typeof child.pid !== 'undefined') {
  788. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  789. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  790. encoding: 'utf8'
  791. })
  792. }
  793. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  794. // inherit : true,
  795. // shell: true, detached: true,
  796. // cwd : 'qms/server',
  797. // env: env,
  798. // shell : true
  799. // })
  800. // nodeShellExec('ember', ['s'], {
  801. // // inherit : true,
  802. // shell: true, detached: true,
  803. // cwd : 'client/',
  804. // env: env
  805. // })
  806. console.log('Starting Elixir Client Host.');
  807. var cmd = ['ember', ['s']]
  808. var childPromise = nodeShellExec(...cmd, {
  809. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  810. // PB : TODO -- ember debugging.
  811. // inherit : true,
  812. shell: true,
  813. detached: true,
  814. stdio: 'ignore',
  815. cwd : 'client'
  816. , env: env
  817. })
  818. // .catch(e=>console.error(e))
  819. child = childPromise.process;
  820. if (typeof child.pid !== 'undefined') {
  821. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  822. fs.writeFileSync('.client.server.pid', child.pid, {
  823. encoding: 'utf8'
  824. })
  825. }
  826. }
  827. , 'stop' : (label)=>{
  828. const kill = require('tree-kill');
  829. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  830. encoding: 'utf8'
  831. })
  832. fs.unlinkSync('.elixir-server.elixir.server.pid')
  833. console.log(serverPid)
  834. kill(serverPid)
  835. serverPid = fs.readFileSync('.client.server.pid', {
  836. encoding: 'utf8'
  837. })
  838. fs.unlinkSync('.client.server.pid')
  839. console.log(serverPid)
  840. kill(serverPid)
  841. }
  842. , 'use' : ()=>{
  843. // use a certain named instance.
  844. // Eg :
  845. // 1) elxr use elixir
  846. // 2) elxr use cihsr
  847. // If environment is not specified defaults to development.
  848. // 1) NODE=test elxr use elixir
  849. /*// Steps
  850. 1) Delete Config and Data symlinks
  851. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  852. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  853. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  854. 5) Iterates all repos and merge from source configured in mergeSource. 'git', ['merge', mergeSource],
  855. */
  856. var runconfig = { NODE_ENV : process.env.NODE_ENV }
  857. try { runconfig = Object.assign(runconfig, require('../run.js')) } catch(e) { }
  858. if((!processedArgs.runas || processedArgs.runas !== 'self') &&
  859. runconfig.NODE_ENV && runconfig.NODE_ENV === (process.env.NODE_ENV || runconfig.NODE_ENV) &&
  860. processedArgs._[1] && runconfig.use === processedArgs._[1]) {
  861. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  862. if(processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  863. return
  864. }
  865. var tasks = [
  866. ()=>{
  867. if(existsSync('config')) {
  868. var p = nodeShellExec('rmdir', ['config'], {inherit : true, shell: true, env: process.env }
  869. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  870. return p;
  871. }
  872. else return Promise.resolve(true);
  873. },
  874. ()=>{
  875. if(existsSync('data')) {
  876. var p = nodeShellExec('rmdir', ['data'], { inherit : true, shell: true, env: process.env }
  877. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  878. return p;
  879. }
  880. else return Promise.resolve(true);
  881. },
  882. ];
  883. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  884. if(processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  885. if(!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  886. // console.log(process.env.cwd)
  887. fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
  888. var checkoutMap = {
  889. 'development' : 'master',
  890. }
  891. // cant use git checkout -b it fails with branch already exists.
  892. var performCheckout = (repo, branch)=>{
  893. if(!branch) return Promise.resolve({ 'skipped' : true })
  894. if(excludeCheckouts[repo]) return Promise.resolve({ 'skipped' : true })
  895. return nodeShellExec('git', ['checkout', branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  896. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  897. // inherit : true, shell: true,
  898. cwd : repo
  899. // , stdio : ignore // Use when we want to silcence output completely.
  900. , runas : processedArgs.runas
  901. , title : `git checkout ${branch ||checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${repo}`
  902. }).catch((e)=>{ console.error(e); return { error : true, message : repo} })
  903. }
  904. if(runconfig.NODE_ENV === 'development') performCheckout = ()=>{ return Promise.resolve(true) }
  905. var performPullAll = (repo)=>{
  906. if(excludeCheckouts[repo]) return Promise.resolve({ 'skipped' : true })
  907. return nodeShellExec('git', ['pull', '--all'], {
  908. // inherit : true, shell: true,
  909. cwd : repo
  910. , runas : processedArgs.runas
  911. , title : `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${repo}`
  912. }).catch((e)=>{ console.error(e); return { error : true, message : repo} })
  913. }
  914. var mergeSources = {
  915. 'development' : null,
  916. 'test' : 'master',
  917. 'production' : 'master'
  918. }
  919. var excludeCheckouts = Object.assign(exludeMergeRepos)
  920. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  921. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  922. var mergeSource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  923. var performMerge = (repo)=>{
  924. if(exludeMergeRepos[repo]) return Promise.resolve({ 'skipped' : true })
  925. return nodeShellExec('git', ['merge', mergeSource], {
  926. inherit : true, shell: true,
  927. cwd : repo
  928. , runas : processedArgs.runas
  929. }).catch((e)=>{ console.error(e) })
  930. }
  931. if(runconfig.NODE_ENV === 'development') performMerge = ()=>{ return Promise.resolve(true) }
  932. any(tasks).then(()=>{
  933. if(!processedArgs.runas) return op['runas']()
  934. tasks = [
  935. ()=>{
  936. // Use junctions to avoid npm package issues
  937. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV ], {
  938. inherit : true, shell: true
  939. , env: process.env
  940. }).catch((e)=>{ console.error(e) })
  941. return p;
  942. }
  943. ];
  944. if(processedArgs._[1]) {
  945. tasks = tasks.concat(
  946. [
  947. ()=>{
  948. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  949. inherit : true, shell: true
  950. , env: process.env
  951. }).catch((e)=>{ console.error(e) })
  952. return p;
  953. }
  954. ]
  955. )
  956. }
  957. return any(tasks)
  958. //target is the env is we specify in elxr use command. Default is dev
  959. .then( //Switch to target branch
  960. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))
  961. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))]) )
  962. .then( //PULL from target branch
  963. () => any([ any(gitRepos.map((repo)=>performPullAll(repo))), any(elevatedRunasRepos.map((repo)=>performPullAll(repo)))]) )
  964. .then( //Switch to merge source branch
  965. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'] )))
  966. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'])))]) )
  967. .then( //Pull on merge source branch
  968. () => any([ any(gitRepos.map((repo)=>performPullAll(repo))), any(elevatedRunasRepos.map((repo)=>performPullAll(repo)))]) )
  969. .then( //Switch to target branch
  970. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))
  971. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))]) )
  972. .then( //Merge source branch to target branch
  973. () => any([ any(gitRepos.map((repo)=>performMerge(repo))).catch(err=>{ console.error('error in performMerge ' + err)}) ,
  974. any(elevatedRunasRepos.map((repo)=>performMerge(repo))).catch(err=>{ console.error('error in performMerge ' + err)})]) )
  975. .then( () => {
  976. // Move test config from dev.
  977. // if(process.env.NODE_ENV === 'test'){
  978. // var devcfgreponame = runconfig.use + '-config' + '-development';
  979. // var testcfgreponame = runconfig.use + '-config' + '-test';
  980. // var testcfgdir = path.dirname(__dirname) + '/' + testcfgreponame + '/'
  981. // var devcfgdir = path.dirname(__dirname) + '/' + devcfgreponame + '/' //eg (elxr/../elixir-config.development)
  982. // return any([
  983. // ()=>{
  984. // return nodeShellExec('git', ['checkout', 'test'], {
  985. // inherit : true, shell: true,
  986. // cwd : testcfgdir
  987. // // , env: process.env
  988. // , runas : processedArgs.runas
  989. // , title : `git checkout test for ${testcfgreponame}`
  990. // }).catch((e)=>{ console.error(e) })
  991. // }
  992. // , ()=> {
  993. // return nodeShellExec('git', ['checkout', 'master'], {
  994. // inherit : true, shell: true,
  995. // cwd : devcfgdir
  996. // // , env: process.env
  997. // , runas : processedArgs.runas
  998. // , title : `git checkout master for ${devcfgreponame}`
  999. // }).catch((e)=>{ console.error(e) })
  1000. // }
  1001. // , ()=> {
  1002. // globSync( '**/*.test.js', {cwd : devcfgdir}).map((filename) => {
  1003. // console.log('File found : ' + devcfgdir + filename)
  1004. // fs.copyFileSync(devcfgdir + filename, testcfgdir+ filename);
  1005. // })
  1006. // return nodeShellExec('git', ['checkout', 'test'], {
  1007. // inherit : true, shell: true,
  1008. // cwd : devcfgdir
  1009. // // , env: process.env
  1010. // , runas : processedArgs.runas
  1011. // , title : `git checkout test for ${devcfgreponame}`
  1012. // }).catch((e)=>{ console.error(e) })
  1013. // }
  1014. // ])
  1015. // }
  1016. // else {
  1017. return Promise.resolve(true)
  1018. // }
  1019. })
  1020. .then(()=>{
  1021. fs.writeFileSync('run.done', 'success')
  1022. }).catch(()=>{
  1023. fs.writeFileSync('run.done', 'error')
  1024. })
  1025. }).catch(()=>{
  1026. fs.writeFileSync('run.done', 'error')
  1027. })
  1028. // Antibiotic stewardship program.
  1029. // 1st use is fine.
  1030. // Max vials dispense
  1031. // 2nd use Pharmacy needs justification Form.
  1032. // Approval after a certain period of time.
  1033. }
  1034. , 'g' : ()=>{
  1035. if(processedArgs.h) {
  1036. console.log('elxr g [modelname] => generate a model named [modelname]');
  1037. console.log('elxr g => regenerate all known models');
  1038. return
  1039. }
  1040. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1041. // console.log('Starting directory: ' + process.cwd());
  1042. // try {
  1043. // child = child.on('close', () => { process.chdir(label) } );
  1044. // console.log('New directory: ' + process.cwd());
  1045. // }
  1046. // catch (err) {
  1047. // console.log('chdir: ' + err);
  1048. // }
  1049. // child.on('close', function(){
  1050. // var options = {
  1051. // shell : true
  1052. // , inherit : true
  1053. // // , cwd : '' + process.cwd
  1054. // // , env : process.env
  1055. // };
  1056. // nodeShellExec('git', ['init'], { inherit : true});
  1057. if(0){
  1058. // PB : TODO -- Special google chrome profile for tests etc.
  1059. nodeShellExec('pwd', { inherit : true});
  1060. //$ "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 1" http://localhost:4200/tests/index.html?grep=loopback
  1061. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1062. "--profile-directory=Profile 1"
  1063. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1064. }
  1065. // nodeShellExec('npm', ['init', '-y'], options);
  1066. // nodeShellExec('npm', ['init', '-y'], options);
  1067. // })
  1068. var g = {
  1069. 'client' : ()=>{
  1070. console.info('Creating new ember client named : ' + processedArgs._[2] ) ;
  1071. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1072. stdio: ['pipe', process.stdout, process.stderr],
  1073. inherit : true,
  1074. shell: true,
  1075. cwd : path.dirname(__dirname),
  1076. env: env
  1077. })
  1078. }
  1079. }
  1080. g[processedArgs._[1]]();
  1081. }
  1082. }
  1083. return op[label] ? op[label]() : null;
  1084. }
  1085. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  1086. // mysql -u root -p db_name < drop_all_tables.sql
  1087. var mysql = '../xampp/mysql/bin/mysql'
  1088. var mysqldump = '../xampp/mysql/bin/mysqldump'
  1089. // --runas
  1090. if(processedArgs.runas) {
  1091. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  1092. __runcmd('runas')
  1093. }
  1094. else __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  1095. function nodeShellExec() {
  1096. var args = Array.from(arguments);
  1097. var opts = args[2] = args[2] || {}
  1098. opts.title ? null : opts.title = `${args[0]} ${args[1] }`
  1099. const child = spawn(...arguments);
  1100. var p = new Promise(function(resolve, reject){
  1101. if(!opts.detached) {
  1102. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  1103. var success = true;
  1104. if(opts.stdio !== 'ignore') {
  1105. child.stdout.setEncoding('utf8');
  1106. child.stderr.setEncoding('utf8');
  1107. child.stdout.on('data', (chunk) => { chunk.trim() === '' ? null : messages.push(chunk); /* console.log('d: ' + chunk) */ });
  1108. child.on('error', (chunk) => { success = false; messages.push(chunk); /* console.error('e: ' + chunk) */ } );
  1109. child.stderr.on('data', (chunk) => { messages.push(chunk);
  1110. // console.error('stderr e: ' + chunk)
  1111. });
  1112. }
  1113. child.on('close', (code) => {
  1114. if(+code !== 0) success = false;
  1115. if(opts.stdio !== 'ignore') {
  1116. if(opts.runas){
  1117. var logEntry = { result: `${opts.title} exited with code ${code}`, messages : messages }
  1118. success ? logEntry.success = true : null;
  1119. fs.writeFileSync('run.log', ', ' + JSON.stringify(logEntry), {'flag':'a+'} )
  1120. }
  1121. else {
  1122. success ? console.log(['success : ' + ` ${opts.title} exited with code ${code}`]) : console.error([`error : ${opts.title} exited with code ${code}`])
  1123. // console.log( messages.join('') )
  1124. process.stdout.write( messages.join('') )
  1125. }
  1126. }
  1127. if(code !== 0) return reject(code)
  1128. resolve(messages)
  1129. });
  1130. }
  1131. else {
  1132. child.unref()
  1133. resolve(true);
  1134. }
  1135. });
  1136. p.process = child;
  1137. return p;
  1138. }