Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

index.js 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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 globSync = require('glob').sync;
  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. , 'elixir-config-test'
  130. , 'cihsr-config'
  131. , 'cihsr-data'
  132. , 'elixir-data'
  133. , 'loopback-connector-ds'
  134. , 'chess-server-lib'
  135. , 'setup'
  136. , 'elixir-client-todos'
  137. , 'elixir-client-unlinked'
  138. , 'elixir-client'
  139. , 'ember-service-worker'
  140. , 'ember-service-worker-asset-cache'
  141. , 'ember-service-worker-cache-fallback'
  142. , 'ember-service-worker-index'
  143. , 'ember-sw-client-route'
  144. , 'global-this'
  145. ]
  146. // Repositiories that have symlinks that required elevated priviletes in windows to create symlinks
  147. //
  148. var elevatedRunasRepos = [
  149. 'elixir-server'
  150. , 'cihsr-server'
  151. , 'chess-server'
  152. ]
  153. var productionRepos = [
  154. 'elixir-config-production'
  155. ]
  156. var productionIsAllowed = true;
  157. if(productionIsAllowed) gitRepos = gitRepos.concat(productionRepos)
  158. var env = Object.assign({}, process.env); // Shallow clone it.
  159. var __runcmd = function(label){
  160. var op = {
  161. 'h' : ()=>{ console.log(cli + ' ' + ver + ' ' + help); return '-h' }
  162. , 'undefined' : ()=>{ return op.h(); }
  163. , 'upgrade' : ()=>{
  164. console.log('upgrade.......')
  165. var tasks = [
  166. ()=>{
  167. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  168. inherit : true, shell: true
  169. , env: process.env
  170. }).catch((e)=>{ console.error(e) })
  171. p.position = 1;
  172. console.log('One')
  173. return p;
  174. }
  175. , ()=>{
  176. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  177. inherit : true, shell: true
  178. , env: process.env
  179. }).catch((e)=>{ console.error(e) })
  180. p.position = 2;
  181. console.log('Two')
  182. return p;
  183. }
  184. , ()=>{
  185. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  186. inherit : true, shell: true
  187. , env: process.env
  188. }).catch((e)=>{ console.error(e) })
  189. p.position = 3;
  190. console.log('Three')
  191. return p;
  192. }
  193. , ()=>{
  194. var p = nodeShellExec('n', ['latest'], {
  195. inherit : true, shell: true
  196. , env: process.env
  197. }).catch((e)=>{ console.error(e) })
  198. p.position = 4;
  199. console.log('Four')
  200. return p;
  201. }
  202. ]
  203. any(tasks)
  204. console.log('.......done')
  205. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  206. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  207. console.info('Uninstalling existing ember globally') ;
  208. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  209. stdio: ['pipe', process.stdout, process.stderr],
  210. inherit : true,
  211. shell: true,
  212. cwd : path.dirname(__dirname),
  213. env: env
  214. })
  215. step1.on('close', ()=>{
  216. console.info('Installing ember globally') ;
  217. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  218. stdio: ['pipe', process.stdout, process.stderr],
  219. inherit : true,
  220. shell: true,
  221. cwd : path.dirname(__dirname),
  222. env: env
  223. })
  224. step2.on('close', ()=>{
  225. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  226. stdio: ['pipe', process.stdout, process.stderr],
  227. inherit : true,
  228. shell: true,
  229. cwd : path.dirname(__dirname),
  230. env: env
  231. })
  232. })
  233. })
  234. }
  235. , 'runas' : ()=>{
  236. return isRunningElevated().then(
  237. (isElevated) => {
  238. if(isElevated) {
  239. try {
  240. op[ processedArgs.label || processedArgs._[0] || 'h']()
  241. }
  242. catch(e){
  243. console.error('Error Invalid command : ' + e)
  244. fs.writeFileSync('run.done', 'success')
  245. }
  246. finally {
  247. }
  248. } else throw false;
  249. }
  250. )
  251. .catch(()=>{
  252. console.log('Not Elevated Requesting Elevated Privileges');
  253. // Wait for the runas to complete before we read it.
  254. try {
  255. fs.unlinkSync('run.done')
  256. fs.unlinkSync('run.log')
  257. }
  258. catch(e) { } //Ignore
  259. // PB : TODO -- Convert all the cli args back to string.
  260. var namedArgs = [];
  261. Object.keys(processedArgs).forEach((v)=>{ v!='_' ? namedArgs.push('--'+v+'='+processedArgs[v]) : null; })
  262. //console.log(' namedArgs : ' + namedArgs)
  263. process.env.NODE_ENV = process.env.NODE_ENV || 'development';
  264. var args = [__dirname + '/windowselevate.hta'].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  265. nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  266. , {
  267. inherit : true
  268. , shell: true
  269. , env: process.env
  270. , runas : 'self'
  271. , title : `runas`
  272. }
  273. ).then(()=>{
  274. // runas returned.
  275. var runaslog = JSON.parse('[ { "success" : true, "result" : "runas Log" }' + fs.readFileSync('run.log', { flags : 'a+'}) + ']');
  276. runaslog.forEach((logEntry)=>{
  277. logEntry.succes ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' '))
  278. })
  279. })
  280. .catch(err => console.error('Elevation failed : ' + err));
  281. })
  282. }
  283. , 'push' : ()=>{
  284. if(!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  285. // init remote bare from local
  286. // pushandinitremotebare
  287. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  288. // connect to repo server -- net use 172.16.0.27
  289. // cd 172.16.0.27/repos/
  290. // mkdir repo.git
  291. // cd repo.git
  292. // git init --bare
  293. // cd localrepo
  294. // git remote rename origin githubclone
  295. // git remote add origin //172.16.0.27/repos/repo.git
  296. // git push origin master
  297. var repo = processedArgs._[1];
  298. var defaultRepoServer = '//172.16.0.27/repos'
  299. var sequentialTaskShellCommands = [];
  300. if(!existsSync(`Z:/${repo}.git`)){
  301. sequentialTaskShellCommands = [
  302. // ['net', ['use', 'Z:', defaultRepoServer.replace('/','\\')], {
  303. // inherit : true, shell: true
  304. // , env: process.env
  305. // }]
  306. ['pwd', { cwd : 'Z:', inherit : true}]
  307. , ['mkdir', [`${repo}.git`], {
  308. cwd : `Z:`
  309. , inherit : true, shell: true
  310. , env: process.env
  311. }]
  312. , ['pwd', { cwd : `Z:/${repo}.git`, inherit : true}]
  313. , ['git', ['init', '--bare'], { cwd : `Z:/${repo}.git`
  314. , inherit : true, shell: true
  315. , env: process.env
  316. }]
  317. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd : `${repo}`}, (err)=>{
  318. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  319. } ] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  320. , ['git', ['remote', 'add', 'origin', `${defaultRepoServer}/${repo}.git`], { cwd : `${repo}`}]
  321. ]
  322. if(!existsSync(`Z:`)){
  323. sequentialTaskShellCommands.splice(0,0, ['net', ['use', 'Z:', defaultRepoServer.replace(/\//gm,'\\')], {
  324. inherit : true, shell: true
  325. , env: process.env
  326. }])
  327. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  328. // throw 'done'
  329. }
  330. }
  331. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd : `${repo}`}])
  332. // console.dir(sequentialTaskShellCommands);
  333. var tasks = [];
  334. sequentialTaskShellCommands.forEach(shellcmd => {
  335. // console.log(shellcmd)
  336. tasks.push(()=>{
  337. var p = nodeShellExec.apply(null, shellcmd.slice(0,3)).catch((e)=>{ if(shellcmd[3]) { return shellcmd[3]() } else { console.error(e);} })
  338. return p;
  339. })
  340. })
  341. any(tasks);
  342. }
  343. , 'pull' : (label) => {
  344. var env = Object.assign({}, process.env); // Shallow clone it.
  345. // console.dir(env)
  346. console.log('Running exlr pull : ' + path.dirname(__dirname))
  347. // nodeShellExec('cmd', ['/c', 'setup\\utility\\chess.bat', 'pull'], {
  348. // // nodeShellExec('cmd', ['/c', '..\\setup\\utility\\chess.bat', 'pull'], {
  349. // stdio: ['pipe', process.stdout, process.stderr],
  350. // inherit : true,
  351. // shell: true,
  352. // cwd : path.dirname(__dirname),
  353. // env: env
  354. // })
  355. var performPull = repo => {
  356. if(existsSync(repo)) {
  357. console.log('pulling ' + repo)
  358. return nodeShellExec('git', ['pull'], {
  359. inherit : true, shell: true,
  360. cwd : repo
  361. // , env: process.env
  362. , runas : processedArgs.runas
  363. , title : `git pull ${repo}`
  364. }).catch((e)=>{ console.error(e) })
  365. }
  366. else {
  367. console.log('cloning ' + repo)
  368. return nodeShellExec('git', ['clone', '//172.16.0.27/repos/' + repo + '.git'],
  369. {
  370. inherit : true, shell: true,
  371. env: process.env
  372. , runas : processedArgs.runas
  373. , title : `git clone ${'//172.16.0.27/repos/' + repo + '.git'}`
  374. }).catch((e)=>{ console.error(e) })
  375. }
  376. }
  377. if(!processedArgs.runas) gitRepos.forEach(performPull)
  378. return isRunningElevated().then(
  379. (isElevated) => {
  380. if(isElevated) {
  381. any(elevatedRunasRepos.map((repo)=>performPull(repo))).then(()=>{
  382. fs.writeFileSync('run.done', 'success')
  383. }).catch(()=>{
  384. fs.writeFileSync('run.done', 'error')
  385. })
  386. }
  387. else throw false;
  388. }
  389. ).catch(
  390. () => {
  391. op['runas']()
  392. }
  393. )
  394. }
  395. , 'npmi' : ()=>{
  396. var tasks = [];
  397. gitRepos.forEach(repo => {
  398. console.log('npm i for ' + repo)
  399. // nodeShellExec('pwd', [], {
  400. // // inherit : true, shell: true
  401. // cwd : repo
  402. // // , env: process.env
  403. // , title : `pwd for ${repo}`
  404. // }).catch((e)=>{ console.error(e) })
  405. nodeShellExec('rm', ['package-lock.json'], {
  406. inherit : true, shell: true
  407. , cwd : repo
  408. , env: process.env
  409. , title : `rm 'package-lock.json' for ${repo}`
  410. }).catch((e)=>{ console.error(e) })
  411. tasks.push(()=>{
  412. var p = nodeShellExec('npm', ['i'], {
  413. inherit : true, shell: true
  414. , cwd : repo
  415. , env: process.env
  416. , title : `npm i for ${repo}`
  417. }).catch((e)=>{ console.error(e) })
  418. return p;
  419. })
  420. })
  421. any(tasks);
  422. }
  423. , 'start' : (label)=>{
  424. console.log('Starting Elixir Server.');
  425. var env = Object.assign({}, process.env); // Shallow clone it.
  426. // console.dir(env)
  427. env.NODE_ENV = process.env.NODE_ENV || 'development';
  428. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  429. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  430. // cmd = 'node'
  431. var childPromise = nodeShellExec(cmd, ['--inspect=9228', 'elixir/server.js'], {
  432. // inherit : true,
  433. shell: true,
  434. detached: true,
  435. stdio: 'ignore',
  436. cwd : 'elixir-server'
  437. , env: env
  438. })
  439. var child = childPromise.process;
  440. if (typeof child.pid !== 'undefined') {
  441. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  442. encoding: 'utf8'
  443. })
  444. }
  445. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  446. // inherit : true,
  447. // shell: true, detached: true,
  448. // cwd : 'qms/server',
  449. // env: env,
  450. // shell : true
  451. // })
  452. // nodeShellExec('ember', ['s'], {
  453. // // inherit : true,
  454. // shell: true, detached: true,
  455. // cwd : 'client/',
  456. // env: env
  457. // })
  458. var childPromise = nodeShellExec('ember', ['s'], {
  459. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  460. // PB : TODO -- ember debugging.
  461. // inherit : true,
  462. shell: true,
  463. detached: true,
  464. stdio: 'ignore',
  465. cwd : 'client'
  466. , env: env
  467. })
  468. // .catch(e=>console.error(e))
  469. child = childPromise.process;
  470. if (typeof child.pid !== 'undefined') {
  471. fs.writeFileSync('.client.server.pid', child.pid, {
  472. encoding: 'utf8'
  473. })
  474. }
  475. }
  476. , 'stop' : (label)=>{
  477. const kill = require('tree-kill');
  478. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  479. encoding: 'utf8'
  480. })
  481. fs.unlinkSync('.elixir-server.elixir.server.pid')
  482. console.log(serverPid)
  483. kill(serverPid)
  484. serverPid = fs.readFileSync('.client.server.pid', {
  485. encoding: 'utf8'
  486. })
  487. fs.unlinkSync('.client.server.pid')
  488. console.log(serverPid)
  489. kill(serverPid)
  490. }
  491. , 'use' : ()=>{
  492. var runconfig = { NODE_ENV : process.env.NODE_ENV }
  493. try { runconfig = Object.assign(runconfig, require('../run.js')) } catch(e) { }
  494. if((!processedArgs.runas || processedArgs.runas !== 'self') &&
  495. runconfig.NODE_ENV && runconfig.NODE_ENV === (process.env.NODE_ENV || runconfig.NODE_ENV) &&
  496. processedArgs._[1] && runconfig.use === processedArgs._[1]) {
  497. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  498. if(processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  499. return
  500. }
  501. var tasks = [
  502. ()=>{
  503. if(existsSync('config')) {
  504. var p = nodeShellExec('rmdir', ['config'], {inherit : true, shell: true, env: process.env }
  505. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  506. return p;
  507. }
  508. else return Promise.resolve(true);
  509. },
  510. ()=>{
  511. if(existsSync('data')) {
  512. var p = nodeShellExec('rmdir', ['data'], { inherit : true, shell: true, env: process.env }
  513. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  514. return p;
  515. }
  516. else return Promise.resolve(true);
  517. },
  518. , () => {
  519. // Move test config from dev.
  520. if(process.env.NODE_ENV === 'test'){
  521. var devcfgreponame = runconfig.use + '-config' + '-development';
  522. var testcfgreponame = runconfig.use + '-config' + '-test';
  523. var testcfgdir = path.dirname(__dirname) + '/' + testcfgreponame + '/'
  524. var devcfgdir = path.dirname(__dirname) + '/' + devcfgreponame + '/' //eg (elxr/../elixir-config.development)
  525. var promises = [];
  526. promises.push(
  527. nodeShellExec('git', ['checkout', 'test'], {
  528. inherit : true, shell: true,
  529. cwd : testcfgdir
  530. // , env: process.env
  531. , runas : processedArgs.runas
  532. , title : `git checkout ${testcfgreponame}`
  533. }).catch((e)=>{ console.error(e) })
  534. )
  535. promises.push(
  536. nodeShellExec('git', ['checkout', 'master'], {
  537. inherit : true, shell: true,
  538. cwd : devcfgdir
  539. // , env: process.env
  540. , runas : processedArgs.runas
  541. , title : `git checkout ${devcfgreponame}`
  542. }).catch((e)=>{ console.error(e) })
  543. )
  544. Promise.all(promises).then(()=> {
  545. globSync( '**/*.test.js', {cwd : devcfgdir}).map((filename) => {
  546. console.log('File found : ' + devcfgdir + filename)
  547. fs.copyFileSync(devcfgdir + filename, testcfgdir+ filename);
  548. nodeShellExec('git', ['checkout', 'test'], {
  549. inherit : true, shell: true,
  550. cwd : devcfgdir
  551. // , env: process.env
  552. , runas : processedArgs.runas
  553. , title : `git checkout ${devcfgreponame}`
  554. }).catch((e)=>{ console.error(e) })
  555. })
  556. })
  557. }
  558. }
  559. ];
  560. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  561. if(processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  562. if(!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  563. // console.log(process.env.cwd)
  564. fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
  565. any(tasks).then(()=>{
  566. if(!processedArgs.runas) return op['runas']()
  567. tasks = [
  568. ()=>{
  569. // Use junctions to avoid npm package issues
  570. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV ], {
  571. inherit : true, shell: true
  572. , env: process.env
  573. }).catch((e)=>{ console.error(e) })
  574. return p;
  575. }
  576. ];
  577. if(processedArgs._[1]) {
  578. tasks = tasks.concat(
  579. [
  580. ()=>{
  581. var p = nodeShellExec('mklink', ['/D', 'data', runconfig.use + '-data'], {
  582. inherit : true, shell: true
  583. , env: process.env
  584. }).catch((e)=>{ console.error(e) })
  585. return p;
  586. }
  587. ]
  588. )
  589. }
  590. return any(tasks).then(()=>{
  591. fs.writeFileSync('run.done', 'success')
  592. }).catch(()=>{
  593. fs.writeFileSync('run.done', 'error')
  594. })
  595. }).catch(()=>{
  596. fs.writeFileSync('run.done', 'error')
  597. })
  598. // Antibiotic stewardship program.
  599. // 1st use is fine.
  600. // Max vials dispense
  601. // 2nd use Pharmacy needs justification Form.
  602. // Approval after a certain period of time.
  603. }
  604. , 'g' : ()=>{
  605. if(processedArgs.h) {
  606. console.log('elxr g [modelname] => generate a model named [modelname]');
  607. console.log('elxr g => regenerate all known models');
  608. return
  609. }
  610. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  611. // console.log('Starting directory: ' + process.cwd());
  612. // try {
  613. // child = child.on('close', () => { process.chdir(label) } );
  614. // console.log('New directory: ' + process.cwd());
  615. // }
  616. // catch (err) {
  617. // console.log('chdir: ' + err);
  618. // }
  619. // child.on('close', function(){
  620. // var options = {
  621. // shell : true
  622. // , inherit : true
  623. // // , cwd : '' + process.cwd
  624. // // , env : process.env
  625. // };
  626. // nodeShellExec('git', ['init'], { inherit : true});
  627. if(0){
  628. // PB : TODO -- Special google chrome profile for tests etc.
  629. nodeShellExec('pwd', { inherit : true});
  630. //$ "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 1" http://localhost:4200/tests/index.html?grep=loopback
  631. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  632. "--profile-directory=Profile 1"
  633. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  634. }
  635. // nodeShellExec('npm', ['init', '-y'], options);
  636. // nodeShellExec('npm', ['init', '-y'], options);
  637. // })
  638. var g = {
  639. 'client' : ()=>{
  640. console.info('Creating new ember client named : ' + processedArgs._[2] ) ;
  641. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  642. stdio: ['pipe', process.stdout, process.stderr],
  643. inherit : true,
  644. shell: true,
  645. cwd : path.dirname(__dirname),
  646. env: env
  647. })
  648. }
  649. }
  650. g[processedArgs._[1]]();
  651. }
  652. }
  653. return op[label] ? op[label]() : null;
  654. }
  655. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  656. // mysql -u root -p db_name < drop_all_tables.sql
  657. var mysql = '../xampp/mysql/bin/mysql'
  658. var mysqldump = '../xampp/mysql/bin/mysqldump'
  659. // --runas
  660. if(processedArgs.runas) {
  661. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  662. __runcmd('runas')
  663. }
  664. else __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  665. function nodeShellExec() {
  666. var args = Array.from(arguments);
  667. var opts = args[2] = args[2] || {}
  668. opts.title ? null : opts.title = `${args[0]} ${args[1] }`
  669. const child = spawn(...arguments);
  670. var p = new Promise(function(resolve, reject){
  671. if(!opts.detached) {
  672. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  673. var succes = true;
  674. // use child.stdout.setEncoding('utf8'); if you want text chunks
  675. child.stdout.setEncoding('utf8');
  676. child.stderr.setEncoding('utf8');
  677. child.stdout.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  678. child.on('error', (chunk) => { succes = false; messages.push(chunk); /*console.error(chunk)*/ });
  679. child.stderr.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  680. // child.stderr.pipe(process.stderr);
  681. child.on('close', (code) => {
  682. if(code !== 0) succes = false;
  683. if(opts.runas){
  684. fs.writeFileSync('run.log', ', ' + JSON.stringify({ result: ` ${opts.title} exited with code ${code}`, messages : messages }), {'flag':'a+'} )
  685. }
  686. else {
  687. succes ? console.log(['success : ' + ` ${opts.title} exited with code ${code}`]) : console.error([`error : ${opts.title} exited with code ${code}`])
  688. // console.log( messages.join('') )
  689. process.stdout.write( messages.join('') )
  690. }
  691. if(code !== 0) return reject(code)
  692. resolve(true)
  693. });
  694. }
  695. else {
  696. child.unref()
  697. resolve(true);
  698. }
  699. });
  700. p.process = child;
  701. return p;
  702. }