Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

index.js 25KB

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