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

index.js 29KB

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