555
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 25KB

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