555
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

6 anos atrás
4 anos atrás
4 anos atrás
5 anos atrás
6 anos atrás
4 anos atrás
6 anos atrás
5 anos atrás
6 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
6 anos atrás
5 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
5 anos atrás
4 anos atrás
5 anos atrás
5 anos atrás
5 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
4 anos atrás
5 anos atrás
4 anos atrás
5 anos atrás
4 anos atrás
5 anos atrás
4 anos atrás
5 anos atrás
6 anos atrás
5 anos atrás
6 anos atrás
5 anos atrás
6 anos atrás
6 anos atrás
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  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('Not Elevated 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.succes ? (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. // Move test config from dev.
  528. if(process.env.NODE_ENV === 'test'){
  529. var devcfgreponame = runconfig.use + '-config' + '-development';
  530. var testcfgreponame = runconfig.use + '-config' + '-test';
  531. var testcfgdir = path.dirname(__dirname) + '/' + testcfgreponame + '/'
  532. var devcfgdir = path.dirname(__dirname) + '/' + devcfgreponame + '/' //eg (elxr/../elixir-config.development)
  533. var promises = [];
  534. promises.push(
  535. nodeShellExec('git', ['checkout', 'test'], {
  536. inherit : true, shell: true,
  537. cwd : testcfgdir
  538. // , env: process.env
  539. , runas : processedArgs.runas
  540. , title : `git checkout ${testcfgreponame}`
  541. }).catch((e)=>{ console.error(e) })
  542. )
  543. promises.push(
  544. nodeShellExec('git', ['checkout', 'master'], {
  545. inherit : true, shell: true,
  546. cwd : devcfgdir
  547. // , env: process.env
  548. , runas : processedArgs.runas
  549. , title : `git checkout ${devcfgreponame}`
  550. }).catch((e)=>{ console.error(e) })
  551. )
  552. Promise.all(promises).then(()=> {
  553. globSync( '**/*.test.js', {cwd : devcfgdir}).map((filename) => {
  554. console.log('File found : ' + devcfgdir + filename)
  555. fs.copyFileSync(devcfgdir + filename, testcfgdir+ filename);
  556. nodeShellExec('git', ['checkout', 'test'], {
  557. inherit : true, shell: true,
  558. cwd : devcfgdir
  559. // , env: process.env
  560. , runas : processedArgs.runas
  561. , title : `git checkout ${devcfgreponame}`
  562. }).catch((e)=>{ console.error(e) })
  563. })
  564. })
  565. }
  566. }
  567. ];
  568. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  569. if(processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  570. if(!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  571. // console.log(process.env.cwd)
  572. fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
  573. var checkoutMap = {
  574. 'development' : 'master',
  575. }
  576. // -b fails...
  577. var performCheckout = (repo)=>{
  578. return nodeShellExec('git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  579. inherit : true, shell: true,
  580. cwd : repo
  581. }).catch((e)=>{ console.error(e) })
  582. }
  583. any(tasks).then(()=>{
  584. if(!processedArgs.runas) return op['runas']()
  585. tasks = [
  586. ()=>{
  587. // Use junctions to avoid npm package issues
  588. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV ], {
  589. inherit : true, shell: true
  590. , env: process.env
  591. }).catch((e)=>{ console.error(e) })
  592. return p;
  593. }
  594. ];
  595. if(processedArgs._[1]) {
  596. tasks = tasks.concat(
  597. [
  598. ()=>{
  599. var p = nodeShellExec('mklink', ['/D', 'data', runconfig.use + '-data'], {
  600. inherit : true, shell: true
  601. , env: process.env
  602. }).catch((e)=>{ console.error(e) })
  603. return p;
  604. }
  605. ]
  606. )
  607. }
  608. return any(tasks.concat([
  609. any(gitRepos.map((repo)=>performCheckout(repo))),
  610. any(elevatedRunasRepos.map((repo)=>performCheckout(repo)))
  611. ])
  612. ).then(()=>{
  613. fs.writeFileSync('run.done', 'success')
  614. }).catch(()=>{
  615. fs.writeFileSync('run.done', 'error')
  616. })
  617. }).catch(()=>{
  618. fs.writeFileSync('run.done', 'error')
  619. })
  620. // Antibiotic stewardship program.
  621. // 1st use is fine.
  622. // Max vials dispense
  623. // 2nd use Pharmacy needs justification Form.
  624. // Approval after a certain period of time.
  625. }
  626. , 'g' : ()=>{
  627. if(processedArgs.h) {
  628. console.log('elxr g [modelname] => generate a model named [modelname]');
  629. console.log('elxr g => regenerate all known models');
  630. return
  631. }
  632. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  633. // console.log('Starting directory: ' + process.cwd());
  634. // try {
  635. // child = child.on('close', () => { process.chdir(label) } );
  636. // console.log('New directory: ' + process.cwd());
  637. // }
  638. // catch (err) {
  639. // console.log('chdir: ' + err);
  640. // }
  641. // child.on('close', function(){
  642. // var options = {
  643. // shell : true
  644. // , inherit : true
  645. // // , cwd : '' + process.cwd
  646. // // , env : process.env
  647. // };
  648. // nodeShellExec('git', ['init'], { inherit : true});
  649. if(0){
  650. // PB : TODO -- Special google chrome profile for tests etc.
  651. nodeShellExec('pwd', { inherit : true});
  652. //$ "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 1" http://localhost:4200/tests/index.html?grep=loopback
  653. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  654. "--profile-directory=Profile 1"
  655. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  656. }
  657. // nodeShellExec('npm', ['init', '-y'], options);
  658. // nodeShellExec('npm', ['init', '-y'], options);
  659. // })
  660. var g = {
  661. 'client' : ()=>{
  662. console.info('Creating new ember client named : ' + processedArgs._[2] ) ;
  663. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  664. stdio: ['pipe', process.stdout, process.stderr],
  665. inherit : true,
  666. shell: true,
  667. cwd : path.dirname(__dirname),
  668. env: env
  669. })
  670. }
  671. }
  672. g[processedArgs._[1]]();
  673. }
  674. }
  675. return op[label] ? op[label]() : null;
  676. }
  677. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  678. // mysql -u root -p db_name < drop_all_tables.sql
  679. var mysql = '../xampp/mysql/bin/mysql'
  680. var mysqldump = '../xampp/mysql/bin/mysqldump'
  681. // --runas
  682. if(processedArgs.runas) {
  683. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  684. __runcmd('runas')
  685. }
  686. else __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  687. function nodeShellExec() {
  688. var args = Array.from(arguments);
  689. var opts = args[2] = args[2] || {}
  690. opts.title ? null : opts.title = `${args[0]} ${args[1] }`
  691. const child = spawn(...arguments);
  692. var p = new Promise(function(resolve, reject){
  693. if(!opts.detached) {
  694. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  695. var succes = true;
  696. // use child.stdout.setEncoding('utf8'); if you want text chunks
  697. child.stdout.setEncoding('utf8');
  698. child.stderr.setEncoding('utf8');
  699. child.stdout.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  700. child.on('error', (chunk) => { succes = false; messages.push(chunk); /*console.error(chunk)*/ });
  701. child.stderr.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  702. // child.stderr.pipe(process.stderr);
  703. child.on('close', (code) => {
  704. if(code !== 0) succes = false;
  705. if(opts.runas){
  706. fs.writeFileSync('run.log', ', ' + JSON.stringify({ result: ` ${opts.title} exited with code ${code}`, messages : messages }), {'flag':'a+'} )
  707. }
  708. else {
  709. succes ? console.log(['success : ' + ` ${opts.title} exited with code ${code}`]) : console.error([`error : ${opts.title} exited with code ${code}`])
  710. // console.log( messages.join('') )
  711. process.stdout.write( messages.join('') )
  712. }
  713. if(code !== 0) return reject(code)
  714. resolve(true)
  715. });
  716. }
  717. else {
  718. child.unref()
  719. resolve(true);
  720. }
  721. });
  722. p.process = child;
  723. return p;
  724. }