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

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