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

index.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. // --------------
  2. // elxr
  3. // A cli tool for elixr.
  4. const { existsSync } = require('fs');
  5. const fs = require('fs')
  6. const { spawn, spawnSync } = require('child_process');
  7. const cliargs = require('../elxr/cliargs'); // Use minimist...
  8. const processedArgs = cliargs(process.argv.slice(2));
  9. console.dir(processedArgs)
  10. var path = require('path')
  11. // Serialize a set of functions that will execute to return a promises one after the other.
  12. // Will stop when any one fails.
  13. function any(iterable, continueOnFailure) {
  14. return iterable.reduce(
  15. (p, fn, i ,a) => {
  16. // console.log('accumulator :');
  17. // console.log(p);
  18. if(Promise.resolve(p) === p ) {
  19. return p.then((pVal) => {
  20. if(Promise.resolve(pVal) === pVal) {
  21. // Passed in function retured a promise. We still need to wait for it.
  22. pVal.then((pVal)=>{
  23. // console.log('Then --pVal = ' + pVal + ' bContinue = ' + continueOnFailure ); console.log(p);
  24. if(!pVal && !continueOnFailure) {
  25. console.error("E : pVal :" + pVal);
  26. // i==0 ? null : console.error("E :1 a[i-1] " + a[i-1]);
  27. // a.map((i)=>console.error(i.toString()));
  28. console.error('debugData 3 -------------------');
  29. // console.error(debugData);
  30. console.error('debugData 3 -------------------');
  31. console.log("Cancelling remaining...");
  32. throw 'Failed in reduce 1 '
  33. return false;
  34. }
  35. // console.log('calling fn : '+ fn);
  36. return (Promise.resolve(fn) === fn ) ? fn : fn() ;
  37. })
  38. }
  39. else {
  40. // console.log('Then --pVal = ' + pVal + ' bContinue = ' + continueOnFailure ); console.log(p);
  41. if(!pVal && !continueOnFailure) {
  42. console.error("E : pVal :" + pVal);
  43. // i==0 ? null : console.error("E :1 a[i-1] " + a[i-1]);
  44. // a.map((i)=>console.error(i.toString()));
  45. console.error('debugData 3 -------------------');
  46. // console.error(debugData);
  47. console.error('debugData 3 -------------------');
  48. console.log("Cancelling remaining...");
  49. throw 'Failed in reduce 1 '
  50. return false;
  51. }
  52. // console.log('calling fn : '+ fn);
  53. return (Promise.resolve(fn) === fn ) ? fn : fn() ;
  54. }
  55. }).catch((error) => {
  56. console.error("E : " + error);
  57. fn ? console.error("Fn : " + fn.toString()) : null;
  58. // i==0 ? null : console.error("E :2 a[i-1] " + a[i-1]);
  59. // a.map((i)=>console.error(i.toString()));
  60. console.error('debugData 4-------------------------');
  61. // console.error(debugData);
  62. console.error('debugData 4-------------------------');
  63. throw 'Failed in reduce 2 '
  64. return false;
  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 isRunningElevated = ()=>{
  76. return nodeShellExec( "fsutil", ["dirty", "query", "C:"], {
  77. inherit : true, shell: true
  78. , env: process.env
  79. , title : `check privileged execution mode using fsutil dirty query C:`
  80. }).then((exitcode)=>{
  81. console.log('Elevated')
  82. return true;
  83. }).catch(()=>{
  84. console.log('Not Elevated');
  85. throw false;
  86. });
  87. }
  88. var cli = 'elxr';
  89. var ver = '#unversioned';
  90. var help = '#unkown list of commands... please refer dveloper documentation for ' + cli;
  91. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  92. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  93. var dbForLabel = function(label){
  94. var dbsForLabel = {
  95. devmysql : 'mysql'
  96. , development : 'mssql'
  97. , production : 'mssql'
  98. }
  99. return dbsForLabel[label] || 'mysql'
  100. }
  101. // Relevant git repos
  102. var gitRepos = [
  103. 'ember-masonry-grid'
  104. , 'bbhverse'
  105. , 'clientverse'
  106. , 'serververse'
  107. , 'client'
  108. // , 'client/server'
  109. , 'elxr'
  110. , 'elixir-client'
  111. , 'elixir-client-unlinked'
  112. , 'ember-searchable-select'
  113. , 'loopback-component-jsonapi'
  114. , 'elixir-config'
  115. , 'cihsr-config'
  116. , 'cihsr-data'
  117. , 'elixir-data'
  118. , 'loopback-connector-ds'
  119. , 'chess-server-lib'
  120. , 'setup'
  121. ]
  122. // Repositiories that have symlinks that required elevated priviletes in windows to create symlinks
  123. //
  124. var elevatedRunasRepos = [
  125. 'elixir-server'
  126. , 'cihsr-server'
  127. , 'chess-server'
  128. ]
  129. var env = Object.assign({}, process.env); // Shallow clone it.
  130. var __runcmd = function(label){
  131. var op = {
  132. 'h' : ()=>{ console.log(cli + ' ' + ver + ' ' + help); return '-h' }
  133. , 'upgrade' : ()=>{
  134. console.log('upgrade.......')
  135. var tasks = [
  136. ()=>{
  137. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  138. inherit : true, shell: true
  139. , env: process.env
  140. }).catch((e)=>{ console.error(e) })
  141. p.position = 1;
  142. console.log('One')
  143. return p;
  144. }
  145. , ()=>{
  146. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  147. inherit : true, shell: true
  148. , env: process.env
  149. }).catch((e)=>{ console.error(e) })
  150. p.position = 2;
  151. console.log('Two')
  152. return p;
  153. }
  154. , ()=>{
  155. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  156. inherit : true, shell: true
  157. , env: process.env
  158. }).catch((e)=>{ console.error(e) })
  159. p.position = 3;
  160. console.log('Three')
  161. return p;
  162. }
  163. , ()=>{
  164. var p = nodeShellExec('n', ['latest'], {
  165. inherit : true, shell: true
  166. , env: process.env
  167. }).catch((e)=>{ console.error(e) })
  168. p.position = 4;
  169. console.log('Four')
  170. return p;
  171. }
  172. ]
  173. any(tasks)
  174. console.log('.......done')
  175. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  176. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  177. console.info('Uninstalling existing ember globally') ;
  178. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  179. stdio: ['pipe', process.stdout, process.stderr],
  180. inherit : true,
  181. shell: true,
  182. cwd : path.dirname(__dirname),
  183. env: env
  184. })
  185. step1.on('close', ()=>{
  186. console.info('Installing ember globally') ;
  187. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  188. stdio: ['pipe', process.stdout, process.stderr],
  189. inherit : true,
  190. shell: true,
  191. cwd : path.dirname(__dirname),
  192. env: env
  193. })
  194. step2.on('close', ()=>{
  195. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  196. stdio: ['pipe', process.stdout, process.stderr],
  197. inherit : true,
  198. shell: true,
  199. cwd : path.dirname(__dirname),
  200. env: env
  201. })
  202. })
  203. })
  204. }
  205. , 'runas' : ()=>{
  206. return isRunningElevated().then(
  207. () => op[ processedArgs.label || processedArgs._[0] || 'h']()
  208. )
  209. .catch(()=>{
  210. console.log('Not Elevated');
  211. console.log('Requesting Elevated Privileges')
  212. nodeShellExec('MSHTA', [`javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('node', 'elxr ${processedArgs._[0]} ${processedArgs._[1]} ${processedArgs._[2]} --runas=true', '', 'runas', 1);close();`]
  213. , {
  214. // inherit : true
  215. // , shell: true
  216. env: process.env
  217. , title : `runas`
  218. }
  219. );
  220. })
  221. }
  222. , 'push' : ()=>{
  223. if(!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  224. // init remote bare from local
  225. // pushandinitremotebare
  226. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  227. // connect to repo server -- net use 172.16.0.27
  228. // cd 172.16.0.27/repos/
  229. // mkdir repo.git
  230. // cd repo.git
  231. // git init --bare
  232. // cd localrepo
  233. // git remote rename origin githubclone
  234. // git remote add origin //172.16.0.27/repos/repo.git
  235. // git push origin master
  236. var repo = processedArgs._[1];
  237. var defaultRepoServer = '//172.16.0.27/repos'
  238. var sequentialTaskShellCommands = [];
  239. if(!existsSync(`Z:/${repo}.git`)){
  240. sequentialTaskShellCommands = [
  241. // ['net', ['use', 'Z:', defaultRepoServer.replace('/','\\')], {
  242. // inherit : true, shell: true
  243. // , env: process.env
  244. // }]
  245. ['pwd', { cwd : 'Z:', inherit : true}]
  246. , ['mkdir', [`${repo}.git`], {
  247. cwd : `Z:`
  248. , inherit : true, shell: true
  249. , env: process.env
  250. }]
  251. , ['pwd', { cwd : `Z:/${repo}.git`, inherit : true}]
  252. , ['git', ['init', '--bare'], { cwd : `Z:/${repo}.git`
  253. , inherit : true, shell: true
  254. , env: process.env
  255. }]
  256. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd : `${repo}`}, (err)=>{
  257. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  258. } ] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  259. , ['git', ['remote', 'add', 'origin', `${defaultRepoServer}/${repo}.git`], { cwd : `${repo}`}]
  260. ]
  261. if(!existsSync(`Z:`)){
  262. sequentialTaskShellCommands.splice(0,0, ['net', ['use', 'Z:', defaultRepoServer.replace(/\//gm,'\\')], {
  263. inherit : true, shell: true
  264. , env: process.env
  265. }])
  266. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  267. // throw 'done'
  268. }
  269. }
  270. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd : `${repo}`}])
  271. // console.dir(sequentialTaskShellCommands);
  272. var tasks = [];
  273. sequentialTaskShellCommands.forEach(shellcmd => {
  274. // console.log(shellcmd)
  275. tasks.push(()=>{
  276. var p = nodeShellExec.apply(null, shellcmd.slice(0,3)).catch((e)=>{ if(shellcmd[3]) { return shellcmd[3]() } else { console.error(e);} })
  277. return p;
  278. })
  279. })
  280. any(tasks);
  281. }
  282. , 'pull' : (label) => {
  283. var env = Object.assign({}, process.env); // Shallow clone it.
  284. // console.dir(env)
  285. console.log('Running exlr pull : ' + path.dirname(__dirname))
  286. // nodeShellExec('cmd', ['/c', 'setup\\utility\\chess.bat', 'pull'], {
  287. // // nodeShellExec('cmd', ['/c', '..\\setup\\utility\\chess.bat', 'pull'], {
  288. // stdio: ['pipe', process.stdout, process.stderr],
  289. // inherit : true,
  290. // shell: true,
  291. // cwd : path.dirname(__dirname),
  292. // env: env
  293. // })
  294. var performPull = repo => {
  295. if(existsSync(repo)) {
  296. console.log('pulling ' + repo)
  297. nodeShellExec('git', ['pull'], {
  298. inherit : true, shell: true,
  299. cwd : repo
  300. // , env: process.env
  301. , title : `git pull ${repo}`
  302. }).catch((e)=>{ console.error(e) })
  303. }
  304. else {
  305. console.log('cloning ' + repo)
  306. nodeShellExec('git', ['clone', '//172.16.0.27/repos/' + repo + '.git'],
  307. {
  308. inherit : true, shell: true,
  309. env: process.env
  310. , title : `git clone ${'//172.16.0.27/repos/' + repo + '.git'}`
  311. }).catch((e)=>{ console.error(e) })
  312. }
  313. }
  314. if(!processedArgs.runas) gitRepos.forEach(performPull)
  315. return isRunningElevated().then(
  316. ()=> elevatedRunasRepos.forEach(performPull))
  317. .catch(
  318. () => op['runas']()
  319. )
  320. }
  321. , 'npmi' : ()=>{
  322. var tasks = [];
  323. gitRepos.forEach(repo => {
  324. console.log('npm i for ' + repo)
  325. // nodeShellExec('pwd', [], {
  326. // // inherit : true, shell: true
  327. // cwd : repo
  328. // // , env: process.env
  329. // , title : `pwd for ${repo}`
  330. // }).catch((e)=>{ console.error(e) })
  331. nodeShellExec('rm', ['package-lock.json'], {
  332. inherit : true, shell: true
  333. , cwd : repo
  334. , env: process.env
  335. , title : `rm 'package-lock.json' for ${repo}`
  336. }).catch((e)=>{ console.error(e) })
  337. tasks.push(()=>{
  338. var p = nodeShellExec('npm', ['i'], {
  339. inherit : true, shell: true
  340. , cwd : repo
  341. , env: process.env
  342. , title : `npm i for ${repo}`
  343. }).catch((e)=>{ console.error(e) })
  344. return p;
  345. })
  346. })
  347. any(tasks);
  348. }
  349. , 'start' : (label)=>{
  350. console.log('Starting Elixir Server.');
  351. var env = Object.assign({}, process.env); // Shallow clone it.
  352. // console.dir(env)
  353. env.NODE_ENV = label || 'development';
  354. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  355. nodeShellExec('node', ['--inspect=9228', 'elixir/server.js'], {
  356. // inherit : true,
  357. shell: true, detached: true,
  358. cwd : 'elixir-server',
  359. env: env
  360. })
  361. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  362. // inherit : true,
  363. // shell: true, detached: true,
  364. // cwd : 'qms/server',
  365. // env: env,
  366. // shell : true
  367. // })
  368. nodeShellExec('ember', ['s'], {
  369. // inherit : true,
  370. shell: true, detached: true,
  371. cwd : 'client/',
  372. env: env
  373. })
  374. }
  375. , 'use' : ()=>{
  376. if(!processedArgs.runas){
  377. try {
  378. var runconfig = require('./run.js')
  379. if(processedArgs._[1] && runconfig.use === processedArgs._[1]) {
  380. return;
  381. }
  382. else runconfig.use = processedArgs._[1];
  383. fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
  384. }
  385. catch(e) {
  386. runconfig = { use : processedArgs._[1] };
  387. fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
  388. }
  389. op['runas']()
  390. }
  391. else {
  392. var runconfig = require('../run.js')
  393. console.log('runconfig.use : ' + runconfig.use)
  394. var tasks = [
  395. ()=>{
  396. var p = nodeShellExec('rm', ['config'], {
  397. inherit : true, shell: true
  398. , cwd : repo
  399. , env: process.env
  400. , title : `rm 'package-lock.json' for ${repo}`
  401. }).catch((e)=>{ console.error(e) })
  402. return p;
  403. },
  404. ()=>{
  405. var p = nodeShellExec('rm', ['data'], {
  406. inherit : true, shell: true
  407. , cwd : repo
  408. , env: process.env
  409. , title : `rm 'package-lock.json' for ${repo}`
  410. }).catch((e)=>{ console.error(e) })
  411. return p;
  412. },
  413. ()=>{
  414. var p = nodeShellExec('mklink', ['/D', 'data', runconfig.use + '-data'], {
  415. inherit : true, shell: true
  416. , env: process.env
  417. }).catch((e)=>{ console.error(e) })
  418. return p;
  419. },
  420. ()=>{
  421. var p = nodeShellExec('mklink', ['/D', 'config', runconfig.use + '-config'], {
  422. inherit : true, shell: true
  423. , env: process.env
  424. }).catch((e)=>{ console.error(e) })
  425. return p;
  426. }
  427. ]
  428. any(tasks)
  429. }
  430. // Antibiotic stewardship program.
  431. // 1st use is fine.
  432. // Max vials dispense
  433. // 2nd use Pharmacy needs justification Form.
  434. // Approval after a certain period of time.
  435. }
  436. , 'g' : ()=>{
  437. if(processedArgs.h) {
  438. console.log('elxr g [modelname] => generate a model named [modelname]');
  439. console.log('elxr g => regenerate all known models');
  440. return
  441. }
  442. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  443. // console.log('Starting directory: ' + process.cwd());
  444. // try {
  445. // child = child.on('close', () => { process.chdir(label) } );
  446. // console.log('New directory: ' + process.cwd());
  447. // }
  448. // catch (err) {
  449. // console.log('chdir: ' + err);
  450. // }
  451. // child.on('close', function(){
  452. // var options = {
  453. // shell : true
  454. // , inherit : true
  455. // // , cwd : '' + process.cwd
  456. // // , env : process.env
  457. // };
  458. // nodeShellExec('git', ['init'], { inherit : true});
  459. if(0){
  460. // PB : TODO -- Special google chrome profile for tests etc.
  461. nodeShellExec('pwd', { inherit : true});
  462. //$ "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 1" http://localhost:4200/tests/index.html?grep=loopback
  463. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  464. "--profile-directory=Profile 1"
  465. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  466. }
  467. // nodeShellExec('npm', ['init', '-y'], options);
  468. // nodeShellExec('npm', ['init', '-y'], options);
  469. // })
  470. var g = {
  471. 'client' : ()=>{
  472. console.info('Creating new ember client named : ' + processedArgs._[2] ) ;
  473. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  474. stdio: ['pipe', process.stdout, process.stderr],
  475. inherit : true,
  476. shell: true,
  477. cwd : path.dirname(__dirname),
  478. env: env
  479. })
  480. }
  481. }
  482. g[processedArgs._[1]]();
  483. }
  484. }
  485. return op[label] ? op[label]() : op['start'](label);
  486. }
  487. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  488. // mysql -u root -p db_name < drop_all_tables.sql
  489. var mysql = '../xampp/mysql/bin/mysql'
  490. var mysqldump = '../xampp/mysql/bin/mysqldump'
  491. __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  492. // nodeShellExec('git', ['status']);
  493. function nodeShellExec() {
  494. var args = Array.from(arguments);
  495. args[2] ? null : args[2] = {}
  496. args[2].title ? null : args[2].title = `${args[0]} ${args[1]}`
  497. const child = spawn(...arguments);
  498. return new Promise(function(resolve, reject){
  499. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  500. // use child.stdout.setEncoding('utf8'); if you want text chunks
  501. child.stdout.setEncoding('utf8');
  502. child.stderr.setEncoding('utf8');
  503. child.stdout.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  504. child.on('error', (chunk) => { messages.push(chunk); /*console.error(chunk)*/ });
  505. child.stderr.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  506. // child.stderr.pipe(process.stderr);
  507. child.on('close', (code) => {
  508. console.log([` ${args[2].title} exited with code ${code}`])
  509. // console.log([ messages.join('') ])
  510. process.stdout.write( messages.join('') )
  511. if(code !== 0 ) return reject(code)
  512. resolve(true)
  513. });
  514. });
  515. }