555
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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}`}] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  257. , ['git', ['remote', 'add', 'origin', `${defaultRepoServer}/${repo}.git`], { cwd : `${repo}`}]
  258. ]
  259. if(!existsSync(`Z:`)){
  260. sequentialTaskShellCommands.splice(0,0, ['net', ['use', 'Z:', defaultRepoServer.replace(/\//gm,'\\')], {
  261. inherit : true, shell: true
  262. , env: process.env
  263. }])
  264. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  265. // throw 'done'
  266. }
  267. }
  268. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd : `${repo}`}])
  269. // console.dir(sequentialTaskShellCommands);
  270. var tasks = [];
  271. sequentialTaskShellCommands.forEach(shellcmd => {
  272. // console.log(shellcmd)
  273. tasks.push(()=>{
  274. var p = nodeShellExec.apply(null, shellcmd).catch((e)=>{ console.error(e) })
  275. return p;
  276. })
  277. })
  278. any(tasks);
  279. }
  280. , 'pull' : (label) => {
  281. var env = Object.assign({}, process.env); // Shallow clone it.
  282. // console.dir(env)
  283. console.log('Running exlr pull : ' + path.dirname(__dirname))
  284. // nodeShellExec('cmd', ['/c', 'setup\\utility\\chess.bat', 'pull'], {
  285. // // nodeShellExec('cmd', ['/c', '..\\setup\\utility\\chess.bat', 'pull'], {
  286. // stdio: ['pipe', process.stdout, process.stderr],
  287. // inherit : true,
  288. // shell: true,
  289. // cwd : path.dirname(__dirname),
  290. // env: env
  291. // })
  292. var performPull = repo => {
  293. if(existsSync(repo)) {
  294. console.log('pulling ' + repo)
  295. nodeShellExec('git', ['pull'], {
  296. inherit : true, shell: true,
  297. cwd : repo
  298. // , env: process.env
  299. , title : `git pull ${repo}`
  300. }).catch((e)=>{ console.error(e) })
  301. }
  302. else {
  303. console.log('cloning ' + repo)
  304. nodeShellExec('git', ['clone', '//172.16.0.27/repos/' + repo + '.git'],
  305. {
  306. inherit : true, shell: true,
  307. env: process.env
  308. , title : `git clone ${'//172.16.0.27/repos/' + repo + '.git'}`
  309. }).catch((e)=>{ console.error(e) })
  310. }
  311. }
  312. if(!processedArgs.runas) gitRepos.forEach(performPull)
  313. return isRunningElevated().then(
  314. ()=> elevatedRunasRepos.forEach(performPull))
  315. .catch(
  316. () => op['runas']()
  317. )
  318. }
  319. , 'npmi' : ()=>{
  320. var tasks = [];
  321. gitRepos.forEach(repo => {
  322. console.log('npm i for ' + repo)
  323. // nodeShellExec('pwd', [], {
  324. // // inherit : true, shell: true
  325. // cwd : repo
  326. // // , env: process.env
  327. // , title : `pwd for ${repo}`
  328. // }).catch((e)=>{ console.error(e) })
  329. nodeShellExec('rm', ['package-lock.json'], {
  330. inherit : true, shell: true
  331. , cwd : repo
  332. , env: process.env
  333. , title : `rm 'package-lock.json' for ${repo}`
  334. }).catch((e)=>{ console.error(e) })
  335. tasks.push(()=>{
  336. var p = nodeShellExec('npm', ['i'], {
  337. inherit : true, shell: true
  338. , cwd : repo
  339. , env: process.env
  340. , title : `npm i for ${repo}`
  341. }).catch((e)=>{ console.error(e) })
  342. return p;
  343. })
  344. })
  345. any(tasks);
  346. }
  347. , 'start' : (label)=>{
  348. console.log('Starting Elixir Server.');
  349. var env = Object.assign({}, process.env); // Shallow clone it.
  350. // console.dir(env)
  351. env.NODE_ENV = label || 'development';
  352. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  353. nodeShellExec('node', ['--inspect=9228', 'elixir/server.js'], {
  354. // inherit : true,
  355. shell: true, detached: true,
  356. cwd : 'elixir-server',
  357. env: env
  358. })
  359. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  360. // inherit : true,
  361. // shell: true, detached: true,
  362. // cwd : 'qms/server',
  363. // env: env,
  364. // shell : true
  365. // })
  366. nodeShellExec('ember', ['s'], {
  367. // inherit : true,
  368. shell: true, detached: true,
  369. cwd : 'client/',
  370. env: env
  371. })
  372. }
  373. , 'use' : ()=>{
  374. if(!processedArgs.runas){
  375. try {
  376. var runconfig = require('./run.js')
  377. if(processedArgs._[1] && runconfig.use === processedArgs._[1]) {
  378. return;
  379. }
  380. else runconfig.use = processedArgs._[1];
  381. fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
  382. }
  383. catch(e) {
  384. runconfig = { use : processedArgs._[1] };
  385. fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
  386. }
  387. op['runas']()
  388. }
  389. else {
  390. var runconfig = require('../run.js')
  391. console.log('runconfig.use : ' + runconfig.use)
  392. var tasks = [
  393. ()=>{
  394. var p = nodeShellExec('rm', ['config'], {
  395. inherit : true, shell: true
  396. , cwd : repo
  397. , env: process.env
  398. , title : `rm 'package-lock.json' for ${repo}`
  399. }).catch((e)=>{ console.error(e) })
  400. return p;
  401. },
  402. ()=>{
  403. var p = nodeShellExec('rm', ['data'], {
  404. inherit : true, shell: true
  405. , cwd : repo
  406. , env: process.env
  407. , title : `rm 'package-lock.json' for ${repo}`
  408. }).catch((e)=>{ console.error(e) })
  409. return p;
  410. },
  411. ()=>{
  412. var p = nodeShellExec('mklink', ['/D', 'data', runconfig.use + '-data'], {
  413. inherit : true, shell: true
  414. , env: process.env
  415. }).catch((e)=>{ console.error(e) })
  416. return p;
  417. },
  418. ()=>{
  419. var p = nodeShellExec('mklink', ['/D', 'config', runconfig.use + '-config'], {
  420. inherit : true, shell: true
  421. , env: process.env
  422. }).catch((e)=>{ console.error(e) })
  423. return p;
  424. }
  425. ]
  426. any(tasks)
  427. }
  428. // Antibiotic stewardship program.
  429. // 1st use is fine.
  430. // Max vials dispense
  431. // 2nd use Pharmacy needs justification Form.
  432. // Approval after a certain period of time.
  433. }
  434. , 'g' : ()=>{
  435. if(processedArgs.h) {
  436. console.log('elxr g [modelname] => generate a model named [modelname]');
  437. console.log('elxr g => regenerate all known models');
  438. return
  439. }
  440. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  441. // console.log('Starting directory: ' + process.cwd());
  442. // try {
  443. // child = child.on('close', () => { process.chdir(label) } );
  444. // console.log('New directory: ' + process.cwd());
  445. // }
  446. // catch (err) {
  447. // console.log('chdir: ' + err);
  448. // }
  449. // child.on('close', function(){
  450. // var options = {
  451. // shell : true
  452. // , inherit : true
  453. // // , cwd : '' + process.cwd
  454. // // , env : process.env
  455. // };
  456. // nodeShellExec('git', ['init'], { inherit : true});
  457. if(0){
  458. // PB : TODO -- Special google chrome profile for tests etc.
  459. nodeShellExec('pwd', { inherit : true});
  460. //$ "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 1" http://localhost:4200/tests/index.html?grep=loopback
  461. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  462. "--profile-directory=Profile 1"
  463. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  464. }
  465. // nodeShellExec('npm', ['init', '-y'], options);
  466. // nodeShellExec('npm', ['init', '-y'], options);
  467. // })
  468. var g = {
  469. 'client' : ()=>{
  470. console.info('Creating new ember client named : ' + processedArgs._[2] ) ;
  471. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  472. stdio: ['pipe', process.stdout, process.stderr],
  473. inherit : true,
  474. shell: true,
  475. cwd : path.dirname(__dirname),
  476. env: env
  477. })
  478. }
  479. }
  480. g[processedArgs._[1]]();
  481. }
  482. }
  483. return op[label] ? op[label]() : op['start'](label);
  484. }
  485. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  486. // mysql -u root -p db_name < drop_all_tables.sql
  487. var mysql = '../xampp/mysql/bin/mysql'
  488. var mysqldump = '../xampp/mysql/bin/mysqldump'
  489. __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  490. // nodeShellExec('git', ['status']);
  491. function nodeShellExec() {
  492. var args = Array.from(arguments);
  493. args[2] ? null : args[2] = {}
  494. args[2].title ? null : args[2].title = `${args[0]} ${args[1]}`
  495. const child = spawn(...arguments);
  496. return new Promise(function(resolve, reject){
  497. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  498. // use child.stdout.setEncoding('utf8'); if you want text chunks
  499. child.stdout.setEncoding('utf8');
  500. child.stderr.setEncoding('utf8');
  501. child.stdout.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  502. child.on('error', (chunk) => { messages.push(chunk); /*console.error(chunk)*/ });
  503. child.stderr.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  504. // child.stderr.pipe(process.stderr);
  505. child.on('close', (code) => {
  506. console.log([` ${args[2].title} exited with code ${code}`])
  507. // console.log([ messages.join('') ])
  508. process.stdout.write( messages.join('') )
  509. if(code !== 0 ) return reject(code)
  510. resolve(true)
  511. });
  512. });
  513. }