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

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