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 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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. , 'pull' : (label) => {
  223. var env = Object.assign({}, process.env); // Shallow clone it.
  224. // console.dir(env)
  225. console.log('Running exlr pull : ' + path.dirname(__dirname))
  226. // nodeShellExec('cmd', ['/c', 'setup\\utility\\chess.bat', 'pull'], {
  227. // // nodeShellExec('cmd', ['/c', '..\\setup\\utility\\chess.bat', 'pull'], {
  228. // stdio: ['pipe', process.stdout, process.stderr],
  229. // inherit : true,
  230. // shell: true,
  231. // cwd : path.dirname(__dirname),
  232. // env: env
  233. // })
  234. var performPull = repo => {
  235. if(existsSync(repo)) {
  236. console.log('pulling ' + repo)
  237. nodeShellExec('git', ['pull'], {
  238. inherit : true, shell: true,
  239. cwd : repo
  240. // , env: process.env
  241. , title : `git pull ${repo}`
  242. }).catch((e)=>{ console.error(e) })
  243. }
  244. else {
  245. console.log('cloning ' + repo)
  246. nodeShellExec('git', ['clone', '//172.16.0.27/repos/' + repo + '.git'],
  247. {
  248. inherit : true, shell: true,
  249. env: process.env
  250. , title : `git clone ${'//172.16.0.27/repos/' + repo + '.git'}`
  251. }).catch((e)=>{ console.error(e) })
  252. }
  253. }
  254. if(!processedArgs.runas) gitRepos.forEach(performPull)
  255. return isRunningElevated().then(
  256. ()=> elevatedRunasRepos.forEach(performPull))
  257. .catch(
  258. () => op['runas']()
  259. )
  260. }
  261. , 'npmi' : ()=>{
  262. var tasks = [];
  263. gitRepos.forEach(repo => {
  264. console.log('npm i for ' + repo)
  265. // nodeShellExec('pwd', [], {
  266. // // inherit : true, shell: true
  267. // cwd : repo
  268. // // , env: process.env
  269. // , title : `pwd for ${repo}`
  270. // }).catch((e)=>{ console.error(e) })
  271. nodeShellExec('rm', ['package-lock.json'], {
  272. inherit : true, shell: true
  273. , cwd : repo
  274. , env: process.env
  275. , title : `rm 'package-lock.json' for ${repo}`
  276. }).catch((e)=>{ console.error(e) })
  277. tasks.push(()=>{
  278. var p = nodeShellExec('npm', ['i'], {
  279. inherit : true, shell: true
  280. , cwd : repo
  281. , env: process.env
  282. , title : `npm i for ${repo}`
  283. }).catch((e)=>{ console.error(e) })
  284. return p;
  285. })
  286. })
  287. any(tasks);
  288. }
  289. , 'start' : (label)=>{
  290. console.log('Starting Elixir Server.');
  291. var env = Object.assign({}, process.env); // Shallow clone it.
  292. // console.dir(env)
  293. env.NODE_ENV = label || 'development';
  294. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  295. nodeShellExec('node', ['--inspect=9228', 'elixir/server.js'], {
  296. // inherit : true,
  297. shell: true, detached: true,
  298. cwd : 'elixir-server',
  299. env: env
  300. })
  301. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  302. // inherit : true,
  303. // shell: true, detached: true,
  304. // cwd : 'qms/server',
  305. // env: env,
  306. // shell : true
  307. // })
  308. nodeShellExec('ember', ['s'], {
  309. // inherit : true,
  310. shell: true, detached: true,
  311. cwd : 'client/',
  312. env: env
  313. })
  314. }
  315. , 'use' : ()=>{
  316. if(!processedArgs.runas){
  317. try {
  318. var runconfig = require('./run.js')
  319. if(processedArgs._[1] && runconfig.use === processedArgs._[1]) {
  320. return;
  321. }
  322. else runconfig.use = processedArgs._[1];
  323. fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
  324. }
  325. catch(e) {
  326. runconfig = { use : processedArgs._[1] };
  327. fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
  328. }
  329. op['runas']()
  330. }
  331. else {
  332. var runconfig = require('../run.js')
  333. console.log('runconfig.use : ' + runconfig.use)
  334. var tasks = [
  335. ()=>{
  336. var p = nodeShellExec('rm', ['config'], {
  337. inherit : true, shell: true
  338. , cwd : repo
  339. , env: process.env
  340. , title : `rm 'package-lock.json' for ${repo}`
  341. }).catch((e)=>{ console.error(e) })
  342. return p;
  343. },
  344. ()=>{
  345. var p = nodeShellExec('rm', ['data'], {
  346. inherit : true, shell: true
  347. , cwd : repo
  348. , env: process.env
  349. , title : `rm 'package-lock.json' for ${repo}`
  350. }).catch((e)=>{ console.error(e) })
  351. return p;
  352. },
  353. ()=>{
  354. var p = nodeShellExec('mklink', ['/D', 'data', runconfig.use + '-data'], {
  355. inherit : true, shell: true
  356. , env: process.env
  357. }).catch((e)=>{ console.error(e) })
  358. return p;
  359. },
  360. ()=>{
  361. var p = nodeShellExec('mklink', ['/D', 'config', runconfig.use + '-config'], {
  362. inherit : true, shell: true
  363. , env: process.env
  364. }).catch((e)=>{ console.error(e) })
  365. return p;
  366. }
  367. ]
  368. any(tasks)
  369. }
  370. // Antibiotic stewardship program.
  371. // 1st use is fine.
  372. // Max vials dispense
  373. // 2nd use Pharmacy needs justification Form.
  374. // Approval after a certain period of time.
  375. }
  376. , 'g' : ()=>{
  377. if(processedArgs.h) {
  378. console.log('elxr g [modelname] => generate a model named [modelname]');
  379. console.log('elxr g => regenerate all known models');
  380. return
  381. }
  382. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  383. // console.log('Starting directory: ' + process.cwd());
  384. // try {
  385. // child = child.on('close', () => { process.chdir(label) } );
  386. // console.log('New directory: ' + process.cwd());
  387. // }
  388. // catch (err) {
  389. // console.log('chdir: ' + err);
  390. // }
  391. // child.on('close', function(){
  392. // var options = {
  393. // shell : true
  394. // , inherit : true
  395. // // , cwd : '' + process.cwd
  396. // // , env : process.env
  397. // };
  398. // nodeShellExec('git', ['init'], { inherit : true});
  399. if(0){
  400. // PB : TODO -- Special google chrome profile for tests etc.
  401. nodeShellExec('pwd', { inherit : true});
  402. //$ "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 1" http://localhost:4200/tests/index.html?grep=loopback
  403. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  404. "--profile-directory=Profile 1"
  405. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  406. }
  407. // nodeShellExec('npm', ['init', '-y'], options);
  408. // nodeShellExec('npm', ['init', '-y'], options);
  409. // })
  410. var g = {
  411. 'client' : ()=>{
  412. console.info('Creating new ember client named : ' + processedArgs._[2] ) ;
  413. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  414. stdio: ['pipe', process.stdout, process.stderr],
  415. inherit : true,
  416. shell: true,
  417. cwd : path.dirname(__dirname),
  418. env: env
  419. })
  420. }
  421. }
  422. g[processedArgs._[1]]();
  423. }
  424. }
  425. return op[label] ? op[label]() : op['start'](label);
  426. }
  427. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  428. // mysql -u root -p db_name < drop_all_tables.sql
  429. var mysql = '../xampp/mysql/bin/mysql'
  430. var mysqldump = '../xampp/mysql/bin/mysqldump'
  431. __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  432. // nodeShellExec('git', ['status']);
  433. function nodeShellExec() {
  434. var args = Array.from(arguments);
  435. const child = spawn(...arguments);
  436. return new Promise(function(resolve, reject){
  437. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  438. // use child.stdout.setEncoding('utf8'); if you want text chunks
  439. child.stdout.setEncoding('utf8');
  440. child.stderr.setEncoding('utf8');
  441. child.stdout.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  442. child.on('error', (chunk) => { messages.push(chunk); /*console.error(chunk)*/ });
  443. child.stderr.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  444. // child.stderr.pipe(process.stderr);
  445. child.on('close', (code) => {
  446. console.log([` ${args[2].title} exited with code ${code}`])
  447. // console.log([ messages.join('') ])
  448. process.stdout.write( messages.join('') )
  449. if(code !== 0 ) return reject(code)
  450. resolve(true)
  451. });
  452. });
  453. }