555
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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