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

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