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

index.js 33KB

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