You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 40KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  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. , 'reset' : ()=>{
  164. // Reset NPM packages semver so major versions can be updated.
  165. const fs = require('fs')
  166. const wipeDependencies = (package) => {
  167. const file = fs.readFileSync(package + '/package.json')
  168. const content = JSON.parse(file)
  169. for (var devDep in content.devDependencies) {
  170. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  171. content.devDependencies[devDep] = '*';
  172. }
  173. }
  174. for (var dep in content.dependencies) {
  175. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  176. content.dependencies[dep] = '*';
  177. }
  178. }
  179. fs.writeFileSync(package + '/package.json', JSON.stringify(content))
  180. }
  181. var repos = ['client'];
  182. // repos = gitRepos;
  183. repos.forEach(wipeDependencies)
  184. // if (require.main === module) {
  185. // } else {
  186. // module.exports = wipeDependencies
  187. // }
  188. }
  189. , 'upgrade' : ()=>{
  190. console.log('upgrade.......')
  191. var tasks = [
  192. ()=>{
  193. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  194. inherit : true, shell: true
  195. , env: process.env
  196. }).catch((e)=>{ console.error(e) })
  197. p.position = 1;
  198. console.log('One')
  199. return p;
  200. }
  201. , ()=>{
  202. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  203. inherit : true, shell: true
  204. , env: process.env
  205. }).catch((e)=>{ console.error(e) })
  206. p.position = 2;
  207. console.log('Two')
  208. return p;
  209. }
  210. , ()=>{
  211. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  212. inherit : true, shell: true
  213. , env: process.env
  214. }).catch((e)=>{ console.error(e) })
  215. p.position = 3;
  216. console.log('Three')
  217. return p;
  218. }
  219. , ()=>{
  220. var p = nodeShellExec('n', ['latest'], {
  221. inherit : true, shell: true
  222. , env: process.env
  223. }).catch((e)=>{ console.error(e) })
  224. p.position = 4;
  225. console.log('Four')
  226. return p;
  227. }
  228. ]
  229. any(tasks)
  230. console.log('.......done')
  231. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  232. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  233. console.info('Uninstalling existing ember globally') ;
  234. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  235. stdio: ['pipe', process.stdout, process.stderr],
  236. inherit : true,
  237. shell: true,
  238. cwd : path.dirname(__dirname),
  239. env: env
  240. })
  241. step1.on('close', ()=>{
  242. console.info('Installing ember globally') ;
  243. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  244. stdio: ['pipe', process.stdout, process.stderr],
  245. inherit : true,
  246. shell: true,
  247. cwd : path.dirname(__dirname),
  248. env: env
  249. })
  250. step2.on('close', ()=>{
  251. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  252. stdio: ['pipe', process.stdout, process.stderr],
  253. inherit : true,
  254. shell: true,
  255. cwd : path.dirname(__dirname),
  256. env: env
  257. })
  258. })
  259. })
  260. }
  261. , 'runas' : ()=>{
  262. return isRunningElevated().then(
  263. (isElevated) => {
  264. if(isElevated) {
  265. try {
  266. op[ processedArgs.label || processedArgs._[0] || 'h']()
  267. }
  268. catch(e){
  269. console.error('Error Invalid command : ' + e)
  270. fs.writeFileSync('run.done', 'success')
  271. }
  272. finally {
  273. }
  274. } else throw false;
  275. }
  276. )
  277. .catch(()=>{
  278. console.log('Requesting Elevated Privileges');
  279. // Wait for the runas to complete before we read it.
  280. try {
  281. fs.unlinkSync('run.done')
  282. fs.unlinkSync('run.log')
  283. }
  284. catch(e) { } //Ignore
  285. // PB : TODO -- Convert all the cli args back to string.
  286. var namedArgs = [];
  287. Object.keys(processedArgs).forEach((v)=>{ v!='_' ? namedArgs.push('--'+v+'='+processedArgs[v]) : null; })
  288. //console.log(' namedArgs : ' + namedArgs)
  289. process.env.NODE_ENV = process.env.NODE_ENV || 'development';
  290. var args = [__dirname + '/windowselevate.hta'].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  291. nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  292. , {
  293. inherit : true
  294. , shell: true
  295. , env: process.env
  296. , runas : 'self'
  297. , title : `runas`
  298. }
  299. ).then(()=>{
  300. // runas returned.
  301. try {
  302. var runaslog = JSON.parse('[ { "success" : true, "result" : "runas Log" }' + fs.readFileSync('run.log', { flags : 'a+'}) + ']');
  303. runaslog.forEach((logEntry)=>{
  304. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  305. })
  306. }
  307. catch(e){
  308. // Ignore nonexistent log
  309. console.warn('Run log error probably was not created by runas : ' + e)
  310. }
  311. })
  312. .catch(err => console.error('Elevation failed : ' + err));
  313. })
  314. }
  315. , 'push' : ()=>{
  316. if(!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  317. // init remote bare from local
  318. // pushandinitremotebare
  319. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  320. // connect to repo server -- net use 172.16.0.27
  321. // cd 172.16.0.27/repos/
  322. // mkdir repo.git
  323. // cd repo.git
  324. // git init --bare
  325. // cd localrepo
  326. // git remote rename origin githubclone
  327. // git remote add origin //172.16.0.27/repos/repo.git
  328. // git push origin master
  329. var repo = processedArgs._[1];
  330. var defaultRepoServer = reposervers[0]
  331. var reposervers = [
  332. 'http://git.bbh'
  333. , '//172.16.0.27/repos'
  334. ]
  335. var sequentialTaskShellCommands = [];
  336. if(!existsSync(`Z:/${repo}.git`)){
  337. sequentialTaskShellCommands = [
  338. // ['net', ['use', 'Z:', defaultRepoServer.replace('/','\\')], {
  339. // inherit : true, shell: true
  340. // , env: process.env
  341. // }]
  342. ['pwd', { cwd : 'Z:', inherit : true}]
  343. , ['mkdir', [`${repo}.git`], {
  344. cwd : `Z:`
  345. , inherit : true, shell: true
  346. , env: process.env
  347. }]
  348. , ['pwd', { cwd : `Z:/${repo}.git`, inherit : true}]
  349. , ['git', ['init', '--bare'], { cwd : `Z:/${repo}.git`
  350. , inherit : true, shell: true
  351. , env: process.env
  352. }]
  353. // PB : TODO -- Do this conditionally only...
  354. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd : `${repo}`}, (err)=>{
  355. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  356. } ] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  357. , ['git', ['remote', 'add', 'origin', `${defaultRepoServer}/${repo}.git`], { cwd : `${repo}`}]
  358. // PB : TODO -- If threre is a gitbubclone origin
  359. // Set the master to pull from the local repo.
  360. ]
  361. if(!existsSync(`Z:`)){
  362. sequentialTaskShellCommands.splice(0,0, ['net', ['use', 'Z:', defaultRepoServer.replace(/\//gm,'\\')], {
  363. inherit : true, shell: true
  364. , env: process.env
  365. }])
  366. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  367. // throw 'done'
  368. }
  369. }
  370. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd : `${repo}`}])
  371. // console.dir(sequentialTaskShellCommands);
  372. var tasks = [];
  373. sequentialTaskShellCommands.forEach(shellcmd => {
  374. // console.log(shellcmd)
  375. tasks.push(()=>{
  376. var p = nodeShellExec.apply(null, shellcmd.slice(0,3)).catch((e)=>{ if(shellcmd[3]) { return shellcmd[3]() } else { console.error(e);} })
  377. return p;
  378. })
  379. })
  380. any(tasks);
  381. }
  382. , 'is-git-repo' : (dir)=>{
  383. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio : 'ignore'})
  384. }
  385. , 'add' : (remotename, url) => {
  386. remotename = remotename || processedArgs._[1]
  387. url = url || processedArgs._[2]
  388. var branch = 'master';
  389. var serial_perform_git_add = (repo)=>{
  390. var options = { cwd : repo }
  391. // console.log(repo)
  392. return [
  393. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd : repo }]
  394. , ['git', ['pull', remotename, branch], { cwd : repo }]
  395. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd : repo }]
  396. ]
  397. }
  398. var x = (args)=>{
  399. return ()=>{
  400. // console.log(args)
  401. return nodeShellExec.apply(null, args)
  402. }
  403. // return Promise.resolve(true)
  404. }
  405. var perform_git_add = (dir)=>{
  406. op['is-git-repo'](dir).then((code)=>{
  407. // console.log(code)
  408. if(code) {
  409. nodeShellExec('git',['remote', 'get-url', remotename], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  410. console.log('skipped : ' + dir.name + ', reason : No remote named origin')
  411. })
  412. .catch((e)=>{
  413. any( serial_perform_git_add(dir.name).map(x) )
  414. })
  415. }
  416. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  417. }).catch((e)=>{
  418. // console.log('Failed : ' + dir.name)
  419. })
  420. }
  421. const { readdir } = require("fs").promises
  422. const dirs = async (perform, path) => {
  423. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  424. if (dir.isDirectory()) perform(dir)
  425. }
  426. }
  427. dirs(perform_git_add)
  428. }
  429. , 'remove' : (remotename) => {
  430. remotename = remotename || processedArgs._[1]
  431. var serial_perform_git_remove = (repo)=>{
  432. var options = { cwd : repo }
  433. // console.log(repo)
  434. return [
  435. ['git', ['remote', 'remove', remotename], { cwd : repo }]
  436. ]
  437. }
  438. var x = (args)=>{
  439. return ()=>{
  440. // console.log(args)
  441. return nodeShellExec.apply(null, args)
  442. }
  443. // return Promise.resolve(true)
  444. }
  445. var perform_git_remove = (dir)=>{
  446. op['is-git-repo'](dir).then((code)=>{
  447. // console.log(code)
  448. if(code) {
  449. nodeShellExec('git',['remote', 'get-url', remotename], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  450. any( serial_perform_git_remove(dir.name).map(x) )
  451. })
  452. .catch((e)=>{
  453. console.log('skipped : ' + dir.name + ', reason : No remote named origin')
  454. })
  455. }
  456. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  457. }).catch((e)=>{
  458. // console.log('Failed : ' + dir.name)
  459. })
  460. }
  461. const { readdir } = require("fs").promises
  462. const dirs = async (perform, path) => {
  463. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  464. if (dir.isDirectory()) perform(dir)
  465. }
  466. }
  467. dirs(perform_git_remove)
  468. }
  469. , 'init-gitea' : (user) => {
  470. user = user || processedArgs._[1]
  471. if(!user) throw 'User name required'
  472. var serial_perform_init_gitea = (repo)=>{
  473. var options = { cwd : repo }
  474. // console.log(repo)
  475. return [
  476. ['git', ['remote', 'add', 'chess', 'http://git.bbh/chess/elxr.git'], { cwd : repo }]
  477. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd : repo }]
  478. , ['git', ['remote', 'set-url', 'origin', `http://git.bbh/${user}/${repo}.git`], { cwd : repo }]
  479. ]}
  480. var x = (args)=>{
  481. return ()=>{
  482. // console.log(args)
  483. return nodeShellExec.apply(null, args)
  484. }
  485. // return Promise.resolve(true)
  486. }
  487. var perform_init_gitea = (dir)=>{
  488. op['is-git-repo'](dir).then((code)=>{
  489. // console.log(code)
  490. if(code) {
  491. nodeShellExec('git',['remote', 'get-url', 'chess'], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  492. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  493. })
  494. .catch((e)=>{
  495. any( serial_perform_init_gitea(dir.name).map(x) )
  496. })
  497. }
  498. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  499. }).catch((e)=>{
  500. // console.log('Failed : ' + dir.name)
  501. })
  502. }
  503. const { readdir } = require("fs").promises
  504. const dirs = async (perform, path) => {
  505. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  506. if (dir.isDirectory()) perform(dir)
  507. }
  508. }
  509. dirs(perform_init_gitea)
  510. }
  511. , 'pull' : (label) => {
  512. // Usage :
  513. // elxr pull -- Defaults to run config
  514. var env = Object.assign({}, process.env); // Shallow clone it.
  515. // console.dir(env)
  516. console.log('Running exlr pull : ' + path.dirname(__dirname))
  517. // nodeShellExec('cmd', ['/c', 'setup\\utility\\chess.bat', 'pull'], {
  518. // // nodeShellExec('cmd', ['/c', '..\\setup\\utility\\chess.bat', 'pull'], {
  519. // stdio: ['pipe', process.stdout, process.stderr],
  520. // inherit : true,
  521. // shell: true,
  522. // cwd : path.dirname(__dirname),
  523. // env: env
  524. // })
  525. var useGitPull = processedArgs.useGitPull || false;
  526. var getPullCmd = (repo)=>{
  527. var pullCmd = ["C:\\Program Files\\Git\\bin\\sh.exe", ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;'], { cwd : repo }]
  528. // var pullCmd = ['pullall', [], { cwd : repo }]
  529. if(useGitPull) pullCmd = ['git', ['pull'], {
  530. inherit : true, shell: true,
  531. cwd : repo
  532. // , env: process.env
  533. , runas : processedArgs.runas
  534. , title : `git pull ${repo}`
  535. }]
  536. return pullCmd
  537. }
  538. var performPull = (repo) => {
  539. if(existsSync(repo)) {
  540. console.log('pulling ' + repo)
  541. return nodeShellExec.apply(null, getPullCmd(repo)).catch((e)=>{ console.error(e) })
  542. }
  543. else {
  544. console.log('cloning ' + repo)
  545. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', defaultRepoServer + '/' + repo + '.git'],
  546. {
  547. inherit : true, shell: true,
  548. env: process.env
  549. , runas : processedArgs.runas
  550. }).catch((e)=>{ console.error(e) }).then(()=>{
  551. return nodeShellExec('git', ['config', '--replace-all' , 'core.symlinks', true],
  552. {
  553. inherit : true, shell: true,
  554. env: process.env
  555. , cwd : repo
  556. , runas : processedArgs.runas
  557. , title : `git core.symlinks --replace-all true for ${defaultRepoServer + '/' + repo + '.git'}`
  558. })
  559. })
  560. }
  561. }
  562. if(!processedArgs.runas) gitRepos.forEach(performPull)
  563. return isRunningElevated().then(
  564. (isElevated) => {
  565. if(isElevated) {
  566. any(elevatedRunasRepos.map((repo)=>performPull(repo))).then(()=>{
  567. fs.writeFileSync('run.done', 'success')
  568. }).catch(()=>{
  569. fs.writeFileSync('run.done', 'error')
  570. })
  571. }
  572. else throw false;
  573. }
  574. ).catch(
  575. () => {
  576. op['runas']()
  577. }
  578. )
  579. }
  580. , 'isInstalled' : ()=>{
  581. return nodeShellExec('where', [processedArgs._[1]], { inherit : true} ).then(()=>{
  582. console.log(processedArgs._[1] + ' exists.')
  583. return true;
  584. });
  585. }
  586. , 'npmi' : ()=>{
  587. var tasks = [];
  588. gitRepos.forEach(repo => {
  589. console.log('npm i for ' + repo)
  590. // nodeShellExec('pwd', [], {
  591. // // inherit : true, shell: true
  592. // cwd : repo
  593. // // , env: process.env
  594. // , title : `pwd for ${repo}`
  595. // }).catch((e)=>{ console.error(e) })
  596. nodeShellExec('rm', ['package-lock.json'], {
  597. inherit : true, shell: true
  598. , cwd : repo
  599. , env: process.env
  600. , title : `rm 'package-lock.json' for ${repo}`
  601. }).catch((e)=>{ console.error(e) })
  602. tasks.push(()=>{
  603. var p = nodeShellExec('npm', ['i'], {
  604. inherit : true, shell: true
  605. , cwd : repo
  606. , env: process.env
  607. , title : `npm i for ${repo}`
  608. }).catch((e)=>{ console.error(e) })
  609. return p;
  610. })
  611. })
  612. any(tasks);
  613. }
  614. , 'start' : (label)=>{
  615. console.log('Starting Elixir Server.');
  616. var env = Object.assign({}, process.env); // Shallow clone it.
  617. // console.dir(env)
  618. env.NODE_ENV = process.env.NODE_ENV || 'development';
  619. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  620. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  621. // cmd = 'node'
  622. var childPromise = nodeShellExec(cmd, ['--inspect=9228', 'elixir/server.js'], {
  623. // inherit : true,
  624. shell: true,
  625. detached: true,
  626. stdio: 'ignore',
  627. cwd : 'elixir-server'
  628. , env: env
  629. })
  630. var child = childPromise.process;
  631. if (typeof child.pid !== 'undefined') {
  632. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  633. encoding: 'utf8'
  634. })
  635. }
  636. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  637. // inherit : true,
  638. // shell: true, detached: true,
  639. // cwd : 'qms/server',
  640. // env: env,
  641. // shell : true
  642. // })
  643. // nodeShellExec('ember', ['s'], {
  644. // // inherit : true,
  645. // shell: true, detached: true,
  646. // cwd : 'client/',
  647. // env: env
  648. // })
  649. var childPromise = nodeShellExec('ember', ['s'], {
  650. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  651. // PB : TODO -- ember debugging.
  652. // inherit : true,
  653. shell: true,
  654. detached: true,
  655. stdio: 'ignore',
  656. cwd : 'client'
  657. , env: env
  658. })
  659. // .catch(e=>console.error(e))
  660. child = childPromise.process;
  661. if (typeof child.pid !== 'undefined') {
  662. fs.writeFileSync('.client.server.pid', child.pid, {
  663. encoding: 'utf8'
  664. })
  665. }
  666. }
  667. , 'stop' : (label)=>{
  668. const kill = require('tree-kill');
  669. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  670. encoding: 'utf8'
  671. })
  672. fs.unlinkSync('.elixir-server.elixir.server.pid')
  673. console.log(serverPid)
  674. kill(serverPid)
  675. serverPid = fs.readFileSync('.client.server.pid', {
  676. encoding: 'utf8'
  677. })
  678. fs.unlinkSync('.client.server.pid')
  679. console.log(serverPid)
  680. kill(serverPid)
  681. }
  682. , 'use' : ()=>{
  683. // use a certain named instance.
  684. // Eg :
  685. // 1) elxr use elixir
  686. // 2) elxr use cihsr
  687. // If environment is not specified defaults to development.
  688. // 1) NODE=test elxr use elixir
  689. /*// Steps
  690. 1) Delete Config and Data symlinks
  691. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  692. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  693. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  694. 5) Iterates all repos and merge from source configured in mergeSource. 'git', ['merge', mergeSource],
  695. */
  696. var runconfig = { NODE_ENV : process.env.NODE_ENV }
  697. try { runconfig = Object.assign(runconfig, require('../run.js')) } catch(e) { }
  698. if((!processedArgs.runas || processedArgs.runas !== 'self') &&
  699. runconfig.NODE_ENV && runconfig.NODE_ENV === (process.env.NODE_ENV || runconfig.NODE_ENV) &&
  700. processedArgs._[1] && runconfig.use === processedArgs._[1]) {
  701. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  702. if(processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  703. return
  704. }
  705. var tasks = [
  706. ()=>{
  707. if(existsSync('config')) {
  708. var p = nodeShellExec('rmdir', ['config'], {inherit : true, shell: true, env: process.env }
  709. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  710. return p;
  711. }
  712. else return Promise.resolve(true);
  713. },
  714. ()=>{
  715. if(existsSync('data')) {
  716. var p = nodeShellExec('rmdir', ['data'], { inherit : true, shell: true, env: process.env }
  717. ).catch((err)=>{ console.log('Ignoring benign error : ' + err); return true; })
  718. return p;
  719. }
  720. else return Promise.resolve(true);
  721. },
  722. ];
  723. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  724. if(processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  725. if(!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  726. // console.log(process.env.cwd)
  727. fs.writeFileSync('./run.js', 'module.exports = ' + JSON.stringify(runconfig))
  728. var checkoutMap = {
  729. 'development' : 'master',
  730. }
  731. // cant use git checkout -b it fails with branch already exists.
  732. var performCheckout = (repo, branch)=>{
  733. if(!branch) return Promise.resolve({ 'skipped' : true })
  734. if(excludeCheckouts[repo]) return Promise.resolve({ 'skipped' : true })
  735. return nodeShellExec('git', ['checkout', branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  736. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  737. // inherit : true, shell: true,
  738. cwd : repo
  739. // , stdio : ignore // Use when we want to silcence output completely.
  740. , runas : processedArgs.runas
  741. , title : `git checkout ${branch ||checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${repo}`
  742. }).catch((e)=>{ console.error(e); return { error : true, message : repo} })
  743. }
  744. if(runconfig.NODE_ENV === 'development') performCheckout = ()=>{ return Promise.resolve(true) }
  745. var performPullAll = (repo)=>{
  746. if(excludeCheckouts[repo]) return Promise.resolve({ 'skipped' : true })
  747. return nodeShellExec('git', ['pull', '--all'], {
  748. // inherit : true, shell: true,
  749. cwd : repo
  750. , runas : processedArgs.runas
  751. , title : `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${repo}`
  752. }).catch((e)=>{ console.error(e); return { error : true, message : repo} })
  753. }
  754. var mergeSources = {
  755. 'development' : null,
  756. 'test' : 'master',
  757. 'production' : 'master'
  758. }
  759. var exludeMergeRepos = {
  760. 'elixir-config-development' : true, 'elixir-config-test': true, 'elixir-config-production' : true
  761. , 'elixir-data' : true
  762. ,'cihsr-config-development' : true, 'cihsr-config-test': true, 'cihsr-config-production' : true
  763. , 'cihsr-data' : true
  764. }
  765. var excludeCheckouts = Object.assign(exludeMergeRepos)
  766. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  767. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  768. var mergeSource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  769. var performMerge = (repo)=>{
  770. if(exludeMergeRepos[repo]) return Promise.resolve({ 'skipped' : true })
  771. return nodeShellExec('git', ['merge', mergeSource], {
  772. inherit : true, shell: true,
  773. cwd : repo
  774. , runas : processedArgs.runas
  775. }).catch((e)=>{ console.error(e) })
  776. }
  777. if(runconfig.NODE_ENV === 'development') performMerge = ()=>{ return Promise.resolve(true) }
  778. any(tasks).then(()=>{
  779. if(!processedArgs.runas) return op['runas']()
  780. tasks = [
  781. ()=>{
  782. // Use junctions to avoid npm package issues
  783. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV ], {
  784. inherit : true, shell: true
  785. , env: process.env
  786. }).catch((e)=>{ console.error(e) })
  787. return p;
  788. }
  789. ];
  790. if(processedArgs._[1]) {
  791. tasks = tasks.concat(
  792. [
  793. ()=>{
  794. var p = nodeShellExec('mklink', ['/D', 'data', runconfig.use + '-data'], {
  795. inherit : true, shell: true
  796. , env: process.env
  797. }).catch((e)=>{ console.error(e) })
  798. return p;
  799. }
  800. ]
  801. )
  802. }
  803. return any(tasks)
  804. //target is the env is we specify in elxr use command. Default is dev
  805. .then( //Switch to target branch
  806. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))
  807. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))]) )
  808. .then( //PULL from target branch
  809. () => any([ any(gitRepos.map((repo)=>performPullAll(repo))), any(elevatedRunasRepos.map((repo)=>performPullAll(repo)))]) )
  810. .then( //Switch to merge source branch
  811. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'] )))
  812. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'])))]) )
  813. .then( //Pull on merge source branch
  814. () => any([ any(gitRepos.map((repo)=>performPullAll(repo))), any(elevatedRunasRepos.map((repo)=>performPullAll(repo)))]) )
  815. .then( //Switch to target branch
  816. () => any([ any(gitRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))
  817. , any(elevatedRunasRepos.map((repo)=>performCheckout(repo, process.env.NODE_ENV || 'development')))]) )
  818. .then( //Merge source branch to target branch
  819. () => any([ any(gitRepos.map((repo)=>performMerge(repo))).catch(err=>{ console.error('error in performMerge ' + err)}) ,
  820. any(elevatedRunasRepos.map((repo)=>performMerge(repo))).catch(err=>{ console.error('error in performMerge ' + err)})]) )
  821. .then( () => {
  822. // Move test config from dev.
  823. // if(process.env.NODE_ENV === 'test'){
  824. // var devcfgreponame = runconfig.use + '-config' + '-development';
  825. // var testcfgreponame = runconfig.use + '-config' + '-test';
  826. // var testcfgdir = path.dirname(__dirname) + '/' + testcfgreponame + '/'
  827. // var devcfgdir = path.dirname(__dirname) + '/' + devcfgreponame + '/' //eg (elxr/../elixir-config.development)
  828. // return any([
  829. // ()=>{
  830. // return nodeShellExec('git', ['checkout', 'test'], {
  831. // inherit : true, shell: true,
  832. // cwd : testcfgdir
  833. // // , env: process.env
  834. // , runas : processedArgs.runas
  835. // , title : `git checkout test for ${testcfgreponame}`
  836. // }).catch((e)=>{ console.error(e) })
  837. // }
  838. // , ()=> {
  839. // return nodeShellExec('git', ['checkout', 'master'], {
  840. // inherit : true, shell: true,
  841. // cwd : devcfgdir
  842. // // , env: process.env
  843. // , runas : processedArgs.runas
  844. // , title : `git checkout master for ${devcfgreponame}`
  845. // }).catch((e)=>{ console.error(e) })
  846. // }
  847. // , ()=> {
  848. // globSync( '**/*.test.js', {cwd : devcfgdir}).map((filename) => {
  849. // console.log('File found : ' + devcfgdir + filename)
  850. // fs.copyFileSync(devcfgdir + filename, testcfgdir+ filename);
  851. // })
  852. // return nodeShellExec('git', ['checkout', 'test'], {
  853. // inherit : true, shell: true,
  854. // cwd : devcfgdir
  855. // // , env: process.env
  856. // , runas : processedArgs.runas
  857. // , title : `git checkout test for ${devcfgreponame}`
  858. // }).catch((e)=>{ console.error(e) })
  859. // }
  860. // ])
  861. // }
  862. // else {
  863. return Promise.resolve(true)
  864. // }
  865. })
  866. .then(()=>{
  867. fs.writeFileSync('run.done', 'success')
  868. }).catch(()=>{
  869. fs.writeFileSync('run.done', 'error')
  870. })
  871. }).catch(()=>{
  872. fs.writeFileSync('run.done', 'error')
  873. })
  874. // Antibiotic stewardship program.
  875. // 1st use is fine.
  876. // Max vials dispense
  877. // 2nd use Pharmacy needs justification Form.
  878. // Approval after a certain period of time.
  879. }
  880. , 'g' : ()=>{
  881. if(processedArgs.h) {
  882. console.log('elxr g [modelname] => generate a model named [modelname]');
  883. console.log('elxr g => regenerate all known models');
  884. return
  885. }
  886. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  887. // console.log('Starting directory: ' + process.cwd());
  888. // try {
  889. // child = child.on('close', () => { process.chdir(label) } );
  890. // console.log('New directory: ' + process.cwd());
  891. // }
  892. // catch (err) {
  893. // console.log('chdir: ' + err);
  894. // }
  895. // child.on('close', function(){
  896. // var options = {
  897. // shell : true
  898. // , inherit : true
  899. // // , cwd : '' + process.cwd
  900. // // , env : process.env
  901. // };
  902. // nodeShellExec('git', ['init'], { inherit : true});
  903. if(0){
  904. // PB : TODO -- Special google chrome profile for tests etc.
  905. nodeShellExec('pwd', { inherit : true});
  906. //$ "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --profile-directory="Profile 1" http://localhost:4200/tests/index.html?grep=loopback
  907. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  908. "--profile-directory=Profile 1"
  909. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  910. }
  911. // nodeShellExec('npm', ['init', '-y'], options);
  912. // nodeShellExec('npm', ['init', '-y'], options);
  913. // })
  914. var g = {
  915. 'client' : ()=>{
  916. console.info('Creating new ember client named : ' + processedArgs._[2] ) ;
  917. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  918. stdio: ['pipe', process.stdout, process.stderr],
  919. inherit : true,
  920. shell: true,
  921. cwd : path.dirname(__dirname),
  922. env: env
  923. })
  924. }
  925. }
  926. g[processedArgs._[1]]();
  927. }
  928. }
  929. return op[label] ? op[label]() : null;
  930. }
  931. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  932. // mysql -u root -p db_name < drop_all_tables.sql
  933. var mysql = '../xampp/mysql/bin/mysql'
  934. var mysqldump = '../xampp/mysql/bin/mysqldump'
  935. // --runas
  936. if(processedArgs.runas) {
  937. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  938. __runcmd('runas')
  939. }
  940. else __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  941. function nodeShellExec() {
  942. var args = Array.from(arguments);
  943. var opts = args[2] = args[2] || {}
  944. opts.title ? null : opts.title = `${args[0]} ${args[1] }`
  945. const child = spawn(...arguments);
  946. var p = new Promise(function(resolve, reject){
  947. if(!opts.detached) {
  948. var messages = []; // PB : TODO -- Explore stream for Task level aggregation to prevent interleaved messages from multiple tasks...
  949. var success = true;
  950. if(opts.stdio !== 'ignore') {
  951. child.stdout.setEncoding('utf8');
  952. child.stderr.setEncoding('utf8');
  953. child.stdout.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  954. child.on('error', (chunk) => { success = false; messages.push(chunk); /*console.error(chunk)*/ });
  955. child.stderr.on('data', (chunk) => { messages.push(chunk); /*console.log(chunk)*/});
  956. }
  957. child.on('close', (code) => {
  958. if(+code !== 0) success = false;
  959. if(opts.stdio !== 'ignore') {
  960. if(opts.runas){
  961. var logEntry = { result: `${opts.title} exited with code ${code}`, messages : messages }
  962. success ? logEntry.success = true : null;
  963. fs.writeFileSync('run.log', ', ' + JSON.stringify(logEntry), {'flag':'a+'} )
  964. }
  965. else {
  966. success ? console.log(['success : ' + ` ${opts.title} exited with code ${code}`]) : console.error([`error : ${opts.title} exited with code ${code}`])
  967. // console.log( messages.join('') )
  968. process.stdout.write( messages.join('') )
  969. }
  970. }
  971. if(code !== 0) return reject(code)
  972. resolve(true)
  973. });
  974. }
  975. else {
  976. child.unref()
  977. resolve(true);
  978. }
  979. });
  980. p.process = child;
  981. return p;
  982. }