Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

index.js 29KB

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