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.

index.js 41KB

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