選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

index.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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. , 'ember-searchable-select'
  111. , 'loopback-component-jsonapi'
  112. , 'elixir-config'
  113. , 'cihsr-config'
  114. , 'cihsr-data'
  115. , 'elixir-data'
  116. , 'loopback-connector-ds'
  117. , 'chess-server-lib'
  118. , 'setup'
  119. , 'elixir-client-todos'
  120. , 'elixir-client-unlinked'
  121. , 'elixir-client'
  122. , 'ember-service-worker'
  123. , 'ember-service-worker-asset-cache'
  124. , 'ember-service-worker-cache-fallback'
  125. , 'ember-service-worker-index'
  126. , 'ember-sw-client-route'
  127. , 'global-this'
  128. ]
  129. // Repositiories that have symlinks that required elevated priviletes in windows to create symlinks
  130. //
  131. var elevatedRunasRepos = [
  132. 'elixir-server'
  133. , 'cihsr-server'
  134. , 'chess-server'
  135. ]
  136. var env = Object.assign({}, process.env); // Shallow clone it.
  137. var __runcmd = function(label){
  138. var op = {
  139. 'h' : ()=>{ console.log(cli + ' ' + ver + ' ' + help); return '-h' }
  140. , 'upgrade' : ()=>{
  141. console.log('upgrade.......')
  142. var tasks = [
  143. ()=>{
  144. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  145. inherit : true, shell: true
  146. , env: process.env
  147. }).catch((e)=>{ console.error(e) })
  148. p.position = 1;
  149. console.log('One')
  150. return p;
  151. }
  152. , ()=>{
  153. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  154. inherit : true, shell: true
  155. , env: process.env
  156. }).catch((e)=>{ console.error(e) })
  157. p.position = 2;
  158. console.log('Two')
  159. return p;
  160. }
  161. , ()=>{
  162. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  163. inherit : true, shell: true
  164. , env: process.env
  165. }).catch((e)=>{ console.error(e) })
  166. p.position = 3;
  167. console.log('Three')
  168. return p;
  169. }
  170. , ()=>{
  171. var p = nodeShellExec('n', ['latest'], {
  172. inherit : true, shell: true
  173. , env: process.env
  174. }).catch((e)=>{ console.error(e) })
  175. p.position = 4;
  176. console.log('Four')
  177. return p;
  178. }
  179. ]
  180. any(tasks)
  181. console.log('.......done')
  182. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  183. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  184. console.info('Uninstalling existing ember globally') ;
  185. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  186. stdio: ['pipe', process.stdout, process.stderr],
  187. inherit : true,
  188. shell: true,
  189. cwd : path.dirname(__dirname),
  190. env: env
  191. })
  192. step1.on('close', ()=>{
  193. console.info('Installing ember globally') ;
  194. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  195. stdio: ['pipe', process.stdout, process.stderr],
  196. inherit : true,
  197. shell: true,
  198. cwd : path.dirname(__dirname),
  199. env: env
  200. })
  201. step2.on('close', ()=>{
  202. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  203. stdio: ['pipe', process.stdout, process.stderr],
  204. inherit : true,
  205. shell: true,
  206. cwd : path.dirname(__dirname),
  207. env: env
  208. })
  209. })
  210. })
  211. }
  212. , 'runas' : ()=>{
  213. return isRunningElevated().then(
  214. () => op[ processedArgs.label || processedArgs._[0] || 'h']()
  215. )
  216. .catch(()=>{
  217. console.log('Not Elevated');
  218. console.dir(processedArgs)
  219. console.log('Requesting Elevated Privileges for : ' + `--insptec-brk elxr ${processedArgs._[0]} ${processedArgs._[1]} --runas=true`)
  220. nodeShellExec('MSHTA', [`javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('node', 'elxr ${processedArgs._[0]} ${processedArgs._[1]} --runas=true', '', 'runas', 1);close();`]
  221. , {
  222. // inherit : true
  223. // , shell: true
  224. env: process.env
  225. , title : `runas`
  226. }
  227. );
  228. })
  229. }
  230. , 'push' : ()=>{
  231. if(!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  232. // init remote bare from local
  233. // pushandinitremotebare
  234. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  235. // connect to repo server -- net use 172.16.0.27
  236. // cd 172.16.0.27/repos/
  237. // mkdir repo.git
  238. // cd repo.git
  239. // git init --bare
  240. // cd localrepo
  241. // git remote rename origin githubclone
  242. // git remote add origin //172.16.0.27/repos/repo.git
  243. // git push origin master
  244. var repo = processedArgs._[1];
  245. var defaultRepoServer = '//172.16.0.27/repos'
  246. var sequentialTaskShellCommands = [];
  247. if(!existsSync(`Z:/${repo}.git`)){
  248. sequentialTaskShellCommands = [
  249. // ['net', ['use', 'Z:', defaultRepoServer.replace('/','\\')], {
  250. // inherit : true, shell: true
  251. // , env: process.env
  252. // }]
  253. ['pwd', { cwd : 'Z:', inherit : true}]
  254. , ['mkdir', [`${repo}.git`], {
  255. cwd : `Z:`
  256. , inherit : true, shell: true
  257. , env: process.env
  258. }]
  259. , ['pwd', { cwd : `Z:/${repo}.git`, inherit : true}]
  260. , ['git', ['init', '--bare'], { cwd : `Z:/${repo}.git`
  261. , inherit : true, shell: true
  262. , env: process.env
  263. }]
  264. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd : `${repo}`}, (err)=>{
  265. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  266. } ] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  267. , ['git', ['remote', 'add', 'origin', `${defaultRepoServer}/${repo}.git`], { cwd : `${repo}`}]
  268. ]
  269. if(!existsSync(`Z:`)){
  270. sequentialTaskShellCommands.splice(0,0, ['net', ['use', 'Z:', defaultRepoServer.replace(/\//gm,'\\')], {
  271. inherit : true, shell: true
  272. , env: process.env
  273. }])
  274. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  275. // throw 'done'
  276. }
  277. }
  278. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd : `${repo}`}])
  279. // console.dir(sequentialTaskShellCommands);
  280. var tasks = [];
  281. sequentialTaskShellCommands.forEach(shellcmd => {
  282. // console.log(shellcmd)
  283. tasks.push(()=>{
  284. var p = nodeShellExec.apply(null, shellcmd.slice(0,3)).catch((e)=>{ if(shellcmd[3]) { return shellcmd[3]() } else { console.error(e);} })
  285. return p;
  286. })
  287. })
  288. any(tasks);
  289. }
  290. , 'pull' : (label) => {
  291. var env = Object.assign({}, process.env); // Shallow clone it.
  292. // console.dir(env)
  293. console.log('Running exlr pull : ' + path.dirname(__dirname))
  294. // nodeShellExec('cmd', ['/c', 'setup\\utility\\chess.bat', 'pull'], {
  295. // // nodeShellExec('cmd', ['/c', '..\\setup\\utility\\chess.bat', 'pull'], {
  296. // stdio: ['pipe', process.stdout, process.stderr],
  297. // inherit : true,
  298. // shell: true,
  299. // cwd : path.dirname(__dirname),
  300. // env: env
  301. // })
  302. var performPull = repo => {
  303. if(existsSync(repo)) {
  304. console.log('pulling ' + repo)
  305. nodeShellExec('git', ['pull'], {
  306. inherit : true, shell: true,
  307. cwd : repo
  308. // , env: process.env
  309. , title : `git pull ${repo}`
  310. }).catch((e)=>{ console.error(e) })
  311. }
  312. else {
  313. console.log('cloning ' + repo)
  314. nodeShellExec('git', ['clone', '//172.16.0.27/repos/' + repo + '.git'],
  315. {
  316. inherit : true, shell: true,
  317. env: process.env
  318. , title : `git clone ${'//172.16.0.27/repos/' + repo + '.git'}`
  319. }).catch((e)=>{ console.error(e) })
  320. }
  321. }
  322. if(!processedArgs.runas) gitRepos.forEach(performPull)
  323. return isRunningElevated().then(
  324. ()=> elevatedRunasRepos.forEach(performPull))
  325. .catch(
  326. () => op['runas']()
  327. )
  328. }
  329. , 'npmi' : ()=>{
  330. var tasks = [];
  331. gitRepos.forEach(repo => {
  332. console.log('npm i for ' + repo)
  333. // nodeShellExec('pwd', [], {
  334. // // inherit : true, shell: true
  335. // cwd : repo
  336. // // , env: process.env
  337. // , title : `pwd for ${repo}`
  338. // }).catch((e)=>{ console.error(e) })
  339. nodeShellExec('rm', ['package-lock.json'], {
  340. inherit : true, shell: true
  341. , cwd : repo
  342. , env: process.env
  343. , title : `rm 'package-lock.json' for ${repo}`
  344. }).catch((e)=>{ console.error(e) })
  345. tasks.push(()=>{
  346. var p = nodeShellExec('npm', ['i'], {
  347. inherit : true, shell: true
  348. , cwd : repo
  349. , env: process.env
  350. , title : `npm i for ${repo}`
  351. }).catch((e)=>{ console.error(e) })
  352. return p;
  353. })
  354. })
  355. any(tasks);
  356. }
  357. , 'start' : (label)=>{
  358. console.log('Starting Elixir Server.');
  359. var env = Object.assign({}, process.env); // Shallow clone it.
  360. // console.dir(env)
  361. env.NODE_ENV = label || 'development';
  362. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  363. nodeShellExec('node', ['--inspect=9228', 'elixir/server.js'], {
  364. // inherit : true,
  365. shell: true, detached: true,
  366. cwd : 'elixir-server',
  367. env: env
  368. })
  369. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  370. // inherit : true,
  371. // shell: true, detached: true,
  372. // cwd : 'qms/server',
  373. // env: env,
  374. // shell : true
  375. // })
  376. nodeShellExec('ember', ['s'], {
  377. // inherit : true,
  378. shell: true, detached: true,
  379. cwd : 'client/',
  380. env: env
  381. })
  382. }
  383. , 'use' : ()=>{
  384. if(!processedArgs.runas){
  385. try {
  386. var runconfig = require('./run.js')
  387. if(processedArgs._[1] && runconfig.use === processedArgs._[1]) {
  388. return;
  389. }
  390. else runconfig.use = processedArgs._[1];
  391. fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
  392. }
  393. catch(e) {
  394. runconfig = { use : processedArgs._[1] };
  395. fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
  396. }
  397. op['runas']()
  398. }
  399. else {
  400. var runconfig = require('../run.js')
  401. console.log('runconfig.use : ' + runconfig.use)
  402. var tasks = [
  403. ()=>{
  404. if(existsSync('config')) {
  405. var p = nodeShellExec('rmdir', ['config'], {
  406. inherit : true, shell: true
  407. , env: process.env
  408. , title : `rmdir config`
  409. }).catch((e)=>{ console.error(e) })
  410. return p;
  411. }
  412. else return Promise.resolve(true);
  413. },
  414. ()=>{
  415. if(existsSync('data')) {
  416. var p = nodeShellExec('rmdir', ['data'], {
  417. inherit : true, shell: true
  418. , env: process.env
  419. , title : `rm data`
  420. }).catch((e)=>{ console.error(e) })
  421. return p;
  422. }
  423. else return Promise.resolve(true);
  424. },
  425. ()=>{
  426. var p = nodeShellExec('mklink', ['/D', 'data', runconfig.use + '-data'], {
  427. inherit : true, shell: true
  428. , env: process.env
  429. }).catch((e)=>{ console.error(e) })
  430. return p;
  431. },
  432. ()=>{
  433. // Use junctions to avoid npm package issues
  434. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config'], {
  435. inherit : true, shell: true
  436. , env: process.env
  437. }).catch((e)=>{ console.error(e) })
  438. return p;
  439. }
  440. ]
  441. any(tasks)
  442. }
  443. // Antibiotic stewardship program.
  444. // 1st use is fine.
  445. // Max vials dispense
  446. // 2nd use Pharmacy needs justification Form.
  447. // Approval after a certain period of time.
  448. }
  449. , 'g' : ()=>{
  450. if(processedArgs.h) {
  451. console.log('elxr g [modelname] => generate a model named [modelname]');
  452. console.log('elxr g => regenerate all known models');
  453. return
  454. }
  455. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  456. // console.log('Starting directory: ' + process.cwd());
  457. // try {
  458. // child = child.on('close', () => { process.chdir(label) } );
  459. // console.log('New directory: ' + process.cwd());
  460. // }
  461. // catch (err) {
  462. // console.log('chdir: ' + err);
  463. // }
  464. // child.on('close', function(){
  465. // var options = {
  466. // shell : true
  467. // , inherit : true
  468. // // , cwd : '' + process.cwd
  469. // // , env : process.env
  470. // };
  471. // nodeShellExec('git', ['init'], { inherit : true});
  472. if(0){
  473. // PB : TODO -- Special google chrome profile for tests etc.
  474. nodeShellExec('pwd', { inherit : true});
  475. //$ "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 1" http://localhost:4200/tests/index.html?grep=loopback
  476. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  477. "--profile-directory=Profile 1"
  478. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  479. }
  480. // nodeShellExec('npm', ['init', '-y'], options);
  481. // nodeShellExec('npm', ['init', '-y'], options);
  482. // })
  483. var g = {
  484. 'client' : ()=>{
  485. console.info('Creating new ember client named : ' + processedArgs._[2] ) ;
  486. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  487. stdio: ['pipe', process.stdout, process.stderr],
  488. inherit : true,
  489. shell: true,
  490. cwd : path.dirname(__dirname),
  491. env: env
  492. })
  493. }
  494. }
  495. g[processedArgs._[1]]();
  496. }
  497. }
  498. return op[label] ? op[label]() : op['start'](label);
  499. }
  500. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  501. // mysql -u root -p db_name < drop_all_tables.sql
  502. var mysql = '../xampp/mysql/bin/mysql'
  503. var mysqldump = '../xampp/mysql/bin/mysqldump'
  504. __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  505. // nodeShellExec('git', ['status']);
  506. function nodeShellExec() {
  507. var args = Array.from(arguments);
  508. args[2] ? null : args[2] = {}
  509. args[2].title ? null : args[2].title = `${args[0]} ${args[1]}`
  510. const child = spawn(...arguments);
  511. return new Promise(function(resolve, reject){
  512. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  513. // use child.stdout.setEncoding('utf8'); if you want text chunks
  514. child.stdout.setEncoding('utf8');
  515. child.stderr.setEncoding('utf8');
  516. child.stdout.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  517. child.on('error', (chunk) => { messages.push(chunk); /*console.error(chunk)*/ });
  518. child.stderr.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  519. // child.stderr.pipe(process.stderr);
  520. child.on('close', (code) => {
  521. console.log([` ${args[2].title} exited with code ${code}`])
  522. // console.log([ messages.join('') ])
  523. process.stdout.write( messages.join('') )
  524. if(code !== 0 ) return reject(code)
  525. resolve(true)
  526. });
  527. });
  528. }