555
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.

5 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
5 anni fa
5 anni fa
4 anni fa
4 anni fa
5 anni fa
5 anni fa
5 anni fa
5 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
4 anni fa
5 anni fa
5 anni fa
5 anni fa
5 anni fa
5 anni fa
5 anni fa
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  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. // Serialize a set of functions that will execute to return a promises one after the other.
  23. // Will stop when any one fails unless continueOnFailure is true.
  24. // All tasks in iterables can be functions or promises.
  25. // promises as usual can return other promises or resolve to either truthy or falsy values.
  26. // functions must return a promise
  27. function any(iterable, continueOnFailure) {
  28. return iterable.reduce(
  29. (p, fn, i ,a) => {
  30. // console.log('accumulator :');
  31. // console.log(p);
  32. if(Promise.resolve(p) === p ) {
  33. return p.then((pVal) => {
  34. // Falsy values are task failure.
  35. if(!pVal) {
  36. console.warn('Possible failure for result : ' + pVal)
  37. console.warn(a[i-1])
  38. fn ? console.error("Fn : " + fn.toString()) : null;
  39. }
  40. // Truthy values are failures if obj has error=true.
  41. if(pVal && pVal.error) { console.error('Failed : ' + pVal.message + ' ' + pVal) }
  42. if(Promise.resolve(pVal) === pVal) {
  43. // Passed in function retured a promise. We still need to wait for it.
  44. pVal.then((pVal)=>{
  45. // console.log('Then --pVal = ' + pVal + ' bContinue = ' + continueOnFailure ); console.log(p);
  46. if(!pVal && !continueOnFailure) {
  47. console.error(`E1 : i = ${i} : pVal :` + pVal);
  48. console.error('debugData 2 -------------------');
  49. console.log("Cancelling remaining...");
  50. throw 'Failed in reduce 1 '
  51. }
  52. if(!fn && !continueOnFailure) { console.error('Error : No task specified.'); throw false;}
  53. else if(!fn) return false;
  54. return (Promise.resolve(fn) === fn ) ? fn : fn() ;
  55. })
  56. }
  57. else {
  58. // We will stop on null resolved values on any one task unless continueOnFailure is true.
  59. // console.log('Then --pVal = ' + pVal + ' bContinue = ' + continueOnFailure ); console.log(p);
  60. if(!pVal && !continueOnFailure) {
  61. console.error(`E2 : i = ${i} : pVal :` + pVal);
  62. console.error('debugData 2 -------------------');
  63. console.log("Cancelling remaining...");
  64. throw 'Failed in reduce 2 '
  65. }
  66. if(!fn && !continueOnFailure) { console.error('Error : No task specified.'); throw false;}
  67. else if(!fn) return false;
  68. return (Promise.resolve(fn) === fn ) ? fn : fn() ;
  69. }
  70. }).catch((error) => {
  71. console.error(`E3 : i = ${i} `);
  72. fn ? console.error("Fn : " + fn.toString()) : null;
  73. console.error('debugData 3-------------------------');
  74. throw 'Failed in reduce 3 '
  75. })
  76. }
  77. else if(!p) {
  78. console.log("Bypass on failure");
  79. return false;
  80. }
  81. }
  82. , Promise.resolve(true)
  83. );
  84. }
  85. var __isElevated = null;
  86. var isRunningElevated = ()=>{
  87. if(__isElevated === null) {
  88. return nodeShellExec( "fsutil", ["dirty", "query", "C:"], {
  89. inherit : true
  90. // , shell: true
  91. , stdio: 'ignore'
  92. , env: process.env
  93. , title : `check privileged execution mode using "fsutil dirty query C:"`
  94. }).then((exitcode)=>{
  95. console.log('Elevated')
  96. __isElevated = true;
  97. return true;
  98. }).catch(()=>{
  99. __isElevated = false;
  100. console.log('Not Elevated');
  101. throw false;
  102. });
  103. }
  104. else return Promise.resolve(__isElevated);
  105. }
  106. var cli = 'elxr';
  107. var ver = '#unversioned';
  108. var help = '#unkown list of commands... please refer dveloper documentation for ' + cli;
  109. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  110. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  111. var dbForLabel = function(label){
  112. var dbsForLabel = {
  113. devmysql : 'mysql'
  114. , development : 'mssql'
  115. , production : 'mssql'
  116. }
  117. return dbsForLabel[label] || 'mysql'
  118. }
  119. // Relevant git repos
  120. var gitRepos = [
  121. 'ember-masonry-grid'
  122. , 'bbhverse'
  123. , 'clientverse'
  124. , 'serververse'
  125. , 'client'
  126. // , 'client/server'
  127. , 'elxr'
  128. , 'ember-searchable-select'
  129. , 'loopback-component-jsonapi'
  130. , 'elixir-config-development'
  131. , 'elixir-config-test'
  132. , 'cihsr-config'
  133. , 'cihsr-data'
  134. , 'elixir-data'
  135. , 'loopback-connector-ds'
  136. , 'chess-server-lib'
  137. , 'setup'
  138. , 'elixir-client-todos'
  139. , 'elixir-client-unlinked'
  140. , 'elixir-client'
  141. , 'ember-service-worker'
  142. , 'ember-service-worker-asset-cache'
  143. , 'ember-service-worker-cache-fallback'
  144. , 'ember-service-worker-index'
  145. , 'ember-sw-client-route'
  146. , 'global-this'
  147. ]
  148. // Repositiories that have symlinks that required elevated priviletes in windows to create symlinks
  149. //
  150. var elevatedRunasRepos = [
  151. 'elixir-server'
  152. , 'cihsr-server'
  153. , 'chess-server'
  154. ]
  155. var productionRepos = [
  156. 'elixir-config-production'
  157. ]
  158. var productionIsAllowed = true;
  159. if(productionIsAllowed) gitRepos = gitRepos.concat(productionRepos)
  160. var env = Object.assign({}, process.env); // Shallow clone it.
  161. var __runcmd = function(label){
  162. var op = {
  163. 'h' : ()=>{ console.log(cli + ' ' + ver + ' ' + help); return '-h' }
  164. , 'undefined' : ()=>{ return op.h(); }
  165. , 'reset' : ()=>{
  166. // Reset NPM packages semver so major versions can be updated.
  167. const fs = require('fs')
  168. const wipeDependencies = (package) => {
  169. const file = fs.readFileSync(package + '/package.json')
  170. const content = JSON.parse(file)
  171. for (var devDep in content.devDependencies) {
  172. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  173. content.devDependencies[devDep] = '*';
  174. }
  175. }
  176. for (var dep in content.dependencies) {
  177. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  178. content.dependencies[dep] = '*';
  179. }
  180. }
  181. fs.writeFileSync(package + '/package.json', JSON.stringify(content))
  182. }
  183. var repos = ['client'];
  184. // repos = gitRepos;
  185. repos.forEach(wipeDependencies)
  186. // if (require.main === module) {
  187. // } else {
  188. // module.exports = wipeDependencies
  189. // }
  190. }
  191. , 'upgrade' : ()=>{
  192. console.log('upgrade.......')
  193. var tasks = [
  194. ()=>{
  195. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  196. inherit : true, shell: true
  197. , env: process.env
  198. }).catch((e)=>{ console.error(e) })
  199. p.position = 1;
  200. console.log('One')
  201. return p;
  202. }
  203. , ()=>{
  204. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  205. inherit : true, shell: true
  206. , env: process.env
  207. }).catch((e)=>{ console.error(e) })
  208. p.position = 2;
  209. console.log('Two')
  210. return p;
  211. }
  212. , ()=>{
  213. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  214. inherit : true, shell: true
  215. , env: process.env
  216. }).catch((e)=>{ console.error(e) })
  217. p.position = 3;
  218. console.log('Three')
  219. return p;
  220. }
  221. , ()=>{
  222. var p = nodeShellExec('n', ['latest'], {
  223. inherit : true, shell: true
  224. , env: process.env
  225. }).catch((e)=>{ console.error(e) })
  226. p.position = 4;
  227. console.log('Four')
  228. return p;
  229. }
  230. ]
  231. any(tasks)
  232. console.log('.......done')
  233. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  234. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  235. console.info('Uninstalling existing ember globally') ;
  236. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  237. stdio: ['pipe', process.stdout, process.stderr],
  238. inherit : true,
  239. shell: true,
  240. cwd : path.dirname(__dirname),
  241. env: env
  242. })
  243. step1.on('close', ()=>{
  244. console.info('Installing ember globally') ;
  245. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-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. step2.on('close', ()=>{
  253. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  254. stdio: ['pipe', process.stdout, process.stderr],
  255. inherit : true,
  256. shell: true,
  257. cwd : path.dirname(__dirname),
  258. env: env
  259. })
  260. })
  261. })
  262. }
  263. , 'runas' : ()=>{
  264. return isRunningElevated().then(
  265. (isElevated) => {
  266. if(isElevated) {
  267. try {
  268. op[ processedArgs.label || processedArgs._[0] || 'h']()
  269. }
  270. catch(e){
  271. console.error('Error Invalid command : ' + e)
  272. fs.writeFileSync('run.done', 'success')
  273. }
  274. finally {
  275. }
  276. } else throw false;
  277. }
  278. )
  279. .catch(()=>{
  280. console.log('Requesting Elevated Privileges');
  281. // Wait for the runas to complete before we read it.
  282. try {
  283. fs.unlinkSync('run.done')
  284. fs.unlinkSync('run.log')
  285. }
  286. catch(e) { } //Ignore
  287. // PB : TODO -- Convert all the cli args back to string.
  288. var namedArgs = [];
  289. Object.keys(processedArgs).forEach((v)=>{ v!='_' ? namedArgs.push('--'+v+'='+processedArgs[v]) : null; })
  290. //console.log(' namedArgs : ' + namedArgs)
  291. process.env.NODE_ENV = process.env.NODE_ENV || 'development';
  292. var args = [__dirname + '/windowselevate.hta'].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  293. nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  294. , {
  295. inherit : true
  296. , shell: true
  297. , env: process.env
  298. , runas : 'self'
  299. , title : `runas`
  300. }
  301. ).then(()=>{
  302. // runas returned.
  303. try {
  304. var runaslog = JSON.parse('[ { "success" : true, "result" : "runas Log" }' + fs.readFileSync('run.log', { flags : 'a+'}) + ']');
  305. runaslog.forEach((logEntry)=>{
  306. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  307. })
  308. }
  309. catch(e){
  310. // Ignore nonexistent log
  311. console.warn('Run log error probably was not created by runas : ' + e)
  312. }
  313. })
  314. .catch(err => console.error('Elevation failed : ' + err));
  315. })
  316. }
  317. , 'push' : ()=>{
  318. if(!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  319. // init remote bare from local
  320. // pushandinitremotebare
  321. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  322. // connect to repo server -- net use 172.16.0.27
  323. // cd 172.16.0.27/repos/
  324. // mkdir repo.git
  325. // cd repo.git
  326. // git init --bare
  327. // cd localrepo
  328. // git remote rename origin githubclone
  329. // git remote add origin //172.16.0.27/repos/repo.git
  330. // git push origin master
  331. var repo = processedArgs._[1];
  332. var reposervers = [
  333. 'http://git.bbh'
  334. , '//172.16.0.27/repos'
  335. ]
  336. var defaultRepoServer = reposervers[0]
  337. var sequentialTaskShellCommands = [];
  338. if(!existsSync(`Z:/${repo}.git`)){
  339. sequentialTaskShellCommands = [
  340. // ['net', ['use', 'Z:', defaultRepoServer.replace('/','\\')], {
  341. // inherit : true, shell: true
  342. // , env: process.env
  343. // }]
  344. ['pwd', { cwd : 'Z:', inherit : true}]
  345. , ['mkdir', [`${repo}.git`], {
  346. cwd : `Z:`
  347. , inherit : true, shell: true
  348. , env: process.env
  349. }]
  350. , ['pwd', { cwd : `Z:/${repo}.git`, inherit : true}]
  351. , ['git', ['init', '--bare'], { cwd : `Z:/${repo}.git`
  352. , inherit : true, shell: true
  353. , env: process.env
  354. }]
  355. // PB : TODO -- Do this conditionally only...
  356. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd : `${repo}`}, (err)=>{
  357. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  358. } ] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  359. , ['git', ['remote', 'add', 'origin', `${defaultRepoServer}/${repo}.git`], { cwd : `${repo}`}]
  360. // PB : TODO -- If threre is a gitbubclone origin
  361. // Set the master to pull from the local repo.
  362. ]
  363. if(!existsSync(`Z:`)){
  364. sequentialTaskShellCommands.splice(0,0, ['net', ['use', 'Z:', defaultRepoServer.replace(/\//gm,'\\')], {
  365. inherit : true, shell: true
  366. , env: process.env
  367. }])
  368. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  369. // throw 'done'
  370. }
  371. }
  372. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd : `${repo}`}])
  373. // console.dir(sequentialTaskShellCommands);
  374. var tasks = [];
  375. sequentialTaskShellCommands.forEach(shellcmd => {
  376. // console.log(shellcmd)
  377. tasks.push(()=>{
  378. var p = nodeShellExec.apply(null, shellcmd.slice(0,3)).catch((e)=>{ if(shellcmd[3]) { return shellcmd[3]() } else { console.error(e);} })
  379. return p;
  380. })
  381. })
  382. any(tasks);
  383. }
  384. , 'is-git-repo' : (dir)=>{
  385. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio : 'ignore'})
  386. }
  387. , 'add' : (remotename, url, branch) => {
  388. var pushable = processedArgs.pushable || false;
  389. remotename = remotename || processedArgs._[1]
  390. url = url || processedArgs._[2]
  391. branch = branch || processedArgs._[3]
  392. var serial_perform_git_add = (repo)=>{
  393. var options = { cwd : repo }
  394. // console.log(repo)
  395. if(pushable) {
  396. return [
  397. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd : repo }]
  398. , ['git', ['pull', remotename, branch], { cwd : repo }]
  399. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd : repo }]
  400. ]
  401. }
  402. else {
  403. return [
  404. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd : repo }]
  405. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd : repo }]
  406. , ['git', ['pull', remotename, branch], { cwd : repo }]
  407. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd : repo }]
  408. ]
  409. }
  410. }
  411. var x = (args)=>{
  412. return ()=>{
  413. // console.log(args)
  414. return nodeShellExec.apply(null, args)
  415. }
  416. // return Promise.resolve(true)
  417. }
  418. var perform_git_add = (dir)=>{
  419. op['is-git-repo'](dir).then((code)=>{
  420. // console.log(code)
  421. if(code) {
  422. nodeShellExec('git',['remote', 'get-url', remotename], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  423. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  424. })
  425. .catch((e)=>{
  426. any( serial_perform_git_add(dir.name).map(x) )
  427. })
  428. }
  429. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  430. }).catch((e)=>{
  431. // console.log('Failed : ' + dir.name)
  432. })
  433. }
  434. const { readdir } = require("fs").promises
  435. const dirs = async (perform, path) => {
  436. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  437. if (dir.isDirectory()) perform(dir)
  438. }
  439. }
  440. dirs(perform_git_add)
  441. }
  442. , 'remove' : (remotename) => {
  443. remotename = remotename || processedArgs._[1]
  444. var serial_perform_git_remove = (repo)=>{
  445. var options = { cwd : repo }
  446. // console.log(repo)
  447. return [
  448. ['git', ['remote', 'remove', remotename], { cwd : repo }]
  449. ]
  450. }
  451. var x = (args)=>{
  452. return ()=>{
  453. // console.log(args)
  454. return nodeShellExec.apply(null, args)
  455. }
  456. // return Promise.resolve(true)
  457. }
  458. var perform_git_remove = (dir)=>{
  459. op['is-git-repo'](dir).then((code)=>{
  460. // console.log(code)
  461. if(code) {
  462. nodeShellExec('git',['remote', 'get-url', remotename], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  463. any( serial_perform_git_remove(dir.name).map(x) )
  464. })
  465. .catch((e)=>{
  466. console.log('skipped : ' + dir.name + ', reason : No remote named origin')
  467. })
  468. }
  469. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  470. }).catch((e)=>{
  471. // console.log('Failed : ' + dir.name)
  472. })
  473. }
  474. const { readdir } = require("fs").promises
  475. const dirs = async (perform, path) => {
  476. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  477. if (dir.isDirectory()) perform(dir)
  478. }
  479. }
  480. dirs(perform_git_remove)
  481. }
  482. , 'init-gitea' : (user) => {
  483. user = user || processedArgs._[1]
  484. if(!user) throw 'User name required'
  485. var serial_perform_init_gitea = (repo)=>{
  486. var options = { cwd : repo }
  487. // console.log(repo)
  488. return [
  489. ['git', ['remote', 'add', 'chess', 'http://git.bbh/chess/elxr.git'], { cwd : repo }]
  490. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd : repo }]
  491. , ['git', ['remote', 'set-url', 'origin', `http://git.bbh/${user}/${repo}.git`], { cwd : repo }]
  492. ]}
  493. var x = (args)=>{
  494. return ()=>{
  495. // console.log(args)
  496. return nodeShellExec.apply(null, args)
  497. }
  498. // return Promise.resolve(true)
  499. }
  500. var perform_init_gitea = (dir)=>{
  501. op['is-git-repo'](dir).then((code)=>{
  502. // console.log(code)
  503. if(code) {
  504. nodeShellExec('git',['remote', 'get-url', 'chess'], { cwd : dir.name, stdio : 'ignore' }).then(()=>{
  505. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  506. })
  507. .catch((e)=>{
  508. any( serial_perform_init_gitea(dir.name).map(x) )
  509. })
  510. }
  511. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  512. }).catch((e)=>{
  513. // console.log('Failed : ' + dir.name)
  514. })
  515. }
  516. const { readdir } = require("fs").promises
  517. const dirs = async (perform, path) => {
  518. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  519. if (dir.isDirectory()) perform(dir)
  520. }
  521. }
  522. dirs(perform_init_gitea)
  523. }
  524. , 'pull' : (label) => {
  525. // Usage :
  526. // elxr pull -- Defaults to run config
  527. var env = Object.assign({}, process.env); // Shallow clone it.
  528. // console.dir(env)
  529. console.log('Running exlr pull : ' + path.dirname(__dirname))
  530. // nodeShellExec('cmd', ['/c', 'setup\\utility\\chess.bat', 'pull'], {
  531. // // nodeShellExec('cmd', ['/c', '..\\setup\\utility\\chess.bat', 'pull'], {
  532. // stdio: ['pipe', process.stdout, process.stderr],
  533. // inherit : true,
  534. // shell: true,
  535. // cwd : path.dirname(__dirname),
  536. // env: env
  537. // })
  538. var useGitPull = processedArgs.useGitPull || false;
  539. var getPullCmd = (repo)=>{
  540. // console.log(useGitPull)
  541. var pullCmd = ["C:\\Program Files\\Git\\bin\\sh.exe"
  542. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  543. , { cwd : repo, title : 'pull all origins for ' + repo }]
  544. // var pullCmd = ['pullall', [], { cwd : repo }]
  545. if(useGitPull) pullCmd = ['git', ['pull'], {
  546. inherit : true, shell: true,
  547. cwd : repo
  548. // , env: process.env
  549. , runas : processedArgs.runas
  550. , title : `git pull ${repo}`
  551. }]
  552. return pullCmd
  553. }
  554. var performPull = (repo) => {
  555. if(existsSync(repo)) {
  556. console.log('pulling ' + repo)
  557. return nodeShellExec.apply(null, getPullCmd(repo)).catch((e)=>{ console.error(e) })
  558. }
  559. else {
  560. console.log('cloning ' + repo)
  561. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', defaultRepoServer + '/' + repo + '.git'],
  562. {
  563. inherit : true, shell: true,
  564. env: process.env
  565. , runas : processedArgs.runas
  566. }).catch((e)=>{ console.error(e) }).then(()=>{
  567. return nodeShellExec('git', ['config', '--replace-all' , 'core.symlinks', true],
  568. {
  569. inherit : true, shell: true,
  570. env: process.env
  571. , cwd : repo
  572. , runas : processedArgs.runas
  573. , title : `git core.symlinks --replace-all true for ${defaultRepoServer + '/' + repo + '.git'}`
  574. })
  575. })
  576. }
  577. }
  578. if(!processedArgs.runas) gitRepos.forEach(performPull)
  579. return isRunningElevated().then(
  580. (isElevated) => {
  581. if(isElevated) {
  582. any(elevatedRunasRepos.map((repo)=>performPull(repo))).then(()=>{
  583. fs.writeFileSync('run.done', 'success')
  584. }).catch(()=>{
  585. fs.writeFileSync('run.done', 'error')
  586. })
  587. }
  588. else throw false;
  589. }
  590. ).catch(
  591. () => {
  592. op['runas']()
  593. }
  594. )
  595. }
  596. , 'isInstalled' : ()=>{
  597. return nodeShellExec('where', [processedArgs._[1]], { inherit : true} ).then(()=>{
  598. console.log(processedArgs._[1] + ' exists.')
  599. return true;
  600. });
  601. }
  602. , 'npmi' : ()=>{
  603. var tasks = [];
  604. gitRepos.forEach(repo => {
  605. console.log('npm i for ' + repo)
  606. // nodeShellExec('pwd', [], {
  607. // // inherit : true, shell: true
  608. // cwd : repo
  609. // // , env: process.env
  610. // , title : `pwd for ${repo}`
  611. // }).catch((e)=>{ console.error(e) })
  612. nodeShellExec('rm', ['package-lock.json'], {
  613. inherit : true, shell: true
  614. , cwd : repo
  615. , env: process.env
  616. , title : `rm 'package-lock.json' for ${repo}`
  617. }).catch((e)=>{ console.error(e) })
  618. tasks.push(()=>{
  619. var p = nodeShellExec('npm', ['i'], {
  620. inherit : true, shell: true
  621. , cwd : repo
  622. , env: process.env
  623. , title : `npm i for ${repo}`
  624. }).catch((e)=>{ console.error(e) })
  625. return p;
  626. })
  627. })
  628. any(tasks);
  629. }
  630. , 'start' : (label)=>{
  631. console.log('Starting Elixir Server.');
  632. var env = Object.assign({}, process.env); // Shallow clone it.
  633. // console.dir(env)
  634. env.NODE_ENV = process.env.NODE_ENV || 'development';
  635. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  636. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  637. // cmd = 'node'
  638. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
  639. var childPromise = nodeShellExec(...cmd, {
  640. // inherit : true,
  641. shell: true,
  642. detached: true,
  643. stdio: 'ignore',
  644. cwd : 'elixir-server'
  645. , env: env
  646. })
  647. var child = childPromise.process;
  648. if (typeof child.pid !== 'undefined') {
  649. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  650. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  651. encoding: 'utf8'
  652. })
  653. }
  654. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  655. // inherit : true,
  656. // shell: true, detached: true,
  657. // cwd : 'qms/server',
  658. // env: env,
  659. // shell : true
  660. // })
  661. // nodeShellExec('ember', ['s'], {
  662. // // inherit : true,
  663. // shell: true, detached: true,
  664. // cwd : 'client/',
  665. // env: env
  666. // })
  667. console.log('Starting Elixir Client Host.');
  668. var cmd = ['ember', ['s']]
  669. var childPromise = nodeShellExec(...cmd, {
  670. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  671. // PB : TODO -- ember debugging.
  672. // inherit : true,
  673. shell: true,
  674. detached: true,
  675. stdio: 'ignore',
  676. cwd : 'client'
  677. , env: env
  678. })
  679. // .catch(e=>console.error(e))
  680. child = childPromise.process;
  681. if (typeof child.pid !== 'undefined') {
  682. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  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. }