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

index.js 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. // --------------
  2. // elxr
  3. // A cli tool for elixr.
  4. // PB : TODO --
  5. // runas bypass non elevated tasks when we request privelege
  6. // runas message is always error needs to be fixed.
  7. // runas wait needs to be parallelized.
  8. // suppress elevation check error messages
  9. // support runas lauched directly from shell.
  10. // pass in environment in hta to shellexecute.
  11. const { existsSync } = require('fs');
  12. const fs = require('fs')
  13. const { spawn, spawnSync } = require('child_process');
  14. const cliargs = require('../elxr/cliargs'); // Use minimist...
  15. const processedArgs = cliargs(process.argv.slice(2));
  16. console.dir(processedArgs)
  17. var globSync = require('glob').sync;
  18. var path = require('path');
  19. const { isMaster } = require('cluster');
  20. // Serialize a set of functions that will execute to return a promises one after the other.
  21. // Will stop when any one fails unless continueOnFailure is true.
  22. // All tasks in iterables can be functions or promises.
  23. // promises as usual can return other promises or resolve to either truthy or falsy values.
  24. // functions must return a promise
  25. function any(iterable, continueOnFailure) {
  26. return iterable.reduce(
  27. (p, fn, i ,a) => {
  28. // console.log('accumulator :');
  29. // console.log(p);
  30. if(Promise.resolve(p) === p ) {
  31. return p.then((pVal) => {
  32. // Falsy values are task failure.
  33. if(!pVal) {
  34. console.warn('Possible failure for result : ' + pVal)
  35. console.warn(a[i-1])
  36. fn ? console.error("Fn : " + fn.toString()) : null;
  37. }
  38. // Truthy values are failures if obj has error=true.
  39. if(pVal && pVal.error) { console.error('Failed : ' + pVal.message + ' ' + pVal) }
  40. if(Promise.resolve(pVal) === pVal) {
  41. // Passed in function retured a promise. We still need to wait for it.
  42. pVal.then((pVal)=>{
  43. // console.log('Then --pVal = ' + pVal + ' bContinue = ' + continueOnFailure ); console.log(p);
  44. if(!pVal && !continueOnFailure) {
  45. console.error(`E1 : i = ${i} : pVal :` + pVal);
  46. console.error('debugData 2 -------------------');
  47. console.log("Cancelling remaining...");
  48. throw 'Failed in reduce 1 '
  49. }
  50. if(!fn && !continueOnFailure) { console.error('Error : No task specified.'); throw false;}
  51. else if(!fn) return false;
  52. return (Promise.resolve(fn) === fn ) ? fn : fn() ;
  53. })
  54. }
  55. else {
  56. // We will stop on null resolved values on any one task unless continueOnFailure is true.
  57. // console.log('Then --pVal = ' + pVal + ' bContinue = ' + continueOnFailure ); console.log(p);
  58. if(!pVal && !continueOnFailure) {
  59. console.error(`E2 : i = ${i} : pVal :` + pVal);
  60. console.error('debugData 2 -------------------');
  61. console.log("Cancelling remaining...");
  62. throw 'Failed in reduce 2 '
  63. }
  64. if(!fn && !continueOnFailure) { console.error('Error : No task specified.'); throw false;}
  65. else if(!fn) return false;
  66. return (Promise.resolve(fn) === fn ) ? fn : fn() ;
  67. }
  68. }).catch((error) => {
  69. console.error(`E3 : i = ${i} `);
  70. fn ? console.error("Fn : " + fn.toString()) : null;
  71. console.error('debugData 3-------------------------');
  72. throw 'Failed in reduce 3 '
  73. })
  74. }
  75. else if(!p) {
  76. console.log("Bypass on failure");
  77. return false;
  78. }
  79. }
  80. , Promise.resolve(true)
  81. );
  82. }
  83. var __isElevated = null;
  84. var isRunningElevated = ()=>{
  85. if(__isElevated === null) {
  86. return nodeShellExec( "fsutil", ["dirty", "query", "C:"], {
  87. inherit : true
  88. // , shell: true
  89. , stdio: 'ignore'
  90. , env: process.env
  91. , title : `check privileged execution mode using "fsutil dirty query C:"`
  92. }).then((exitcode)=>{
  93. console.log('Elevated')
  94. __isElevated = true;
  95. return true;
  96. }).catch(()=>{
  97. __isElevated = false;
  98. console.log('Not Elevated');
  99. throw false;
  100. });
  101. }
  102. else return Promise.resolve(__isElevated);
  103. }
  104. var cli = 'elxr';
  105. var ver = '#unversioned';
  106. var help = '#unkown list of commands... please refer dveloper documentation for ' + cli;
  107. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  108. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  109. var dbForLabel = function(label){
  110. var dbsForLabel = {
  111. devmysql : 'mysql'
  112. , development : 'mssql'
  113. , production : 'mssql'
  114. }
  115. return dbsForLabel[label] || 'mysql'
  116. }
  117. // Relevant git repos
  118. var gitRepos = [
  119. 'ember-masonry-grid'
  120. , 'bbhverse'
  121. , 'clientverse'
  122. , 'serververse'
  123. , 'client'
  124. // , 'client/server'
  125. , 'elxr'
  126. , 'ember-searchable-select'
  127. , 'loopback-component-jsonapi'
  128. , 'elixir-config-development'
  129. , 'elixir-config-test'
  130. , 'cihsr-config'
  131. , 'cihsr-data'
  132. , 'elixir-data'
  133. , 'loopback-connector-ds'
  134. , 'chess-server-lib'
  135. , 'setup'
  136. , 'elixir-client-todos'
  137. , 'elixir-client-unlinked'
  138. , 'elixir-client'
  139. , 'ember-service-worker'
  140. , 'ember-service-worker-asset-cache'
  141. , 'ember-service-worker-cache-fallback'
  142. , 'ember-service-worker-index'
  143. , 'ember-sw-client-route'
  144. , 'global-this'
  145. ]
  146. // Repositiories that have symlinks that required elevated priviletes in windows to create symlinks
  147. //
  148. var elevatedRunasRepos = [
  149. 'elixir-server'
  150. , 'cihsr-server'
  151. , 'chess-server'
  152. ]
  153. var productionRepos = [
  154. 'elixir-config-production'
  155. ]
  156. var productionIsAllowed = true;
  157. if(productionIsAllowed) gitRepos = gitRepos.concat(productionRepos)
  158. var env = Object.assign({}, process.env); // Shallow clone it.
  159. var __runcmd = function(label){
  160. var op = {
  161. 'h' : ()=>{ console.log(cli + ' ' + ver + ' ' + help); return '-h' }
  162. , 'undefined' : ()=>{ return op.h(); }
  163. , 'upgrade' : ()=>{
  164. console.log('upgrade.......')
  165. var tasks = [
  166. ()=>{
  167. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  168. inherit : true, shell: true
  169. , env: process.env
  170. }).catch((e)=>{ console.error(e) })
  171. p.position = 1;
  172. console.log('One')
  173. return p;
  174. }
  175. , ()=>{
  176. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  177. inherit : true, shell: true
  178. , env: process.env
  179. }).catch((e)=>{ console.error(e) })
  180. p.position = 2;
  181. console.log('Two')
  182. return p;
  183. }
  184. , ()=>{
  185. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  186. inherit : true, shell: true
  187. , env: process.env
  188. }).catch((e)=>{ console.error(e) })
  189. p.position = 3;
  190. console.log('Three')
  191. return p;
  192. }
  193. , ()=>{
  194. var p = nodeShellExec('n', ['latest'], {
  195. inherit : true, shell: true
  196. , env: process.env
  197. }).catch((e)=>{ console.error(e) })
  198. p.position = 4;
  199. console.log('Four')
  200. return p;
  201. }
  202. ]
  203. any(tasks)
  204. console.log('.......done')
  205. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  206. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  207. console.info('Uninstalling existing ember globally') ;
  208. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  209. stdio: ['pipe', process.stdout, process.stderr],
  210. inherit : true,
  211. shell: true,
  212. cwd : path.dirname(__dirname),
  213. env: env
  214. })
  215. step1.on('close', ()=>{
  216. console.info('Installing ember globally') ;
  217. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  218. stdio: ['pipe', process.stdout, process.stderr],
  219. inherit : true,
  220. shell: true,
  221. cwd : path.dirname(__dirname),
  222. env: env
  223. })
  224. step2.on('close', ()=>{
  225. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  226. stdio: ['pipe', process.stdout, process.stderr],
  227. inherit : true,
  228. shell: true,
  229. cwd : path.dirname(__dirname),
  230. env: env
  231. })
  232. })
  233. })
  234. }
  235. , 'runas' : ()=>{
  236. return isRunningElevated().then(
  237. (isElevated) => {
  238. if(isElevated) {
  239. try {
  240. op[ processedArgs.label || processedArgs._[0] || 'h']()
  241. }
  242. catch(e){
  243. console.error('Error Invalid command : ' + e)
  244. fs.writeFileSync('run.done', 'success')
  245. }
  246. finally {
  247. }
  248. } else throw false;
  249. }
  250. )
  251. .catch(()=>{
  252. console.log('Requesting Elevated Privileges');
  253. // Wait for the runas to complete before we read it.
  254. try {
  255. fs.unlinkSync('run.done')
  256. fs.unlinkSync('run.log')
  257. }
  258. catch(e) { } //Ignore
  259. // PB : TODO -- Convert all the cli args back to string.
  260. var namedArgs = [];
  261. Object.keys(processedArgs).forEach((v)=>{ v!='_' ? namedArgs.push('--'+v+'='+processedArgs[v]) : null; })
  262. //console.log(' namedArgs : ' + namedArgs)
  263. process.env.NODE_ENV = process.env.NODE_ENV || 'development';
  264. var args = [__dirname + '/windowselevate.hta'].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  265. nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  266. , {
  267. inherit : true
  268. , shell: true
  269. , env: process.env
  270. , runas : 'self'
  271. , title : `runas`
  272. }
  273. ).then(()=>{
  274. // runas returned.
  275. try {
  276. var runaslog = JSON.parse('[ { "success" : true, "result" : "runas Log" }' + fs.readFileSync('run.log', { flags : 'a+'}) + ']');
  277. runaslog.forEach((logEntry)=>{
  278. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  279. })
  280. }
  281. catch(e){
  282. // Ignore nonexistent log
  283. console.warn('Run log error probably was not created by runas : ' + e)
  284. }
  285. })
  286. .catch(err => console.error('Elevation failed : ' + err));
  287. })
  288. }
  289. , 'push' : ()=>{
  290. if(!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  291. // init remote bare from local
  292. // pushandinitremotebare
  293. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  294. // connect to repo server -- net use 172.16.0.27
  295. // cd 172.16.0.27/repos/
  296. // mkdir repo.git
  297. // cd repo.git
  298. // git init --bare
  299. // cd localrepo
  300. // git remote rename origin githubclone
  301. // git remote add origin //172.16.0.27/repos/repo.git
  302. // git push origin master
  303. var repo = processedArgs._[1];
  304. var defaultRepoServer = '//172.16.0.27/repos'
  305. var sequentialTaskShellCommands = [];
  306. if(!existsSync(`Z:/${repo}.git`)){
  307. sequentialTaskShellCommands = [
  308. // ['net', ['use', 'Z:', defaultRepoServer.replace('/','\\')], {
  309. // inherit : true, shell: true
  310. // , env: process.env
  311. // }]
  312. ['pwd', { cwd : 'Z:', inherit : true}]
  313. , ['mkdir', [`${repo}.git`], {
  314. cwd : `Z:`
  315. , inherit : true, shell: true
  316. , env: process.env
  317. }]
  318. , ['pwd', { cwd : `Z:/${repo}.git`, inherit : true}]
  319. , ['git', ['init', '--bare'], { cwd : `Z:/${repo}.git`
  320. , inherit : true, shell: true
  321. , env: process.env
  322. }]
  323. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd : `${repo}`}, (err)=>{
  324. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  325. } ] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  326. , ['git', ['remote', 'add', 'origin', `${defaultRepoServer}/${repo}.git`], { cwd : `${repo}`}]
  327. ]
  328. if(!existsSync(`Z:`)){
  329. sequentialTaskShellCommands.splice(0,0, ['net', ['use', 'Z:', defaultRepoServer.replace(/\//gm,'\\')], {
  330. inherit : true, shell: true
  331. , env: process.env
  332. }])
  333. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  334. // throw 'done'
  335. }
  336. }
  337. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd : `${repo}`}])
  338. // console.dir(sequentialTaskShellCommands);
  339. var tasks = [];
  340. sequentialTaskShellCommands.forEach(shellcmd => {
  341. // console.log(shellcmd)
  342. tasks.push(()=>{
  343. var p = nodeShellExec.apply(null, shellcmd.slice(0,3)).catch((e)=>{ if(shellcmd[3]) { return shellcmd[3]() } else { console.error(e);} })
  344. return p;
  345. })
  346. })
  347. any(tasks);
  348. }
  349. , 'pull' : (label) => {
  350. // Usage :
  351. // elxr pull -- Defaults to run config
  352. var env = Object.assign({}, process.env); // Shallow clone it.
  353. // console.dir(env)
  354. console.log('Running exlr pull : ' + path.dirname(__dirname))
  355. // nodeShellExec('cmd', ['/c', 'setup\\utility\\chess.bat', 'pull'], {
  356. // // nodeShellExec('cmd', ['/c', '..\\setup\\utility\\chess.bat', 'pull'], {
  357. // stdio: ['pipe', process.stdout, process.stderr],
  358. // inherit : true,
  359. // shell: true,
  360. // cwd : path.dirname(__dirname),
  361. // env: env
  362. // })
  363. var performPull = (repo) => {
  364. if(existsSync(repo)) {
  365. console.log('pulling ' + repo)
  366. return nodeShellExec('git', ['pull'], {
  367. inherit : true, shell: true,
  368. cwd : repo
  369. // , env: process.env
  370. , runas : processedArgs.runas
  371. , title : `git pull ${repo}`
  372. }).catch((e)=>{ console.error(e) })
  373. }
  374. else {
  375. console.log('cloning ' + repo)
  376. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', '//172.16.0.27/repos/' + repo + '.git'],
  377. {
  378. inherit : true, shell: true,
  379. env: process.env
  380. , runas : processedArgs.runas
  381. }).catch((e)=>{ console.error(e) }).then(()=>{
  382. return nodeShellExec('git', ['config', '--replace-all' , 'core.symlinks', true],
  383. {
  384. inherit : true, shell: true,
  385. env: process.env
  386. , cwd : repo
  387. , runas : processedArgs.runas
  388. , title : `git core.symlinks --replace-all true for ${'//172.16.0.27/repos/' + repo + '.git'}`
  389. })
  390. })
  391. }
  392. }
  393. if(!processedArgs.runas) gitRepos.forEach(performPull)
  394. return isRunningElevated().then(
  395. (isElevated) => {
  396. if(isElevated) {
  397. any(elevatedRunasRepos.map((repo)=>performPull(repo))).then(()=>{
  398. fs.writeFileSync('run.done', 'success')
  399. }).catch(()=>{
  400. fs.writeFileSync('run.done', 'error')
  401. })
  402. }
  403. else throw false;
  404. }
  405. ).catch(
  406. () => {
  407. op['runas']()
  408. }
  409. )
  410. }
  411. , 'npmi' : ()=>{
  412. var tasks = [];
  413. gitRepos.forEach(repo => {
  414. console.log('npm i for ' + repo)
  415. // nodeShellExec('pwd', [], {
  416. // // inherit : true, shell: true
  417. // cwd : repo
  418. // // , env: process.env
  419. // , title : `pwd for ${repo}`
  420. // }).catch((e)=>{ console.error(e) })
  421. nodeShellExec('rm', ['package-lock.json'], {
  422. inherit : true, shell: true
  423. , cwd : repo
  424. , env: process.env
  425. , title : `rm 'package-lock.json' for ${repo}`
  426. }).catch((e)=>{ console.error(e) })
  427. tasks.push(()=>{
  428. var p = nodeShellExec('npm', ['i'], {
  429. inherit : true, shell: true
  430. , cwd : repo
  431. , env: process.env
  432. , title : `npm i for ${repo}`
  433. }).catch((e)=>{ console.error(e) })
  434. return p;
  435. })
  436. })
  437. any(tasks);
  438. }
  439. , 'start' : (label)=>{
  440. console.log('Starting Elixir Server.');
  441. var env = Object.assign({}, process.env); // Shallow clone it.
  442. // console.dir(env)
  443. env.NODE_ENV = process.env.NODE_ENV || 'development';
  444. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  445. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  446. // cmd = 'node'
  447. var childPromise = nodeShellExec(cmd, ['--inspect=9228', 'elixir/server.js'], {
  448. // inherit : true,
  449. shell: true,
  450. detached: true,
  451. stdio: 'ignore',
  452. cwd : 'elixir-server'
  453. , env: env
  454. })
  455. var child = childPromise.process;
  456. if (typeof child.pid !== 'undefined') {
  457. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  458. encoding: 'utf8'
  459. })
  460. }
  461. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  462. // inherit : true,
  463. // shell: true, detached: true,
  464. // cwd : 'qms/server',
  465. // env: env,
  466. // shell : true
  467. // })
  468. // nodeShellExec('ember', ['s'], {
  469. // // inherit : true,
  470. // shell: true, detached: true,
  471. // cwd : 'client/',
  472. // env: env
  473. // })
  474. var childPromise = nodeShellExec('ember', ['s'], {
  475. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  476. // PB : TODO -- ember debugging.
  477. // inherit : true,
  478. shell: true,
  479. detached: true,
  480. stdio: 'ignore',
  481. cwd : 'client'
  482. , env: env
  483. })
  484. // .catch(e=>console.error(e))
  485. child = childPromise.process;
  486. if (typeof child.pid !== 'undefined') {
  487. fs.writeFileSync('.client.server.pid', child.pid, {
  488. encoding: 'utf8'
  489. })
  490. }
  491. }
  492. , 'stop' : (label)=>{
  493. const kill = require('tree-kill');
  494. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  495. encoding: 'utf8'
  496. })
  497. fs.unlinkSync('.elixir-server.elixir.server.pid')
  498. console.log(serverPid)
  499. kill(serverPid)
  500. serverPid = fs.readFileSync('.client.server.pid', {
  501. encoding: 'utf8'
  502. })
  503. fs.unlinkSync('.client.server.pid')
  504. console.log(serverPid)
  505. kill(serverPid)
  506. }
  507. , 'use' : ()=>{
  508. // use a certain named instance.
  509. // Eg :
  510. // 1) elxr use elixir
  511. // 2) elxr use cihsr
  512. // If environment is not specified defaults to development.
  513. // 1) NODE=test elxr use elixir
  514. /*// Steps
  515. 1) Delete Config and Data symlinks
  516. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  517. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  518. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  519. 5) Iterates all repos and merge from source configured in mergeSource. 'git', ['merge', mergeSource],
  520. */
  521. var runconfig = { NODE_ENV : process.env.NODE_ENV }
  522. try { runconfig = Object.assign(runconfig, require('../run.js')) } catch(e) { }
  523. if((!processedArgs.runas || processedArgs.runas !== 'self') &&
  524. runconfig.NODE_ENV && runconfig.NODE_ENV === (process.env.NODE_ENV || runconfig.NODE_ENV) &&
  525. processedArgs._[1] && runconfig.use === processedArgs._[1]) {
  526. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  527. if(processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  528. return
  529. }
  530. var tasks = [
  531. ()=>{
  532. if(existsSync('config')) {
  533. var p = nodeShellExec('rmdir', ['config'], {inherit : true, shell: true, env: process.env }
  534. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  535. return p;
  536. }
  537. else return Promise.resolve(true);
  538. },
  539. ()=>{
  540. if(existsSync('data')) {
  541. var p = nodeShellExec('rmdir', ['data'], { inherit : true, shell: true, env: process.env }
  542. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  543. return p;
  544. }
  545. else return Promise.resolve(true);
  546. },
  547. ];
  548. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  549. if(processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  550. if(!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  551. // console.log(process.env.cwd)
  552. fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
  553. var checkoutMap = {
  554. 'development' : 'master',
  555. }
  556. // cant use git checkout -b it fails with branch already exists.
  557. var performCheckout = (repo, branch)=>{
  558. if(!branch) return Promise.resolve({ 'skipped' : true })
  559. if(excludeCheckouts[repo]) return Promise.resolve({ 'skipped' : true })
  560. return nodeShellExec('git', ['checkout', branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  561. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  562. // inherit : true, shell: true,
  563. cwd : repo
  564. // , stdio : ignore // Use when we want to silcence output completely.
  565. , runas : processedArgs.runas
  566. , title : `git checkout ${branch ||checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${repo}`
  567. }).catch((e)=>{ console.error(e); return { error : true, message : repo} })
  568. }
  569. if(runconfig.NODE_ENV === 'development') performCheckout = ()=>{ return Promise.resolve(true) }
  570. var performPullAll = (repo)=>{
  571. if(excludeCheckouts[repo]) return Promise.resolve({ 'skipped' : true })
  572. return nodeShellExec('git', ['pull', '--all'], {
  573. // inherit : true, shell: true,
  574. cwd : repo
  575. , runas : processedArgs.runas
  576. , title : `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${repo}`
  577. }).catch((e)=>{ console.error(e); return { error : true, message : repo} })
  578. }
  579. var mergeSources = {
  580. 'development' : null,
  581. 'test' : 'master',
  582. 'production' : 'master'
  583. }
  584. var exludeMergeRepos = {
  585. 'elixir-config-development' : true, 'elixir-config-test': true, 'elixir-config-production' : true
  586. , 'elixir-data' : true
  587. ,'cihsr-config-development' : true, 'cihsr-config-test': true, 'cihsr-config-production' : true
  588. , 'cihsr-data' : true
  589. }
  590. var excludeCheckouts = Object.assign(exludeMergeRepos)
  591. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  592. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  593. var mergeSource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  594. var performMerge = (repo)=>{
  595. if(exludeMergeRepos[repo]) return Promise.resolve({ 'skipped' : true })
  596. return nodeShellExec('git', ['merge', mergeSource], {
  597. inherit : true, shell: true,
  598. cwd : repo
  599. , runas : processedArgs.runas
  600. }).catch((e)=>{ console.error(e) })
  601. }
  602. if(runconfig.NODE_ENV === 'development') performMerge = ()=>{ return Promise.resolve(true) }
  603. any(tasks).then(()=>{
  604. if(!processedArgs.runas) return op['runas']()
  605. tasks = [
  606. ()=>{
  607. // Use junctions to avoid npm package issues
  608. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV ], {
  609. inherit : true, shell: true
  610. , env: process.env
  611. }).catch((e)=>{ console.error(e) })
  612. return p;
  613. }
  614. ];
  615. if(processedArgs._[1]) {
  616. tasks = tasks.concat(
  617. [
  618. ()=>{
  619. var p = nodeShellExec('mklink', ['/D', 'data', runconfig.use + '-data'], {
  620. inherit : true, shell: true
  621. , env: process.env
  622. }).catch((e)=>{ console.error(e) })
  623. return p;
  624. }
  625. ]
  626. )
  627. }
  628. return any(tasks)
  629. //target is the env is we specify in elxr use command. Default is dev
  630. .then( //Switch to target branch
  631. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))
  632. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))]) )
  633. .then( //PULL from target branch
  634. () => any([ any(gitRepos.map((repo)=>performPullAll(repo))), any(elevatedRunasRepos.map((repo)=>performPullAll(repo)))]) )
  635. .then( //Switch to merge source branch
  636. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'] )))
  637. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'])))]) )
  638. .then( //Pull on merge source branch
  639. () => any([ any(gitRepos.map((repo)=>performPullAll(repo))), any(elevatedRunasRepos.map((repo)=>performPullAll(repo)))]) )
  640. .then( //Switch to target branch
  641. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))
  642. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))]) )
  643. .then( //Merge source branch to target branch
  644. () => any([ any(gitRepos.map((repo)=>performMerge(repo))).catch(err=>{ console.error('error in performMerge ' + err)}) ,
  645. any(elevatedRunasRepos.map((repo)=>performMerge(repo))).catch(err=>{ console.error('error in performMerge ' + err)})]) )
  646. .then( () => {
  647. // Move test config from dev.
  648. if(process.env.NODE_ENV === 'test'){
  649. var devcfgreponame = runconfig.use + '-config' + '-development';
  650. var testcfgreponame = runconfig.use + '-config' + '-test';
  651. var testcfgdir = path.dirname(__dirname) + '/' + testcfgreponame + '/'
  652. var devcfgdir = path.dirname(__dirname) + '/' + devcfgreponame + '/' //eg (elxr/../elixir-config.development)
  653. return any([
  654. ()=>{
  655. return nodeShellExec('git', ['checkout', 'test'], {
  656. inherit : true, shell: true,
  657. cwd : testcfgdir
  658. // , env: process.env
  659. , runas : processedArgs.runas
  660. , title : `git checkout test for ${testcfgreponame}`
  661. }).catch((e)=>{ console.error(e) })
  662. }
  663. , ()=> {
  664. return nodeShellExec('git', ['checkout', 'master'], {
  665. inherit : true, shell: true,
  666. cwd : devcfgdir
  667. // , env: process.env
  668. , runas : processedArgs.runas
  669. , title : `git checkout master for ${devcfgreponame}`
  670. }).catch((e)=>{ console.error(e) })
  671. }
  672. , ()=> {
  673. globSync( '**/*.test.js', {cwd : devcfgdir}).map((filename) => {
  674. console.log('File found : ' + devcfgdir + filename)
  675. fs.copyFileSync(devcfgdir + filename, testcfgdir+ filename);
  676. })
  677. return nodeShellExec('git', ['checkout', 'test'], {
  678. inherit : true, shell: true,
  679. cwd : devcfgdir
  680. // , env: process.env
  681. , runas : processedArgs.runas
  682. , title : `git checkout test for ${devcfgreponame}`
  683. }).catch((e)=>{ console.error(e) })
  684. }
  685. ])
  686. }
  687. else return Promise.resolve(true)
  688. })
  689. .then(()=>{
  690. fs.writeFileSync('run.done', 'success')
  691. }).catch(()=>{
  692. fs.writeFileSync('run.done', 'error')
  693. })
  694. }).catch(()=>{
  695. fs.writeFileSync('run.done', 'error')
  696. })
  697. // Antibiotic stewardship program.
  698. // 1st use is fine.
  699. // Max vials dispense
  700. // 2nd use Pharmacy needs justification Form.
  701. // Approval after a certain period of time.
  702. }
  703. , 'g' : ()=>{
  704. if(processedArgs.h) {
  705. console.log('elxr g [modelname] => generate a model named [modelname]');
  706. console.log('elxr g => regenerate all known models');
  707. return
  708. }
  709. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  710. // console.log('Starting directory: ' + process.cwd());
  711. // try {
  712. // child = child.on('close', () => { process.chdir(label) } );
  713. // console.log('New directory: ' + process.cwd());
  714. // }
  715. // catch (err) {
  716. // console.log('chdir: ' + err);
  717. // }
  718. // child.on('close', function(){
  719. // var options = {
  720. // shell : true
  721. // , inherit : true
  722. // // , cwd : '' + process.cwd
  723. // // , env : process.env
  724. // };
  725. // nodeShellExec('git', ['init'], { inherit : true});
  726. if(0){
  727. // PB : TODO -- Special google chrome profile for tests etc.
  728. nodeShellExec('pwd', { inherit : true});
  729. //$ "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 1" http://localhost:4200/tests/index.html?grep=loopback
  730. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  731. "--profile-directory=Profile 1"
  732. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  733. }
  734. // nodeShellExec('npm', ['init', '-y'], options);
  735. // nodeShellExec('npm', ['init', '-y'], options);
  736. // })
  737. var g = {
  738. 'client' : ()=>{
  739. console.info('Creating new ember client named : ' + processedArgs._[2] ) ;
  740. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  741. stdio: ['pipe', process.stdout, process.stderr],
  742. inherit : true,
  743. shell: true,
  744. cwd : path.dirname(__dirname),
  745. env: env
  746. })
  747. }
  748. }
  749. g[processedArgs._[1]]();
  750. }
  751. }
  752. return op[label] ? op[label]() : null;
  753. }
  754. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  755. // mysql -u root -p db_name < drop_all_tables.sql
  756. var mysql = '../xampp/mysql/bin/mysql'
  757. var mysqldump = '../xampp/mysql/bin/mysqldump'
  758. // --runas
  759. if(processedArgs.runas) {
  760. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  761. __runcmd('runas')
  762. }
  763. else __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  764. function nodeShellExec() {
  765. var args = Array.from(arguments);
  766. var opts = args[2] = args[2] || {}
  767. opts.title ? null : opts.title = `${args[0]} ${args[1] }`
  768. const child = spawn(...arguments);
  769. var p = new Promise(function(resolve, reject){
  770. if(!opts.detached) {
  771. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  772. var success = true;
  773. if(opts.stdio !== 'ignore') {
  774. child.stdout.setEncoding('utf8');
  775. child.stderr.setEncoding('utf8');
  776. child.stdout.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  777. child.on('error', (chunk) => { success = false; messages.push(chunk); /*console.error(chunk)*/ });
  778. child.stderr.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  779. }
  780. child.on('close', (code) => {
  781. if(+code !== 0) success = false;
  782. if(opts.stdio !== 'ignore') {
  783. if(opts.runas){
  784. var logEntry = { result: `${opts.title} exited with code ${code}`, messages : messages }
  785. success ? logEntry.success = true : null;
  786. fs.writeFileSync('run.log', ', ' + JSON.stringify(logEntry), {'flag':'a+'} )
  787. }
  788. else {
  789. success ? console.log(['success : ' + ` ${opts.title} exited with code ${code}`]) : console.error([`error : ${opts.title} exited with code ${code}`])
  790. // console.log( messages.join('') )
  791. process.stdout.write( messages.join('') )
  792. }
  793. }
  794. if(code !== 0) return reject(code)
  795. resolve(true)
  796. });
  797. }
  798. else {
  799. child.unref()
  800. resolve(true);
  801. }
  802. });
  803. p.process = child;
  804. return p;
  805. }