555
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 29KB

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