Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

index.js 29KB

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