Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
4 anos atrás
4 anos atrás
3 anos atrás
3 anos atrás
5 anos atrás
6 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
6 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
4 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
4 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
5 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
5 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
6 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
3 anos atrás
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083
  1. var path = require('path');
  2. var utils = require('bbhverse');
  3. var any = utils.any;
  4. var Tasq = utils.Tasq
  5. var statuslog = utils.Traq
  6. var Traq = utils.Traq
  7. Tasq.addlistener(statuslog.statuslog)
  8. var cli = require('./cliverse')
  9. var nodeShellExec = cli.nodeShellExec;
  10. var chalk = require('chalk')
  11. const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  12. const runtimestamp = (new Date()).getTime();
  13. function getVersion() { return BUILD_VERSION; }
  14. console.log(getVersion())
  15. // 'use strict';
  16. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  17. // PB : TODO --
  18. // runas bypass non elevated tasks when we request privelege
  19. // runas message is always error needs to be fixed.
  20. // runas wait needs to be parallelized.
  21. // suppress elevation check error messages
  22. // support runas lauched directly from shell.
  23. // pass in environment in hta to shellexecute.
  24. const { existsSync } = require('fs');
  25. const fs = require('fs')
  26. const cliargs = utils.cliargs;
  27. const processedArgs = cliargs(process.argv.slice(2));
  28. console.dir(processedArgs)
  29. var globSync = require('glob').sync;
  30. var ENV = Object.assign({}, process.env); // Shallow clone it.
  31. const { readdir } = require("fs").promises
  32. // Directory shallow walk and do perform on each dir.
  33. const dirs = async (perform, path) => {
  34. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  35. if (dir.isDirectory()) perform(dir)
  36. }
  37. }
  38. var getShellTask = (command, args, options) => {
  39. options = options || {}
  40. return () => {
  41. var p = nodeShellExec.apply(null, [command, args, Object.assign({
  42. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  43. }, options)
  44. ])
  45. if (options.ignorefailures) {
  46. return p.catch(e => {
  47. // Ignore. Not a major error.
  48. })
  49. }
  50. else return p;
  51. }
  52. }
  53. var callsheltask = (args) => { return () => { return nodeShellExec.apply(null, args) } }
  54. var getTaskCheckExists = (command, options) => {
  55. options = options || {}
  56. return () => {
  57. var p = nodeShellExec.apply(null, ['where', [command]])
  58. if (options.ignorefailures) {
  59. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  60. return false;
  61. })
  62. }
  63. else return p.then(() => { return true });
  64. }
  65. }
  66. var getTaskWithElevation = function(tasdef){
  67. return ()=>{
  68. if (__isElevated) {
  69. return tasdef.elevatedpulltasks();
  70. }
  71. else {
  72. // PB : TODO -- Rename op['runas'] to 'elevate'
  73. return op['runas']().then(() => { return true; })
  74. .catch((e) => {
  75. console.error(e)
  76. })
  77. .finally(() => {
  78. if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
  79. })
  80. }
  81. }
  82. }
  83. var getTaskWithoutElevation = function(tasdef){
  84. return ()=>{
  85. if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  86. else Promise.resolve(true)
  87. }
  88. }
  89. var gitops = {
  90. getdiscoverbranchcmd : function(repo){
  91. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  92. var cmd = [gitbash
  93. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  94. , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo + ' ' + parameters.join(' ') }]
  95. return cmd
  96. }
  97. }
  98. var getPullCmd = (repo, branch) => {
  99. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  100. // console.log(useGitPull)
  101. if(branch) {
  102. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  103. var pullCmd = [ gitbash
  104. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  105. , { cwd: instanceroot + '/' + repo, title : 'pull all origins for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  106. }
  107. else {
  108. console.warn('No branch was specified detecting from working client.')
  109. var pullCmd = gitops.getdiscoverbranchcmd(repo)
  110. }
  111. // var pullCmd = ['pullall', [], { cwd : repo }]
  112. if (useGitPull) pullCmd = ['git', ['pull'], {
  113. inherit: true, shell: true,
  114. cwd: instanceroot + '/' + repo
  115. // , env: process.env
  116. , runas: processedArgs.runas
  117. , title: `git pull ${repo}`
  118. }]
  119. return pullCmd
  120. }
  121. var performPull = (repo, branch) => {
  122. // PB : TODO -- Handle no branch passed in case.
  123. // if(!branch) { throw 'No branch specified' }
  124. if (existsSync(instanceroot + '/' + repo)) {
  125. var branchprint = branch ? ' branch :' + branch : '';
  126. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  127. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  128. if (__isElevated) {
  129. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  130. }
  131. else statuslog.statuslog(null, repo)
  132. return true;
  133. })
  134. .catch((e) => {
  135. e.repo = repo;
  136. if (__isElevated) {
  137. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  138. }
  139. else statuslog.statuslog(e); console.error(e)
  140. })
  141. }
  142. else {
  143. console.log('cloning ' + repo)
  144. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  145. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'],
  146. {
  147. inherit: true, shell: true,
  148. env: process.env
  149. , cwd : instanceroot
  150. , runas: processedArgs.runas
  151. }).catch((e) => {
  152. throw e;
  153. }).then(() => {
  154. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  155. {
  156. inherit: true, shell: true,
  157. env: process.env
  158. , cwd: instanceroot + '/' + repo
  159. , runas: processedArgs.runas
  160. , title: `git core.symlinks --replace-all true for ${selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'}`
  161. })
  162. .then(() => {
  163. if (__isElevated) {
  164. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  165. }
  166. else statuslog.statuslog(null, repo)
  167. })
  168. .catch((e) => {
  169. e.repo = repo;
  170. if (__isElevated) {
  171. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  172. }
  173. else statuslog.statuslog(e);
  174. })
  175. })
  176. .catch(e => {
  177. e.repo = repo;
  178. if (__isElevated) {
  179. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  180. }
  181. else statuslog.statuslog(e);
  182. })
  183. }
  184. }
  185. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  186. // -- Currently workaround is to always run from a non-elevated shell.
  187. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  188. var acquireElevationState = () => {
  189. if (__isElevated === null) {
  190. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  191. inherit: true
  192. // , shell: true
  193. , stdio: 'ignore'
  194. , env: process.env
  195. , title: `check privileged execution mode using "fsutil dirty query C:"`
  196. }).then((exitcode) => {
  197. console.log('Elevated')
  198. __isElevated = true;
  199. return true;
  200. }).catch(() => {
  201. __isElevated = false;
  202. console.log('Not Elevated');
  203. return false;
  204. });
  205. }
  206. else return Promise.resolve(__isElevated);
  207. }
  208. var repomanifest = null;
  209. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current gittea username
  210. var defaultRepoOwner = 'chess';
  211. var elevatedRunasRepos = null
  212. var gitRepos = null
  213. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  214. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  215. var dbForLabel = function (label) {
  216. var dbsForLabel = {
  217. devmysql: 'mysql'
  218. , development: 'mssql'
  219. , production: 'mssql'
  220. }
  221. return dbsForLabel[label] || 'mysql'
  222. }
  223. // SAM : TODO Use nodeshellexec where to detect git installation dir
  224. var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe"
  225. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  226. // Relevant git repos
  227. // var repomanifest = require('../'+repomanifest.instanceName+'-config-'+ nodeenv +'/repo-manifest')()
  228. var exludeMergeRepos = [];
  229. var useGitPull = processedArgs.useGitPull || false;
  230. var configPromise = null
  231. // elxr cli operations
  232. var op = {
  233. 'h': () => { console.log(elxr.help()); return '-h' }
  234. , 'clean' : () => {
  235. // delete all node_module folders and links.
  236. var tasklist = [];
  237. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot )
  238. return Promise.all(tasklist)
  239. }
  240. , 'undefined': () => { return op.h(); }
  241. , 'reset': () => {
  242. // Reset NPM packages semver so major versions can be updated.
  243. const fs = require('fs')
  244. const wipeDependencies = (__package) => {
  245. const file = fs.readFileSync(__package + '/package.json')
  246. const content = JSON.parse(file)
  247. for (var devDep in content.devDependencies) {
  248. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  249. content.devDependencies[devDep] = '*';
  250. }
  251. }
  252. for (var dep in content.dependencies) {
  253. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  254. content.dependencies[dep] = '*';
  255. }
  256. }
  257. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  258. }
  259. var repos = ['client'];
  260. // repos = gitRepos;
  261. repos.forEach(wipeDependencies)
  262. // if (require.main === module) {
  263. // } else {
  264. // module.exports = wipeDependencies
  265. // }
  266. }
  267. , 'upgrade': () => {
  268. console.log('upgrade.......')
  269. var tasks = [
  270. () => {
  271. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  272. inherit: true, shell: true
  273. , env: process.env
  274. }).catch((e) => { console.error(e) })
  275. p.position = 1;
  276. console.log('One')
  277. return p;
  278. }
  279. , () => {
  280. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  281. inherit: true, shell: true
  282. , env: process.env
  283. }).catch((e) => { console.error(e) })
  284. p.position = 2;
  285. console.log('Two')
  286. return p;
  287. }
  288. , () => {
  289. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  290. inherit: true, shell: true
  291. , env: process.env
  292. }).catch((e) => { console.error(e) })
  293. p.position = 3;
  294. console.log('Three')
  295. return p;
  296. }
  297. , () => {
  298. var p = nodeShellExec('n', ['latest'], {
  299. inherit: true, shell: true
  300. , env: process.env
  301. }).catch((e) => { console.error(e) })
  302. p.position = 4;
  303. console.log('Four')
  304. return p;
  305. }
  306. ]
  307. any(tasks)
  308. console.log('.......done')
  309. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  310. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  311. console.info('Uninstalling existing ember globally');
  312. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  313. stdio: ['pipe', process.stdout, process.stderr],
  314. inherit: true,
  315. shell: true,
  316. cwd: path.dirname(__dirname),
  317. env: env
  318. })
  319. step1.on('close', () => {
  320. console.info('Installing ember globally');
  321. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  322. stdio: ['pipe', process.stdout, process.stderr],
  323. inherit: true,
  324. shell: true,
  325. cwd: path.dirname(__dirname),
  326. env: env
  327. })
  328. step2.on('close', () => {
  329. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  330. stdio: ['pipe', process.stdout, process.stderr],
  331. inherit: true,
  332. shell: true,
  333. cwd: path.dirname(__dirname),
  334. env: env
  335. })
  336. })
  337. })
  338. }
  339. , 'runas': () => {
  340. console.log('Testing Elevation')
  341. if (__isElevated) {
  342. try {
  343. op[processedArgs.label || processedArgs._[0] || 'h']()
  344. }
  345. catch (e) {
  346. console.error('Error Invalid command : ' + e)
  347. fs.writeFileSync('run.done', 'error')
  348. }
  349. finally {
  350. }
  351. }
  352. else {
  353. console.log('Requesting Elevated Privileges');
  354. // Wait for the runas to complete before we read it.
  355. try {
  356. fs.unlinkSync('run.done')
  357. fs.unlinkSync('run.log')
  358. }
  359. catch (e) { } //Ignore
  360. // Find node path to send to hta.
  361. return nodeShellExec('where', ['node']).then(r => {
  362. var namedArgs = [];
  363. console.log('result : ' + JSON.stringify(r))
  364. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; })
  365. // PB : TODO -- Convert all the cli args back to string.
  366. var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  367. args.push('--nodepath=' + r[r.length - 1])
  368. if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
  369. if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
  370. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  371. , {
  372. inherit: true
  373. , shell: true
  374. , env: ENV
  375. , runas: 'self'
  376. , title: `runas`
  377. }
  378. ).then(() => {
  379. // runas returned.
  380. try {
  381. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  382. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  383. runaslog.forEach((logEntry) => {
  384. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry)
  385. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  386. })
  387. }
  388. catch (e) {
  389. // We must have a runas log
  390. statuslog.statuslog(e)
  391. console.error('Run log error probably was not created by runas : ' + e)
  392. }
  393. })
  394. .catch(err => console.error('Elevation failed : ' + err));
  395. })
  396. }
  397. }
  398. , 'push': () => {
  399. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  400. // init remote bare from local
  401. // pushandinitremotebare
  402. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  403. // connect to repo server -- net use 172.16.0.27
  404. // cd 172.16.0.27/repos/
  405. // mkdir repo.git
  406. // cd repo.git
  407. // git init --bare
  408. // cd localrepo
  409. // git remote rename origin githubclone
  410. // git remote add origin //172.16.0.27/repos/repo.git
  411. // git push origin master
  412. var repo = processedArgs._[1];
  413. var sequentialTaskShellCommands = [];
  414. if (!existsSync(`Z:/${repo}.git`)) {
  415. sequentialTaskShellCommands = [
  416. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  417. // inherit : true, shell: true
  418. // , env: process.env
  419. // }]
  420. ['pwd', { cwd: 'Z:', inherit: true }]
  421. , ['mkdir', [`${repo}.git`], {
  422. cwd: `Z:`
  423. , inherit: true, shell: true
  424. , env: process.env
  425. }]
  426. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  427. , ['git', ['init', '--bare'], {
  428. cwd: `Z:/${repo}.git`
  429. , inherit: true, shell: true
  430. , env: process.env
  431. }]
  432. // PB : TODO -- Do this conditionally only...
  433. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  434. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  435. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  436. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  437. // PB : TODO -- If threre is a gitbubclone origin
  438. // Set the master to pull from the local repo.
  439. ]
  440. if (!existsSync(`Z:`)) {
  441. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  442. inherit: true, shell: true
  443. , env: process.env
  444. }])
  445. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  446. // throw 'done'
  447. }
  448. }
  449. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }])
  450. // console.dir(sequentialTaskShellCommands);
  451. var tasks = [];
  452. sequentialTaskShellCommands.forEach(shellcmd => {
  453. // console.log(shellcmd)
  454. tasks.push(() => {
  455. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
  456. return p;
  457. })
  458. })
  459. any(tasks);
  460. }
  461. , 'is-git-repo': (dir) => {
  462. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  463. }
  464. , 'set-url': (remotename, url) => {
  465. var pushable = processedArgs.pushable || false;
  466. remotename = remotename || processedArgs._[1]
  467. url = url || processedArgs._[2]
  468. var serial_perform_git_seturl = (repo) => {
  469. var options = { cwd: instanceroot + '/' + repo }
  470. // console.log(repo)
  471. if (pushable) {
  472. return [
  473. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  474. ]
  475. }
  476. else {
  477. console.error('not supported for non-pushable')
  478. }
  479. }
  480. var perform_git_seturl = (dir) => {
  481. op['is-git-repo'](dir).then((logEntry) => {
  482. any(serial_perform_git_seturl(dir.name).map(x))
  483. }).catch((e) => {
  484. // console.log('Failed : ' + dir.name)
  485. })
  486. }
  487. dirs(perform_git_seturl)
  488. }
  489. , 'add': (remotename, url, branch) => {
  490. var pushable = processedArgs.pushable || false;
  491. remotename = remotename || processedArgs._[1]
  492. url = url || processedArgs._[2]
  493. branch = branch || processedArgs._[3]
  494. var serial_perform_git_add = (repo) => {
  495. var options = { cwd: instanceroot + '/' + repo }
  496. // console.log(repo)
  497. if (pushable) {
  498. return [
  499. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  500. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  501. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  502. ]
  503. }
  504. else {
  505. return [
  506. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  507. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  508. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  509. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  510. ]
  511. }
  512. }
  513. var x = (args) => {
  514. return () => {
  515. // console.log(args)
  516. return nodeShellExec.apply(null, args)
  517. }
  518. // return Promise.resolve(true)
  519. }
  520. var perform_git_add = (dir) => {
  521. op['is-git-repo'](dir).then((logEntry) => {
  522. // console.log(code)
  523. if (logEntry.success) {
  524. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  525. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  526. })
  527. .catch((e) => {
  528. any(serial_perform_git_add(dir.name).map(x))
  529. })
  530. }
  531. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  532. }).catch((e) => {
  533. // console.log('Failed : ' + dir.name)
  534. })
  535. }
  536. const { readdir } = require("fs").promises
  537. dirs(perform_git_add)
  538. }
  539. , 'remove': (remotename) => {
  540. remotename = remotename || processedArgs._[1]
  541. var serial_perform_git_remove = (repo) => {
  542. var options = { cwd: instanceroot + '/' + repo }
  543. // console.log(repo)
  544. return [
  545. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  546. ]
  547. }
  548. var x = (args) => {
  549. return () => {
  550. // console.log(args)
  551. return nodeShellExec.apply(null, args)
  552. }
  553. // return Promise.resolve(true)
  554. }
  555. var perform_git_remove = (dir) => {
  556. op['is-git-repo'](dir).then((logEntry) => {
  557. // console.log(code)
  558. if (logEntry.success) {
  559. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  560. any(serial_perform_git_remove(dir.name).map(x))
  561. })
  562. .catch((e) => {
  563. console.log('skipped : ' + dir.name + ', reason : No remote named origin')
  564. })
  565. }
  566. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  567. }).catch((e) => {
  568. // console.log('Failed : ' + dir.name)
  569. })
  570. }
  571. const { readdir } = require("fs").promises
  572. dirs(perform_git_remove)
  573. }
  574. , 'init-gitea': (user) => {
  575. user = user || processedArgs._[1]
  576. if (!user) throw 'User name required'
  577. var serial_perform_init_gitea = (repo) => {
  578. var options = { cwd: instanceroot + '/' + repo }
  579. // console.log(repo)
  580. return [
  581. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  582. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  583. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  584. ]
  585. }
  586. var x = (args) => {
  587. return () => {
  588. // console.log(args)
  589. return nodeShellExec.apply(null, args)
  590. }
  591. // return Promise.resolve(true)
  592. }
  593. var perform_init_gitea = (dir) => {
  594. op['is-git-repo'](dir).then((logEntry) => {
  595. // console.log(code)
  596. if (logEntry.success) {
  597. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  598. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  599. })
  600. .catch((e) => {
  601. any(serial_perform_init_gitea(dir.name).map(x))
  602. })
  603. }
  604. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  605. }).catch((e) => {
  606. // console.log('Failed : ' + dir.name)
  607. })
  608. }
  609. const { readdir } = require("fs").promises
  610. dirs(perform_init_gitea)
  611. }
  612. , 'syncmaster': (label) => {
  613. // Usage :
  614. // elxr pull -- Defaults to run config
  615. var env = Object.assign({}, process.env); // Shallow clone it.
  616. // console.dir(env)
  617. console.log('Running exlr pull : ' + path.dirname(__dirname))
  618. if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'))
  619. if (__isElevated) {
  620. return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
  621. fs.writeFileSync('run.done', 'success')
  622. }).catch(() => {
  623. fs.writeFileSync('run.done', 'error')
  624. })
  625. }
  626. else return op['runas']()
  627. }
  628. , 'pull' : (label) => {
  629. // Usage :
  630. // elxr pull -- Defaults to run config
  631. return elxr.getpulltask()()
  632. }
  633. , 'isInstalled': () => {
  634. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  635. console.log(processedArgs._[1] + ' exists.')
  636. return true;
  637. });
  638. }
  639. , 'i' : () => {
  640. var tasks = []
  641. // tasks.push(op['pull']);
  642. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
  643. tasks.push(op['use'])
  644. if (!__isElevated) {
  645. tasks.push(op['npmi'])
  646. }
  647. // var tasksdefs = [
  648. // ['elxr', ['pull']]
  649. // , ['elxr', ['use', 'elixir']]
  650. // , ['elxr', ['npmi']]
  651. // ]
  652. // tasksdefs.forEach(tasksdef=>{
  653. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  654. // })
  655. return any(tasks);
  656. }
  657. , 'npmi': () => {
  658. var tasks = [];
  659. // Build fails without babel...
  660. tasks.push(getShellTask(
  661. 'npm',[ 'i', '-g', 'babel-cli' ]
  662. ) )
  663. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  664. npmbuildrepos = []
  665. npmbuildrepos.forEach(repo => {
  666. tasks.push(() => {
  667. return nodeShellExec('npm', ['i --force'], {
  668. inherit: true, shell: true
  669. , cwd: instanceroot + '/' + repo
  670. , env: process.env
  671. , title: `npm i for ${repo}`
  672. }).catch((e) => {
  673. console.error('Ignoring Benign Error'); console.error(e);
  674. }).then(() => {
  675. console.log(`--npm run build for ${repo}--------------------`)
  676. return nodeShellExec('npm', ['run build'], {
  677. inherit: true, shell: true
  678. , cwd: instanceroot + '/' + repo
  679. , env: process.env
  680. , title: `npm run build for ${repo}`
  681. }).then(Tasq.then).catch(Tasq.catch)
  682. })
  683. })
  684. })
  685. any(tasks).then(() => {
  686. gitRepos.push('client/server');
  687. gitRepos = gitRepos.concat(elevatedRunasRepos);
  688. // gitRepos = [
  689. // // 'bbhverse', 'serververse', 'elixir-server',
  690. // // 'clientverse',
  691. // 'client'
  692. // ];
  693. var rmtasks = []
  694. var repotasks = []
  695. var env = Object.assign({}, process.env)
  696. delete env.NODE_ENV
  697. gitRepos.forEach(repodef => {
  698. rmtasks.push(
  699. // () => {
  700. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  701. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  702. nodeShellExec('rm', ['package-lock.json'], {
  703. inherit: true, shell: true
  704. , cwd: instanceroot + '/' + repodef.repo
  705. , env: process.env
  706. , title: `rm 'package-lock.json' for ${repodef.repo}`
  707. })
  708. .then(()=>{
  709. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  710. }).catch((e) => { console.error(e) })
  711. // }
  712. )
  713. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  714. repotasks.push(
  715. () => {
  716. console.log(`--npm i for ${repodef.repo}--------------------`)
  717. var p = nodeShellExec('npm', ['i', '--force'], {
  718. inherit: true, shell: true
  719. , cwd: instanceroot + '/' + repodef.repo
  720. , env
  721. , title: `npm i for ${repodef.repo}`
  722. }).then(Tasq.then).catch(Tasq.catch)
  723. return p;
  724. })
  725. }
  726. })
  727. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  728. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  729. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  730. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  731. // Second time try also doesnt work.
  732. // repotasks.push(
  733. // () => {
  734. // var env = Object.assign({}, process.env)
  735. // delete env.NODE_ENV
  736. // console.log(`--------------------second time npm i for client--------------------`)
  737. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  738. // // return nodeShellExec('npm', ['i --force'], {
  739. // inherit: true, shell: true
  740. // , cwd: instanceroot + '/' + 'client'
  741. // , env
  742. // , title: `npm i for client`
  743. // }).then(Tasq.then).catch(Tasq.catch)
  744. // })
  745. var bowerRepos = [{ repo : 'client'}]
  746. bowerRepos.forEach(repodef => {
  747. repotasks.push(() => {
  748. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
  749. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  750. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  751. inherit: true, shell: true
  752. , cwd: instanceroot + '/' + repodef.repo
  753. , env: process.env
  754. , title: `bower i for ${repodef.repo}`
  755. }).then(Tasq.then).catch(Tasq.catch)
  756. return p;
  757. })
  758. })
  759. // console.log('rmtasks.length : ' + rmtasks.length)
  760. return Promise.all(rmtasks).then(() => any(repotasks));
  761. }).catch(e => {
  762. }).finally(statuslog.finally)
  763. }
  764. , 'start': (label) => {
  765. console.log('Starting Elixir Server.');
  766. var env = Object.assign({}, process.env); // Shallow clone it.
  767. // console.dir(env)
  768. env.NODE_ENV = process.env.NODE_ENV || 'development';
  769. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  770. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  771. // cmd = 'node'
  772. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
  773. var childPromise = nodeShellExec(...cmd, {
  774. // inherit : true,
  775. shell: true,
  776. detached: true,
  777. stdio: 'ignore',
  778. cwd: instanceroot + '/' + 'elixir-server'
  779. , env: env
  780. })
  781. var child = childPromise.process;
  782. if (typeof child.pid !== 'undefined') {
  783. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  784. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  785. encoding: 'utf8'
  786. })
  787. }
  788. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  789. // inherit : true,
  790. // shell: true, detached: true,
  791. // cwd : 'qms/server',
  792. // env: env,
  793. // shell : true
  794. // })
  795. // nodeShellExec('ember', ['s'], {
  796. // // inherit : true,
  797. // shell: true, detached: true,
  798. // cwd : 'client/',
  799. // env: env
  800. // })
  801. console.log('Starting Elixir Client Host.');
  802. var cmd = ['ember', ['s']]
  803. var childPromise = nodeShellExec(...cmd, {
  804. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  805. // PB : TODO -- ember debugging.
  806. // inherit : true,
  807. shell: true,
  808. detached: true,
  809. stdio: 'ignore',
  810. cwd: instanceroot + '/' + 'client'
  811. , env: env
  812. })
  813. // .catch(e=>console.error(e))
  814. child = childPromise.process;
  815. if (typeof child.pid !== 'undefined') {
  816. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  817. fs.writeFileSync('.client.server.pid', child.pid, {
  818. encoding: 'utf8'
  819. })
  820. }
  821. }
  822. , 'stop': (label) => {
  823. const kill = require('tree-kill');
  824. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  825. encoding: 'utf8'
  826. })
  827. fs.unlinkSync('.elixir-server.elixir.server.pid')
  828. console.log(serverPid)
  829. kill(serverPid)
  830. serverPid = fs.readFileSync('.client.server.pid', {
  831. encoding: 'utf8'
  832. })
  833. fs.unlinkSync('.client.server.pid')
  834. console.log(serverPid)
  835. kill(serverPid)
  836. }
  837. , 'model' : () => {
  838. if (__isElevated) {
  839. var tasks = [
  840. () => {
  841. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  842. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  843. inherit: true, shell: true
  844. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  845. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  846. , env: process.env
  847. }).catch((e) => { console.error(e) })
  848. return p;
  849. }
  850. ];
  851. return any(tasks).then(() => {
  852. fs.writeFileSync('run.done', 'success')
  853. }).catch(() => {
  854. fs.writeFileSync('run.done', 'error')
  855. })
  856. }
  857. else return op['runas']()
  858. }
  859. , 'use' : () => {
  860. // use a certain named instance.
  861. // Eg :
  862. // 1) elxr use elixir
  863. // 2) elxr use cihsr
  864. // If environment is not specified defaults to development.
  865. // 1) NODE=test elxr use elixir
  866. /*// Steps
  867. 1) Delete Config and Data symlinks
  868. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  869. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  870. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  871. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  872. */
  873. var runconfig = { NODE_ENV: repomanifest.node_env }
  874. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  875. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  876. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  877. runconfig.NODE_ENV && runconfig.NODE_ENV === (repomanifest.node_env || runconfig.NODE_ENV) &&
  878. repomanifest.instanceName && runconfig.use === repomanifest.instanceName) {
  879. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  880. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  881. return
  882. }
  883. var tasks = [
  884. () => {
  885. if (existsSync('config')) {
  886. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  887. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  888. return p;
  889. }
  890. else return Promise.resolve(true);
  891. },
  892. () => {
  893. if (existsSync('data')) {
  894. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  895. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  896. return p;
  897. }
  898. else return Promise.resolve(true);
  899. },
  900. ];
  901. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  902. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  903. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  904. // console.log(process.env.cwd)
  905. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  906. // Maps an environment to a branch. Not required if the branch is appropriately named.
  907. var checkoutMap = { 'development': 'master' }
  908. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  909. var performPullOrCloneForBranch = (def)=>{
  910. var promise = Promise.resolve(true)
  911. if (!branch) {
  912. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  913. promise = nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{ branch = __branch})
  914. .catch((e) => { console.error(e); return { error: true, message: repo } })
  915. }
  916. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e )})
  917. }
  918. var performCloneAndCheckout = null;
  919. // cant use git checkout -b it fails when branch already exists.
  920. var performCheckout = performCloneAndCheckout = (def) => {
  921. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  922. return performPullOrCloneForBranch(def).then(()=>{
  923. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  924. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  925. // inherit : true, shell: true,
  926. cwd: instanceroot + '/' + def.repo
  927. // , stdio : ignore // Use when we want to silence output completely.
  928. , runas: processedArgs.runas
  929. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  930. }).then(()=>{ console.log( `SUCCESS : git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}` ) }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  931. })
  932. }
  933. // var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  934. // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  935. var elevatedqueue = [];
  936. var enqueueOnce = (queue, task, def) => {
  937. var found = queue.find(element => {
  938. var keys = Object.keys( element )
  939. for(var k=0; k < keys.length; k++) {
  940. if(element[keys[k]] !== def[k]) return false;
  941. }
  942. })
  943. queue.push(function(){ return task(this)}.bind(def));
  944. }
  945. var enqueue = (queue, task, def) => {
  946. queue.push(function(){ return task(def)}.bind(def));
  947. }
  948. var mergeSources = {
  949. 'development': null,
  950. 'test': 'master',
  951. 'production': 'master'
  952. }
  953. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  954. // Checkout is reduced to pull provided the current branch is the targetbranch
  955. if(branch === mergesource) performCheckout = (def) => {
  956. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  957. return nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{
  958. if(branch === __branch) return performCloneAndCheckout(def)
  959. return performPullOrCloneForBranch(def)
  960. })
  961. .catch((e) => { console.error(e); return { error: true, message: repo } })
  962. }
  963. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  964. var performPullAll = (def) => {
  965. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  966. return nodeShellExec('git', ['pull', '--all'], {
  967. // inherit : true, shell: true,
  968. cwd: instanceroot + '/' + def.repo
  969. , runas: processedArgs.runas
  970. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  971. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  972. }
  973. var excludeCheckouts = Object.assign(exludeMergeRepos)
  974. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  975. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  976. var performMerge = (def) => {
  977. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  978. return nodeShellExec('git', ['merge', mergesource], {
  979. inherit: true, shell: true,
  980. cwd: instanceroot + '/' + def.repo
  981. , runas: processedArgs.runas
  982. }).catch((e) => { console.error(e) })
  983. }
  984. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
  985. // var performRepoOperation = function(def) {
  986. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  987. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  988. // }
  989. return any(tasks).then(() => {
  990. var pr = Promise.resolve(true)
  991. if (!__isElevated) {
  992. pr = op['runas']()
  993. return pr.then(()=>{
  994. //target is the env is we specify in elxr use command. Default is dev
  995. //Switch to target branch
  996. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  997. // pull or clone target branch
  998. .then(() => {
  999. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1000. return any(gitRepos.map((repo) => performPullAll(repo)))
  1001. })
  1002. // switch to source branch
  1003. .then( () => {
  1004. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  1005. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  1006. })
  1007. //Pull on merge source branch
  1008. .then( () => {
  1009. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1010. return any(gitRepos.map((repo) => performPullAll(repo)))
  1011. })
  1012. //Switch to target branch
  1013. .then( () => {
  1014. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1015. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  1016. })
  1017. .then( //Merge source branch to target branch
  1018. () => {
  1019. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1020. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
  1021. })
  1022. })
  1023. }
  1024. else {
  1025. tasks = [
  1026. () => {
  1027. // Use junctions to avoid npm package issues
  1028. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  1029. inherit: true, shell: true
  1030. , cwd : instanceroot
  1031. , env: process.env
  1032. }).catch((e) => { console.error(e) })
  1033. return p;
  1034. }
  1035. ];
  1036. if (processedArgs._[1]) {
  1037. tasks = tasks.concat(
  1038. [
  1039. () => {
  1040. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  1041. inherit: true, shell: true
  1042. , cwd : instanceroot
  1043. , env: process.env
  1044. }).catch((e) => { console.error(e) })
  1045. return p;
  1046. }
  1047. ]
  1048. )
  1049. }
  1050. return any(tasks).then(()=>{
  1051. // checkout target branch
  1052. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1053. // pull or clone target branch
  1054. .then(() => {
  1055. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1056. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  1057. })
  1058. // switch to source branch
  1059. .then( () => {
  1060. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1061. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  1062. })
  1063. //Pull on merge source branch
  1064. .then( () => {
  1065. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1066. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  1067. })
  1068. //Switch to target branch
  1069. .then( () => {
  1070. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1071. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1072. })
  1073. .then( //Merge source branch to target branch
  1074. () => {
  1075. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1076. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
  1077. })
  1078. .then(() => {
  1079. fs.writeFileSync('run.done', 'success')
  1080. }).catch(() => {
  1081. fs.writeFileSync('run.done', 'error')
  1082. })
  1083. })
  1084. }
  1085. }).catch(() => {
  1086. fs.writeFileSync('run.done', 'error')
  1087. })
  1088. // Antibiotic stewardship program.
  1089. // 1st use is fine.
  1090. // Max vials dispense
  1091. // 2nd use Pharmacy needs justification Form.
  1092. // Approval after a certain period of time.
  1093. }
  1094. , 'g': () => {
  1095. if (processedArgs.h) {
  1096. console.log('elxr g [modelname] => generate a model named [modelname]');
  1097. console.log('elxr g => regenerate all known models');
  1098. return
  1099. }
  1100. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1101. // console.log('Starting directory: ' + process.cwd());
  1102. // try {
  1103. // child = child.on('close', () => { process.chdir(label) } );
  1104. // console.log('New directory: ' + process.cwd());
  1105. // }
  1106. // catch (err) {
  1107. // console.log('chdir: ' + err);
  1108. // }
  1109. // child.on('close', function(){
  1110. // var options = {
  1111. // shell : true
  1112. // , inherit : true
  1113. // // , cwd : '' + process.cwd
  1114. // // , env : process.env
  1115. // };
  1116. // nodeShellExec('git', ['init'], { inherit : true});
  1117. if (0) {
  1118. // PB : TODO -- Special google chrome profile for tests etc.
  1119. nodeShellExec('pwd', { inherit: true });
  1120. // /c/Program\ Files\ \(x86\)/Google/Chrome/Application/chrome.exe --user-data-dir=/c/chess/instances/elixir_01/data/Google/Chrome/User\ Data --profile-directory="chess"
  1121. // "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="C:\chess\instances\elixir_01\data\Google\Chrome\User Data" --profile-directory="chess" http://localhost:4200/admin/crud/create/item
  1122. // "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir="C:\chess\instances\elixir_01\data\Google\Chrome\User Data" --profile-directory="chess" http://localhost:4200/tests/index.html?grep=loopback
  1123. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1124. "--profile-directory=Profile 1"
  1125. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1126. }
  1127. // nodeShellExec('npm', ['init', '-y'], options);
  1128. // nodeShellExec('npm', ['init', '-y'], options);
  1129. // })
  1130. var g = {
  1131. 'client': () => {
  1132. console.info('Creating new ember client named : ' + processedArgs._[2]);
  1133. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1134. stdio: ['pipe', process.stdout, process.stderr],
  1135. inherit: true,
  1136. shell: true,
  1137. cwd: path.dirname(__dirname),
  1138. env: env
  1139. })
  1140. },
  1141. 'modelr': () => {
  1142. var tasks = [
  1143. () => {
  1144. var p = nodeShellExec('"ember"', [
  1145. 'g'
  1146. , 'modelr'
  1147. , processedArgs._[2]], {
  1148. inherit: true, shell: true, env: process.env
  1149. }).then(() => {
  1150. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  1151. return true;
  1152. }).catch((e) => { console.error(e) })
  1153. return p;
  1154. },
  1155. () => {
  1156. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1157. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  1158. chromeprefs = JSON.parse(chromeprefs)
  1159. var previous = chromeprefs.download.default_directory;
  1160. var parentDir = path.dirname(__dirname);
  1161. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1162. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1163. // PB : TODO -- detect where chrome is installed.
  1164. // PB : TODO -- set the download dir to the place where files are needed.
  1165. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1166. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1167. , '--profile-directory="chess"'
  1168. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1169. inherit: true, shell: true
  1170. , env: process.env
  1171. }).then(() => {
  1172. chromeprefs.download.default_directory = previous;
  1173. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1174. return true;
  1175. }).catch((e) => { console.error(e) })
  1176. return p;
  1177. }
  1178. ,
  1179. () => {
  1180. console.log('Browser process should have closed here....')
  1181. return true;
  1182. }
  1183. ]
  1184. any(tasks)
  1185. }
  1186. }
  1187. g[processedArgs._[1]]();
  1188. }
  1189. }
  1190. var util = require('util')
  1191. var cliname = 'elxr';
  1192. var ver = '1.1';
  1193. var help = `# list of commands... please refer dveloper documentation for ${cliname}
  1194. ${
  1195. // util.inspect(
  1196. [Object.keys(op)]
  1197. // )
  1198. }
  1199. `;
  1200. var elxr = {
  1201. help() {
  1202. return chalk.cyanBright(`
  1203. -------------------------------------------------------------------------------
  1204. *** BBH Elixir ***
  1205. -------------------------------------------------------------------------------
  1206. elxr ${ver}
  1207. A cli tool for chess
  1208. ${help}
  1209. -------------------------------------------------------------------------------
  1210. `)
  1211. }
  1212. , info() {
  1213. return chalk.cyanBright(`
  1214. -------------------------------------------------------------------------------
  1215. *** BBH Elixir ***
  1216. -------------------------------------------------------------------------------
  1217. elxr ${ver}
  1218. A cli tool for chess
  1219. -------------------------------------------------------------------------------
  1220. `)
  1221. }
  1222. , getpulltask(def){
  1223. def = def || {
  1224. requiresElevation : true,
  1225. reqularRepos : gitRepos,
  1226. elevatedRepos : elevatedRunasRepos
  1227. }
  1228. console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  1229. console.dir(def)
  1230. var env = Object.assign({}, process.env); // Shallow clone it.
  1231. console.log('Running exlr pull : ' + path.dirname(__dirname))
  1232. var useGitPull = processedArgs.useGitPull || false;
  1233. if(def.elevatedRepos || def.reqularRepos) {
  1234. if(def.elevatedRepos) def.requiresElevation = true;
  1235. else delete def.requiresElevation;
  1236. }
  1237. else {
  1238. if(def.requiresElevation) def.elevatedRepos = [def]
  1239. else def.reqularRepos = [def]
  1240. }
  1241. var elevatedpulltasks = null;
  1242. var regularpulltasks = function(){ return Promise.resolve(true) }
  1243. if(def.elevatedRepos){
  1244. elevatedpulltasks = function() {
  1245. return any(def.elevatedRepos.map((def) => performPull(def.repo))).then(() => {
  1246. // fs.writeFileSync('run.done', 'success')
  1247. return true;
  1248. }).catch((e) => {
  1249. console.error(e)
  1250. fs.writeFileSync('run.done', 'error')
  1251. })
  1252. }
  1253. }
  1254. if(def.reqularRepos) {
  1255. var regularpulltasks = function(){
  1256. var pendingpulls = [];
  1257. def.reqularRepos.forEach((def) => { pendingpulls.push(performPull(def.repo)) })
  1258. return Promise.all(pendingpulls).finally(Traq.finally)
  1259. }
  1260. }
  1261. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1262. else return getTaskWithoutElevation({ regularpulltasks})
  1263. }
  1264. }
  1265. // The main elxr cli process
  1266. function elxrworker() {
  1267. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  1268. gitRepos = repomanifest.repos
  1269. // gitRepos = ['chess-server-lib'];
  1270. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  1271. elevatedRunasRepos = repomanifest.elevated
  1272. // Repos that should excluded from merge for releases...
  1273. exludeMergeRepos = repomanifest.exludeMergeRepos
  1274. var env = Object.assign({}, process.env); // Shallow clone it.
  1275. var __runcmd = function (label) {
  1276. return op[label] ? op[label]() : null;
  1277. }
  1278. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  1279. // mysql -u root -p db_name < drop_all_tables.sql
  1280. var mysql = '../xampp/mysql/bin/mysql'
  1281. var mysqldump = '../xampp/mysql/bin/mysqldump'
  1282. // --runas
  1283. if (processedArgs.runas) {
  1284. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  1285. return __runcmd('runas')
  1286. }
  1287. else return __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  1288. }
  1289. var getManifest = function () {
  1290. // Once choices are made we need to load config according to those choices.
  1291. // No trace of a previous run...
  1292. // Default Config...
  1293. return repomanifest = selectedinstance;
  1294. }
  1295. function acquireChoices(selectedinstance) {
  1296. var hasconfig = false;
  1297. console.warn(chalk.yellow(`
  1298. -------------------------------------------------------------------------------
  1299. Warning : Cannot locate your preferred configuration since it was not specified
  1300. You should fork the default chess configuration to customize and make it
  1301. your own instance with a named config as
  1302. {{yourowninstancename}}-config-{{yourcurrentenvironment}}
  1303. And then run this tool as follows
  1304. NODE_ENV={{yourenvironment}} elxr i {{yourowninstancename}}
  1305. OR
  1306. Run this tool with the following command to use a quick start default.
  1307. node elxr --default
  1308. OR
  1309. Choose the the option to create a new instance for you interactively.
  1310. We will run your choice of default or create your own at the next prompt.
  1311. -------------------------------------------------------------------------------
  1312. `))
  1313. var prompt = cli.prompter;
  1314. return prompt.ask(`Choose an option :
  1315. d) Install the default chess instance.
  1316. => elxr i chess node_env=development --default
  1317. n) Create your custom new instance interactively
  1318. => elxr i {{instanceName}} node_env={{environment}}
  1319. i) Choose an instance and environment to install
  1320. => elxr i {{instanceName}} node_env={{environment}}
  1321. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  1322. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  1323. h) Help
  1324. q) Quit
  1325. Default <= d
  1326. : `).then((choice) => {
  1327. prompt.close();
  1328. if (choice && choice === 'd' || !choice) {
  1329. processedArgs._[0] = 'i'
  1330. selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  1331. selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  1332. selectedinstance.reposerver = 'https://git.bbh.org.in'
  1333. getManifest() // PB : TODO -- acquire the manifest directly from http url instead of clone before cloning the config. Since
  1334. // This is because the manifest at any server location can redirect to the preferred server..
  1335. }
  1336. else if (choice === 'h') {
  1337. processedArgs._[0] = 'h'
  1338. fs.writeFileSync('run.done', 'noop help');
  1339. console.log(elxr.help()); process.exit()
  1340. }
  1341. else if (choice === 'n' || choice === 'i') {
  1342. var p1 = cli.prompter;
  1343. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1344. processedArgs._[0] = 'i'
  1345. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  1346. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1347. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1348. if (choice === 'n') {
  1349. selectedinstance.reposerver = 'https://git.bbh.org.in'
  1350. console.warn(
  1351. chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  1352. process.exit();
  1353. }
  1354. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1355. p1.close()
  1356. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1357. })
  1358. })
  1359. })
  1360. } else if (choice === 'c') {
  1361. var p1 = cli.prompter;
  1362. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1363. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  1364. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1365. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1366. return p1.ask(`Enter cmd :
  1367. p) pull
  1368. Default <= p
  1369. : `).then(function (cmd) {
  1370. if (!cmd || cmd === 'p') {
  1371. processedArgs._[0] = 'pull'
  1372. }
  1373. else processedArgs._[0] = cmd
  1374. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1375. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1376. p1.close()
  1377. })
  1378. })
  1379. })
  1380. })
  1381. } else {
  1382. console.log(chalk.gray(`Default option not exercised. Please follow manual instructions to customize your instance here http://git.bbh.org.in/chess and try again.`));
  1383. fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  1384. fs.writeFileSync('run.done', 'noop quit');
  1385. process.exit()
  1386. }
  1387. })
  1388. }
  1389. var acquireConfig = function (selected, chessinstances) {
  1390. var configrepo = selected.instanceName + '-config-' + selected.node_env;
  1391. return performPull(configrepo).then(() => {
  1392. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  1393. repomanifest = require(manifestpath)()
  1394. chessinstances = chessinstances || {};
  1395. chessinstances[selected.instanceName] = chessinstances[selected.instanceName] || {}
  1396. chessinstances[selected.instanceName][selected.node_env] = chessinstances[selected.instanceName][selected.node_env] || {}
  1397. chessinstances['current_run'] = { instanceName: selected.instanceName, node_env: selected.node_env }
  1398. // Config from server always override merges into selection ecept for the current selection.
  1399. selectedinstance = utils.assign(chessinstances[selected.instanceName][selected.node_env], selected, repomanifest)
  1400. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  1401. // PB : TODO -- We should probably write the new server config also...
  1402. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  1403. ENV.NODE_ENV = selectedinstance.node_env;
  1404. })
  1405. .catch((e) => {
  1406. console.error(e)
  1407. console.error('Config acquisition failed.')
  1408. })
  1409. }
  1410. var launchpath = process.cwd().replace(/\\/, '/')
  1411. var thisscriptdir = __dirname
  1412. var instanceroot = launchpath;
  1413. var detectInstance = function () {
  1414. console.log(`launchpath = ${launchpath}`)
  1415. console.log(`thisscriptdir = ${thisscriptdir}`)
  1416. var root = launchpath;
  1417. // We need a reference to the root director for elxr cli to be properly oriented.
  1418. if ((launchpath + path.normalize('/elxr')) === thisscriptdir) {
  1419. // We ran unbuilt from the proper root with elxr subfolder.
  1420. console.log(`Instance Path : ${root}`)
  1421. }
  1422. else {
  1423. if (launchpath === thisscriptdir) {
  1424. // Same directory doesn't mean we are being run from elxr directory or the root directory.
  1425. // It could be a standalone elxr build which may or maynot be in the proper location.
  1426. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  1427. // Unbuilt therefore we are in the elxr directory.
  1428. root = path.normalize(launchpath + '/..');
  1429. }
  1430. else {
  1431. // Built version.
  1432. // check if we have a elxr subfolder.
  1433. if (fs.existsSync(launchpath + '/..' + path.normalize('/elxr'))) {
  1434. // Probably in the right place.
  1435. root = path.normalize(launchpath + '/..');
  1436. }
  1437. else {
  1438. // Assume launchpath is meaningless.
  1439. // Figure it out from the input instance name and environment parameters if we are in the right location.
  1440. root = path.normalize(launchpath + '/' + processedArgs._[1] + '/' + processedArgs.node_env)
  1441. }
  1442. }
  1443. }
  1444. }
  1445. instanceroot = root.replace(/\\/, '/');
  1446. __default.root = root;
  1447. return Promise.resolve(__default);
  1448. }
  1449. //
  1450. var __default = {
  1451. // Default is public server only.
  1452. // All public repos are by default available.
  1453. reposervers: ['https://git.bbh.org.in']
  1454. , repos: [
  1455. 'setup'
  1456. , 'elxr'
  1457. , 'loopback-connector-mysql'
  1458. , 'loopback-jsonapi-model-serializer'
  1459. , 'loopback-component-jsonapi'
  1460. , 'ember-service-worker'
  1461. , 'ember-service-worker-asset-cache'
  1462. , 'ember-service-worker-cache-fallback'
  1463. , 'ember-service-worker-index'
  1464. , 'ember-sw-client-route'
  1465. ]
  1466. , elevated: []
  1467. , exludeMergeRepos: {}
  1468. , instanceName: 'chess'
  1469. // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
  1470. , node_env: 'development'
  1471. }
  1472. var __interactve_promts = {
  1473. get reposerver(){
  1474. return cli.prompt(this.reposervers, 'git default repo').then(reposerver => {
  1475. Object.defineProperty(this, 'reposerver', {
  1476. value: reposerver,
  1477. writable: false,
  1478. configurable : true
  1479. });
  1480. return reposerver
  1481. })
  1482. }
  1483. , set reposerver(reposerver){
  1484. Object.defineProperty(this, 'reposerver', {
  1485. value: reposerver,
  1486. writable: false,
  1487. configurable : true
  1488. });
  1489. return reposerver
  1490. }
  1491. }
  1492. var downloadsdir = '../Downloads';
  1493. var prerequisites = [
  1494. {
  1495. shellcmd: 'git',
  1496. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  1497. , installer: 'Git-2.31.0-64-bit.exe'
  1498. , installcmd: ['cmd', ['/c', 'start',
  1499. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  1500. , '/VERYSILENT'
  1501. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  1502. ]]
  1503. , preinstallsteps: function() {
  1504. var prompt = cli.prompter;
  1505. var steps = [
  1506. () => {
  1507. if (!existsSync(downloadsdir + '/' + this.installer)) {
  1508. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  1509. }
  1510. else return Promise.resolve(true)
  1511. }
  1512. ]
  1513. var prompts = [
  1514. () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
  1515. , () => prompt.ask(`git email : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
  1516. ]
  1517. return any([any(steps), any(prompts)]).then(() => { prompt.close() })
  1518. }
  1519. , installsteps: function () {
  1520. return any([this.installcmd].map(callsheltask))
  1521. }
  1522. , postinstallsteps: function(){
  1523. var prompt = cli.prompter;
  1524. var gitUser = 'guest';
  1525. var gitEmail = 'guest@bbh.org.in';
  1526. var prompts = [];
  1527. prompts.push(
  1528. ()=>{
  1529. var choices = { 0 : 'guest', 1 : 'chessdemo' }
  1530. return cli.prompt(choices, 'git user name').then(gituser => gitUser = gituser)
  1531. }
  1532. )
  1533. prompts.push(
  1534. ()=>{
  1535. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  1536. return cli.prompt(choices, 'git user email').then(gitemail => gitEmail = gitemail)
  1537. }
  1538. )
  1539. return any(prompts).then(()=>{
  1540. var steps = [
  1541. ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  1542. , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  1543. ]
  1544. return any(steps.map(callsheltask)).then(() => {
  1545. })
  1546. });
  1547. }
  1548. , install: function () {
  1549. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  1550. }
  1551. , verifyAndInstall : function(){
  1552. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  1553. if(exists) {
  1554. // return any(['git', ['config', '--global', '-l']].map(callsheltask))
  1555. return this.getUser(null, this.postinstallsteps.bind(this))
  1556. }
  1557. return this.install();
  1558. });
  1559. }
  1560. , getUser : function(repo, onNoResult){
  1561. onNoResult = onNoResult || function(){return false}
  1562. var globalOrLocal = '--global';
  1563. if(!repo) globalOrLocal = '--global';
  1564. else globalOrLocal = '--local'
  1565. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(callsheltask)).then((result)=>{
  1566. // not yet configured.
  1567. if(!result.success) return onNoResult()
  1568. else {
  1569. var users = result.messages[0].trim().split('\n');
  1570. if(users.length === 0 ||
  1571. users.length === 1 && users[0] === 'guest') {
  1572. return onNoResult()
  1573. }
  1574. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  1575. }
  1576. })
  1577. .catch((e)=>{
  1578. console.log(e)
  1579. return onNoResult()
  1580. })
  1581. }
  1582. }
  1583. ,
  1584. {
  1585. shellcmd: 'node',
  1586. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  1587. , installer: 'node-v14.16.0-x64.msi'
  1588. , installcmd: ['MSIEXEC.exe', ['/i'
  1589. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  1590. , 'ACCEPT=YES', '/passive']]
  1591. , install : function() { return any([this.installcmd].map(callsheltask)).then(() => { }) }
  1592. }
  1593. ]
  1594. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  1595. function ensureDirectoryExistence(filePath) {
  1596. var dirname = path.dirname(filePath);
  1597. if (fs.existsSync(dirname)) {
  1598. return filePath;
  1599. }
  1600. ensureDirectoryExistence(dirname);
  1601. fs.mkdirSync(dirname);
  1602. return filePath;
  1603. }
  1604. var mainTasks = [];
  1605. function verifyAndInstallPrerequisites() {
  1606. fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
  1607. // PB : TODO include and build from files... using rollup..
  1608. var downloadbatch =
  1609. `::**************************************************************************
  1610. :Download_ <url> <File>
  1611. Powershell.exe ^
  1612. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  1613. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  1614. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  1615. exit /b
  1616. ::**************************************************************************`
  1617. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch)
  1618. var windowselevate =
  1619. `
  1620. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  1621. <script language="vbscript">
  1622. document.title = "elxr control panel"
  1623. self.ResizeTo 200,600
  1624. Sub Window_Onload
  1625. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  1626. End Sub
  1627. Set objShell = CreateObject("WScript.Shell")
  1628. Set objENV = objShell.Environment("Process")
  1629. dim NODE_ENV
  1630. NODE_ENV = objENV("NODE_ENV")
  1631. </script>
  1632. <script language="javascript">
  1633. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  1634. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  1635. // alert(windowselevate.commandLine)
  1636. var args = windowselevate.commandLine.split('"').slice(3);
  1637. // alert(args)
  1638. var processedArgs = { _ : [] }
  1639. var namedArgs = [];
  1640. for(var item in args){
  1641. if(args[item].charAt(0) === '-'){
  1642. namedArgs.push(args[item])
  1643. var split = args[item].split('=');
  1644. processedArgs[split[0].slice(2)] = split[1] || true;
  1645. }
  1646. else processedArgs._.push(args[item]);
  1647. }
  1648. // args = args.forEach(function(item){ })
  1649. // alert('processedArgs._ : ' + processedArgs._);
  1650. // alert(processedArgs.runas);
  1651. // PB : TODO -- Convert all the cli args back to string.
  1652. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  1653. // alert(cargs)
  1654. var shell = new ActiveXObject('shell.application');
  1655. // alert('launching node privilged. ' + processedArgs['nodepath'])
  1656. // shell.ShellExecute('where', 'node', '', '', 10);
  1657. shell.ShellExecute('node', cargs, '', 'runas', 1);
  1658. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  1659. var fso = new ActiveXObject('Scripting.FileSystemObject');
  1660. window.onload = function() {
  1661. document.body.style.backgroundColor = 'black';
  1662. document.body.style.fontFamily = 'arial';
  1663. var log = document.createElement('div');
  1664. log.innerHTML='Please Wait';
  1665. function l(msg){ log.innerHTML+= msg; };
  1666. log.style.color = 'blue';
  1667. log.style.width = '95%';
  1668. log.id = 'log';
  1669. document.body.appendChild(log);
  1670. l('<Br/>Current config : ')
  1671. l('<Br/>NODE_ENV = ' + NODE_ENV)
  1672. l('<Br/>cmd = ' + processedArgs._[0])
  1673. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  1674. l('<Br/><Br/>')
  1675. var timer = function(){
  1676. l('.');
  1677. if(fso.FileExists("run.done")) close();
  1678. else window.setTimeout(timer, 1000);
  1679. };
  1680. window.setTimeout(timer, 3000);
  1681. };
  1682. </script>
  1683. </html>
  1684. `
  1685. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate)
  1686. var downloadtasks = [];
  1687. var installtasks = [];
  1688. prerequisites.forEach(preq => {
  1689. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  1690. if (exists) console.log(`${preq.shellcmd} exists`)
  1691. else {
  1692. console.log(`${preq.shellcmd} is not installed`)
  1693. return preq.preinstallsteps.call(preq).then(() => {
  1694. installtasks.push(preq.install.bind(preq))
  1695. })
  1696. }
  1697. }))
  1698. })
  1699. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  1700. }
  1701. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  1702. var selectedinstance = null;
  1703. var chessinstances = { current_run : {} };
  1704. acquireElevationState().then(() => {
  1705. var skipprerequisites = false;
  1706. var clioverrides = { }
  1707. function initinstances(chessinstances, selected) {
  1708. chessinstances.current_run.instanceName = processedArgs._[1] = processedArgs._[1] || chessinstances.current_run.instanceName || selected.instanceName;
  1709. chessinstances.current_run.node_env = processedArgs.node_env = processedArgs.node_env || chessinstances.current_run.node_env || selected.node_env;
  1710. chessinstances[chessinstances.current_run.instanceName] = chessinstances[chessinstances.current_run.instanceName] || {}
  1711. // Override sequence.
  1712. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  1713. selectedinstance = Object.assign(
  1714. selected
  1715. , chessinstances[chessinstances.current_run.instanceName][chessinstances.current_run.node_env]
  1716. , clioverrides
  1717. // , __interactve_promts -- Cant just override. Also need selectedinstance to be ready...
  1718. );
  1719. repomanifest = selectedinstance
  1720. return chessinstances
  1721. }
  1722. function acquirelocalinstances(selected){
  1723. var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
  1724. return chessinstances
  1725. }
  1726. var noprerequisites = {
  1727. add : true
  1728. }
  1729. var skipprereqs = {}
  1730. var maintask = () => {
  1731. // Default cmd to run !
  1732. processedArgs._[0] === processedArgs._[0] || 'pull';
  1733. // selectedinstance.reposerver = repomanifest.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available...
  1734. if(!noprerequisites[processedArgs._[0]]
  1735. && !skipprereqs[processedArgs._[0]]
  1736. ) {
  1737. return prerequisites.git.verifyAndInstall().then(()=>{
  1738. var e = { message : 'verifyAndInstall', success : true}
  1739. return acquireConfig(selectedinstance, chessinstances).catch((err) => {
  1740. e = err;
  1741. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  1742. console.error(err)
  1743. }).then(() => { return elxrworker(true) })
  1744. // .finally(()=>{
  1745. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  1746. // if(!e.success) fs.writeFileSync('run.done', 'error');
  1747. // // return process.exit()
  1748. // })
  1749. })
  1750. }
  1751. else {
  1752. console.log('cmd has no preqs or has been configured to skip preqs')
  1753. return elxrworker()
  1754. }
  1755. }
  1756. const retaincount = 2
  1757. var min = runtimestamp;
  1758. var collect = []
  1759. return detectInstance().then((detectedInstance)=>{
  1760. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  1761. processedArgs.node_env ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env
  1762. : (process.env.NODE_ENV && process.env.NODE_ENV.trim()) ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()): null;
  1763. selectedinstance = Object.assign(detectedInstance, clioverrides);
  1764. var todo = Promise.resolve(true);
  1765. try {
  1766. chessinstances = acquirelocalinstances(selectedinstance);
  1767. initinstances(chessinstances, selectedinstance)
  1768. }
  1769. catch (e) {
  1770. console.error(e)
  1771. // No local instances config found. We acquire user choices and proceed to reattempt.
  1772. initinstances(chessinstances, selectedinstance)
  1773. var prompts = [];
  1774. Object.keys(__interactve_promts).forEach(k => {
  1775. if(!selectedinstance[k]) {
  1776. prompts.push(async ()=>{
  1777. Object.defineProperty(selectedinstance, k, Object.getOwnPropertyDescriptor(__interactve_promts, k));
  1778. return await selectedinstance[k]
  1779. })
  1780. }
  1781. })
  1782. todo = any(prompts).then(()=>{ return selectedinstance })
  1783. if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  1784. // Weve been told what to do.
  1785. todo = acquireChoices(selectedinstance)
  1786. }
  1787. todo = todo.then(() => {
  1788. try {
  1789. chessinstances = acquirelocalinstances(selectedinstance)
  1790. initinstances(chessinstances, selectedinstance)
  1791. }
  1792. catch (e) {
  1793. console.error(e)
  1794. console.log('No local instances config found in current root = ' + selectedinstance.root);
  1795. console.log('A config will be createed with the instance and environment chosen...')
  1796. // return (async ()=>{return await __default.reposerver})().then(()=>{
  1797. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  1798. // return selectedinstance = Object.assign(__default, selectedinstance);
  1799. // })
  1800. return selectedinstance
  1801. }
  1802. })
  1803. }
  1804. return todo
  1805. })
  1806. .then(()=>{
  1807. if(!__isElevated) {
  1808. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/readme.txt`)
  1809. // collect garbage
  1810. return dirs( (dir)=>{
  1811. var matches = /run-(.*)/gm.exec(dir.name)
  1812. if(matches) {
  1813. if(+(matches[1]) < min) {
  1814. min = matches[1]
  1815. collect.splice( 0, 0, matches[1] )
  1816. }
  1817. else collect.push(matches[1])
  1818. }
  1819. }, `${selectedinstance.root}/.elxr` ).then(()=>{
  1820. // delete garbage
  1821. if(collect.length > retaincount) {
  1822. var asyncs = [];
  1823. while((collect.length - asyncs.length) > retaincount) {
  1824. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  1825. }
  1826. return Promise.all(asyncs)
  1827. }
  1828. else return true
  1829. })
  1830. }
  1831. else return true;
  1832. })
  1833. .then(()=>{
  1834. // PB : TODO -- Keep only the last n runs...
  1835. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  1836. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
  1837. if (!skipprerequisites && !__isElevated) mainTasks.push(verifyAndInstallPrerequisites);
  1838. mainTasks.push(maintask)
  1839. return any(mainTasks);
  1840. })
  1841. })
  1842. // detect if alread installed -> Take no action.
  1843. // download if no installer avalable -> next()
  1844. // install
  1845. function chackandinstall(items) {
  1846. var tasks = []
  1847. items.forEach(item => {
  1848. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  1849. })
  1850. return Promise.all(tasks).then(existances => {
  1851. existances.forEach((exists, i) => {
  1852. if (!exists) {
  1853. return downloadandinstall([items[i]])
  1854. }
  1855. })
  1856. })
  1857. }
  1858. function downloadandinstall(items) {
  1859. var tasks = []
  1860. items.forEach(item => {
  1861. tasks.push(getTaskDownload(item))
  1862. })
  1863. return Promise.all(tasks)
  1864. }
  1865. // Sample instances config.
  1866. // var instances = {
  1867. // "elixir": {
  1868. // "production": {
  1869. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  1870. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  1871. // , "exludeMergeRepos": {
  1872. // "elixir-config-development": true, "elixir-config-test": true
  1873. // , "elixir-config-production": true, "elixir-data": true
  1874. // }
  1875. // , "instanceName": "elixir", "node_env": "production"
  1876. // }
  1877. // },
  1878. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  1879. // }
  1880. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...