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

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