555
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
4 年之前
4 年之前
3 年之前
3 年之前
5 年之前
6 年之前
3 年之前
3 年之前
3 年之前
6 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
4 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
5 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
5 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
6 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
3 年之前
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905
  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 __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b'
  12. const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  13. const runtimestamp = (new Date()).getTime();
  14. function getVersion() { return BUILD_VERSION; }
  15. console.log(getVersion());
  16. // 'use strict';
  17. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  18. // PB : TODO --
  19. // runas bypass non elevated tasks when we request privelege
  20. // runas message is always error needs to be fixed.
  21. // runas wait needs to be parallelized.
  22. // suppress elevation check error messages
  23. // support runas lauched directly from shell.
  24. // pass in environment in hta to shellexecute.
  25. // PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
  26. (function () {
  27. "use strict";
  28. if (!Array.prototype.earlyreduce) {
  29. Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
  30. var iterable = this;
  31. var donecallback = donecallback || (a=>a)
  32. var result = { value : initialValue === undefined ? iterable[0] : initialValue };
  33. initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
  34. // function *earlyReduceGenerator(acc, v, i, a) {
  35. for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
  36. var element = iterable[i]
  37. result = eachcallback(result, element, i, iterable)
  38. if(result.done) return donecallback(result)
  39. }
  40. // }
  41. return donecallback(result)
  42. }
  43. }
  44. }());
  45. const { existsSync } = require('fs');
  46. const existsFolderSync = existsSync;
  47. const fs = require('fs')
  48. const cliargs = utils.cliargs;
  49. const processedArgs = cliargs(process.argv.slice(2));
  50. console.dir(processedArgs)
  51. // PB : TODO -- defaults for valuless arguments if passed.
  52. // Object.keys(processedArgs).forEach(a=>{
  53. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  54. // }
  55. // })
  56. var clioverrides = { }
  57. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  58. processedArgs.node_env ? clioverrides.node_env = processedArgs.node_env
  59. : (process.env.NODE_ENV && process.env.NODE_ENV.trim())
  60. ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) : null;
  61. Object.keys(clioverrides).forEach( prop => { })
  62. var globSync = require('glob').sync;
  63. var ENV = Object.assign({}, process.env); // Shallow clone it.
  64. const { readdir } = require("fs").promises
  65. // Directory shallow walk and do perform on each dir.
  66. const dirs = async (perform, path) => {
  67. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  68. if (dir.isDirectory()) perform(dir)
  69. }
  70. }
  71. var getShellTask = (command, args, options) => {
  72. options = options || {}
  73. var callshell = command === 'rm' ? callgitbashtask : callsheltask;
  74. return () => {
  75. var p = callshell( [command, args, Object.assign({
  76. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  77. }, options)
  78. ])
  79. if (options.ignorefailures) {
  80. return p.catch(e => {
  81. // Ignore. Not a major error.
  82. })
  83. }
  84. else return p;
  85. }
  86. }
  87. var callsheltask = (args) => {
  88. return args[0] === 'rm' ? callgitbashtask(args) : () => { return nodeShellExec.apply(null, args) } }
  89. var callgitbashtask = (args) => { return () => {
  90. return nodeShellExec( `"${gitbash}"`, ['-c', `"${args[0]} ${args[1].join(' ')}"`], args[2]) }
  91. }
  92. var getTaskCheckExists = (command, options) => {
  93. options = options || {}
  94. return () => {
  95. var p = nodeShellExec.apply(null, ['where', [command]])
  96. if (options.ignorefailures) {
  97. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  98. return false;
  99. })
  100. }
  101. else return p.then(() => { return true });
  102. }
  103. }
  104. var getTaskWithElevation = function(tasdef){
  105. return ()=>{
  106. if (__isElevated) {
  107. return tasdef.elevatedpulltasks().then(()=>{
  108. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  109. fs.writeFileSync('run.done', 'success')
  110. }).catch(e=>{
  111. fs.writeFileSync('run.done', 'failure')
  112. });
  113. }
  114. else {
  115. // PB : TODO -- Rename op['runas'] to 'elevate'
  116. var __runasresult = null;
  117. return op['runas']().then((r) => { return __runasresult = r; })
  118. .catch((e) => {
  119. console.error(e)
  120. })
  121. .finally(() => {
  122. if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done')
  123. if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
  124. })
  125. }
  126. }
  127. }
  128. var getTaskWithoutElevation = function(tasdef){
  129. return ()=>{
  130. if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  131. else Promise.resolve(true)
  132. }
  133. }
  134. var gitops = {
  135. getdiscoverbranchcmd : function(repo){
  136. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  137. var cmd = [gitbash
  138. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  139. , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo + ' ' + parameters.join(' ') }]
  140. return cmd
  141. }
  142. }
  143. var getPullCmd = (repo, branch) => {
  144. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  145. // console.log(useGitPull)
  146. // var pullCmd = [gitInstallDir
  147. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  148. // , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo }]
  149. if(branch) {
  150. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  151. var pullCmd = [ gitbash
  152. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  153. , { cwd: instanceroot + '/' + repo, title : 'pull all origins for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  154. }
  155. else {
  156. // console.warn('No branch was specified detecting from working client.')
  157. // First check if working client exits.
  158. // if (existsSync(instanceroot + '/' + repo)) {
  159. var pullCmd = gitops.getdiscoverbranchcmd(repo)
  160. // }
  161. // else performpull
  162. }
  163. // var pullCmd = ['pullall', [], { cwd : repo }]
  164. if (useGitPull) pullCmd = ['git', ['pull'], {
  165. inherit: true, shell: true,
  166. cwd: instanceroot + '/' + repo
  167. // , env: process.env
  168. , runas: processedArgs.runas
  169. , title: `git pull ${repo}`
  170. }]
  171. return pullCmd
  172. }
  173. var performPull = (repo, branch) => {
  174. // PB : TODO -- Handle no branch passed in case.
  175. // if(!branch) { throw 'No branch specified' }
  176. if (existsSync(instanceroot + '/' + repo)) {
  177. var branchprint = branch ? ' branch :' + branch : '';
  178. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  179. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  180. if (__isElevated) {
  181. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  182. }
  183. else statuslog.statuslog(null, repo)
  184. return true;
  185. })
  186. .catch((e) => {
  187. e.repo = repo;
  188. if (__isElevated) {
  189. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  190. }
  191. else statuslog.statuslog(e); console.error(e)
  192. })
  193. }
  194. else {
  195. console.log('cloning ' + repo)
  196. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  197. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'],
  198. {
  199. inherit: true, shell: true,
  200. env: process.env
  201. , cwd : instanceroot
  202. , runas: processedArgs.runas
  203. }).catch((e) => {
  204. throw e;
  205. }).then(() => {
  206. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  207. {
  208. inherit: true, shell: true,
  209. env: process.env
  210. , cwd: instanceroot + '/' + repo
  211. , runas: processedArgs.runas
  212. , title: `git core.symlinks --replace-all true for ${selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'}`
  213. })
  214. .then(() => {
  215. if (__isElevated) {
  216. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  217. }
  218. else statuslog.statuslog(null, repo)
  219. })
  220. .catch((e) => {
  221. e.repo = repo;
  222. if (__isElevated) {
  223. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  224. }
  225. else statuslog.statuslog(e);
  226. })
  227. })
  228. .catch(e => {
  229. e.repo = repo;
  230. if (__isElevated) {
  231. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  232. }
  233. else statuslog.statuslog(e);
  234. })
  235. }
  236. }
  237. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  238. // -- Currently workaround is to always run from a non-elevated shell.
  239. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  240. var acquireElevationState = () => {
  241. if (__isElevated === null) {
  242. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  243. inherit: true
  244. // , shell: true
  245. , stdio: 'ignore'
  246. , env: process.env
  247. , title: `check privileged execution mode using "fsutil dirty query C:"`
  248. }).then((exitcode) => {
  249. console.log('Elevated')
  250. __isElevated = true;
  251. return true;
  252. }).catch(() => {
  253. __isElevated = false;
  254. console.log('Not Elevated');
  255. return false;
  256. });
  257. }
  258. else return Promise.resolve(__isElevated);
  259. }
  260. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current gittea username
  261. var defaultRepoOwner = 'chess';
  262. var elevatedRunasRepos = null
  263. var gitRepos = null
  264. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  265. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  266. var dbForLabel = function (label) {
  267. var dbsForLabel = {
  268. devmysql: 'mysql'
  269. , development: 'mssql'
  270. , production: 'mssql'
  271. }
  272. return dbsForLabel[label] || 'mysql'
  273. }
  274. // SAM : TODO Use nodeshellexec where to detect git installation dir
  275. var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe"
  276. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  277. // Relevant git repos
  278. var exludeMergeRepos = [];
  279. var useGitPull = processedArgs.useGitPull || false;
  280. var configPromise = null
  281. // elxr cli operations
  282. var op = {
  283. 'h': () => { console.log(elxr.help()); return '-h' }
  284. , 'clean' : () => {
  285. // delete all node_module folders and links.
  286. var tasklist = [];
  287. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot )
  288. return Promise.all(tasklist)
  289. }
  290. , 'undefined': () => { return op.h(); }
  291. , 'reset': () => {
  292. // Reset NPM packages semver so major versions can be updated.
  293. const fs = require('fs')
  294. const wipeDependencies = (__package) => {
  295. const file = fs.readFileSync(__package + '/package.json')
  296. const content = JSON.parse(file)
  297. for (var devDep in content.devDependencies) {
  298. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  299. content.devDependencies[devDep] = '*';
  300. }
  301. }
  302. for (var dep in content.dependencies) {
  303. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  304. content.dependencies[dep] = '*';
  305. }
  306. }
  307. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  308. }
  309. var repos = ['client'];
  310. // repos = gitRepos;
  311. repos.forEach(wipeDependencies)
  312. // if (require.main === module) {
  313. // } else {
  314. // module.exports = wipeDependencies
  315. // }
  316. }
  317. , 'upgrade': () => {
  318. console.log('upgrade.......')
  319. var tasks = [
  320. () => {
  321. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  322. inherit: true, shell: true
  323. , env: process.env
  324. }).catch((e) => { console.error(e) })
  325. p.position = 1;
  326. console.log('One')
  327. return p;
  328. }
  329. , () => {
  330. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  331. inherit: true, shell: true
  332. , env: process.env
  333. }).catch((e) => { console.error(e) })
  334. p.position = 2;
  335. console.log('Two')
  336. return p;
  337. }
  338. , () => {
  339. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  340. inherit: true, shell: true
  341. , env: process.env
  342. }).catch((e) => { console.error(e) })
  343. p.position = 3;
  344. console.log('Three')
  345. return p;
  346. }
  347. , () => {
  348. var p = nodeShellExec('n', ['latest'], {
  349. inherit: true, shell: true
  350. , env: process.env
  351. }).catch((e) => { console.error(e) })
  352. p.position = 4;
  353. console.log('Four')
  354. return p;
  355. }
  356. ]
  357. any(tasks)
  358. console.log('.......done')
  359. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  360. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  361. console.info('Uninstalling existing ember globally');
  362. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  363. stdio: ['pipe', process.stdout, process.stderr],
  364. inherit: true,
  365. shell: true,
  366. cwd: path.dirname(__dirname),
  367. env: env
  368. })
  369. step1.on('close', () => {
  370. console.info('Installing ember globally');
  371. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  372. stdio: ['pipe', process.stdout, process.stderr],
  373. inherit: true,
  374. shell: true,
  375. cwd: path.dirname(__dirname),
  376. env: env
  377. })
  378. step2.on('close', () => {
  379. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  380. stdio: ['pipe', process.stdout, process.stderr],
  381. inherit: true,
  382. shell: true,
  383. cwd: path.dirname(__dirname),
  384. env: env
  385. })
  386. })
  387. })
  388. }
  389. , 'runas': () => {
  390. if(processedArgs.skipelevated) return Promise.resolve({ skipped : true });
  391. console.log('Testing Elevation')
  392. if (__isElevated) {
  393. try {
  394. op[processedArgs.label || processedArgs._[0] || 'h']()
  395. }
  396. catch (e) {
  397. console.error('Error Invalid command : ' + e)
  398. fs.writeFileSync('run.done', 'error')
  399. }
  400. finally {
  401. }
  402. }
  403. else {
  404. console.log('Requesting Elevated Privileges');
  405. // Wait for the runas to complete before we read it.
  406. try {
  407. fs.unlinkSync('run.done')
  408. fs.unlinkSync('run.log')
  409. }
  410. catch (e) { } //Ignore
  411. // Find node path to send to hta.
  412. return nodeShellExec('where', ['node']).then(r => {
  413. var namedArgs = [];
  414. console.log('result : ' + JSON.stringify(r))
  415. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; })
  416. // PB : TODO -- Convert all the cli args back to string.
  417. var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  418. // args.push('--nodepath=' + r.messages[r.messages.length - 1])
  419. // if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
  420. // if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
  421. console.dir(processedArgs)
  422. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  423. , {
  424. inherit: true
  425. , shell: true
  426. , env: ENV
  427. , runas: 'self'
  428. , title: `runas`
  429. }
  430. ).then(() => {
  431. // runas returned.
  432. try {
  433. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  434. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  435. runaslog.forEach((logEntry) => {
  436. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry)
  437. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  438. })
  439. }
  440. catch (e) {
  441. // We must have a runas log
  442. statuslog.statuslog(e)
  443. console.error('Run log error probably was not created by runas : ' + e)
  444. }
  445. })
  446. .catch(err => console.error('Elevation failed : ' + err));
  447. })
  448. }
  449. }
  450. , 'push': () => {
  451. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  452. // init remote bare from local
  453. // pushandinitremotebare
  454. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  455. // connect to repo server -- net use 172.16.0.27
  456. // cd 172.16.0.27/repos/
  457. // mkdir repo.git
  458. // cd repo.git
  459. // git init --bare
  460. // cd localrepo
  461. // git remote rename origin githubclone
  462. // git remote add origin //172.16.0.27/repos/repo.git
  463. // git push origin master
  464. var repo = processedArgs._[1];
  465. var sequentialTaskShellCommands = [];
  466. if (!existsSync(`Z:/${repo}.git`)) {
  467. sequentialTaskShellCommands = [
  468. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  469. // inherit : true, shell: true
  470. // , env: process.env
  471. // }]
  472. ['pwd', { cwd: 'Z:', inherit: true }]
  473. , ['mkdir', [`${repo}.git`], {
  474. cwd: `Z:`
  475. , inherit: true, shell: true
  476. , env: process.env
  477. }]
  478. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  479. , ['git', ['init', '--bare'], {
  480. cwd: `Z:/${repo}.git`
  481. , inherit: true, shell: true
  482. , env: process.env
  483. }]
  484. // PB : TODO -- Do this conditionally only...
  485. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  486. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  487. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  488. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  489. // PB : TODO -- If threre is a gitbubclone origin
  490. // Set the master to pull from the local repo.
  491. ]
  492. if (!existsSync(`Z:`)) {
  493. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  494. inherit: true, shell: true
  495. , env: process.env
  496. }])
  497. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  498. // throw 'done'
  499. }
  500. }
  501. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }])
  502. // console.dir(sequentialTaskShellCommands);
  503. var tasks = [];
  504. sequentialTaskShellCommands.forEach(shellcmd => {
  505. // console.log(shellcmd)
  506. tasks.push(() => {
  507. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
  508. return p;
  509. })
  510. })
  511. any(tasks);
  512. }
  513. , 'is-git-repo': (dir) => {
  514. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  515. }
  516. // git remote equivalents...
  517. // git branch --set-upstream-to=elixir-unc/master master
  518. // git push --set-upstream elixir-unc branch..
  519. , 'remote': (args) => {
  520. // Subcommands!
  521. if(!processedArgs.v) return false; // Only -v is supported presently..
  522. var serial_perform = (repo) => {
  523. var options = { cwd: instanceroot + '/' + repo }
  524. return [
  525. ['git', ['remote', '-v'], options]
  526. ]
  527. }
  528. var x = (args) => {
  529. var tasq = () => {
  530. // console.log(args)
  531. return nodeShellExec.apply(null, args).catch(e => {
  532. // We continue on failure.
  533. console.error(tasq.toString())
  534. })
  535. }
  536. tasq.toString = function(){
  537. return JSON.stringify(args)
  538. }
  539. return tasq;
  540. }
  541. var perform = (dir) => {
  542. return any(serial_perform(dir.name).map(x))
  543. }
  544. dirs(perform)
  545. }
  546. , 'remote set-url': (args) => {
  547. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  548. var __args = {
  549. remotename : args.remotename || processedArgs._[2]
  550. , url : args.url || processedArgs._[3]
  551. }
  552. // pushable doesn't mean the remote doesn't support being pushed to.
  553. // Over here it just means we are disabling pushing to that remote by setting the push portion of the url the a junk remote called no-pushing.
  554. // PB : TODO -- change this to enablepushing.
  555. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  556. var pushable = processedArgs.pushable || false;
  557. remotename = __args.remotename
  558. url = __args.url
  559. var serial_perform_git_seturl = (repo) => {
  560. var options = { cwd: instanceroot + '/' + repo }
  561. // console.log(repo)
  562. if (pushable) {
  563. return [
  564. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  565. , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  566. ]
  567. }
  568. else {
  569. return [
  570. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  571. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  572. ]
  573. }
  574. }
  575. var x = (args) => {
  576. var tasq = () => {
  577. // console.log(args)
  578. return nodeShellExec.apply(null, args).catch(e => {
  579. // We continue on failure.
  580. console.error(tasq.toString())
  581. })
  582. }
  583. tasq.toString = function(){
  584. return JSON.stringify(args)
  585. }
  586. return tasq;
  587. }
  588. var perform_git_seturl = (dir) => {
  589. op['is-git-repo'](dir).then((logEntry) => {
  590. return any(serial_perform_git_seturl(dir.name).map(x))
  591. }).catch((e) => {
  592. // console.log('Failed : ' + dir.name)
  593. })
  594. }
  595. dirs(perform_git_seturl)
  596. }
  597. , 'reset' : ()=>{
  598. // Reset the whole installation pertaining to this elxr folder.
  599. }
  600. , 'remote add': (args) => {
  601. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  602. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  603. // That explicitly has a remote name prefix.
  604. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  605. // git branch branch_name -u your_new_remote/branch_name -- older versions
  606. // git branch -vv -- Detect which branch are we tracking.
  607. // default upstream should be users own fork.
  608. // Also need alias branches to
  609. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  610. // probably git merge from all remotes... and relevant branches...
  611. // alias pushall='for i in `git remote`; do git push $i; done;'
  612. // alias pullall='for i in `git remote`; do git pull $i; done;'
  613. // args === processedArgs ? args = {} : null;
  614. var __args = {
  615. remotename : args.remotename|| processedArgs._[2]
  616. , url : args.url || processedArgs._[3]
  617. , branch : args.branch || processedArgs._[4]
  618. }
  619. var remotename = __args.remotename
  620. var url = __args.url
  621. var branch = __args.branch
  622. var pushable = processedArgs.pushable || false;
  623. var serial_perform_git_add = (repo) => {
  624. var options = { cwd: instanceroot + '/' + repo }
  625. // console.log(repo)
  626. if (pushable) {
  627. return [
  628. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  629. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  630. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  631. ]
  632. }
  633. else {
  634. return [
  635. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  636. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  637. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  638. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  639. ]
  640. }
  641. }
  642. var x = (args) => {
  643. return () => {
  644. // console.log(args)
  645. return nodeShellExec.apply(null, args)
  646. }
  647. // return Promise.resolve(true)
  648. }
  649. var perform_git_add = (dir) => {
  650. op['is-git-repo'](dir).then((logEntry) => {
  651. // console.log(code)
  652. if (logEntry.success) {
  653. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  654. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  655. })
  656. .catch((e) => {
  657. any(serial_perform_git_add(dir.name).map(x))
  658. })
  659. }
  660. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  661. }).catch((e) => {
  662. console.log('Failed : ' + dir.name)
  663. })
  664. }
  665. const { readdir } = require("fs").promises
  666. dirs(perform_git_add)
  667. }
  668. , 'remote remove': (args) => {
  669. var __args = {
  670. remotename : args.remotename|| processedArgs._[2]
  671. }
  672. var remotename = __args.remotename
  673. var serial_perform_git_remove = (repo) => {
  674. var options = { cwd: instanceroot + '/' + repo }
  675. // console.log(repo)
  676. return [
  677. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  678. ]
  679. }
  680. var x = (args) => {
  681. return () => {
  682. // console.log(args)
  683. return nodeShellExec.apply(null, args)
  684. }
  685. // return Promise.resolve(true)
  686. }
  687. var perform_git_remove = (dir) => {
  688. op['is-git-repo'](dir).then((logEntry) => {
  689. // console.log(code)
  690. if (logEntry.success) {
  691. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  692. any(serial_perform_git_remove(dir.name).map(x))
  693. })
  694. .catch((e) => {
  695. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`)
  696. })
  697. }
  698. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  699. }).catch((e) => {
  700. // console.log('Failed : ' + dir.name)
  701. })
  702. }
  703. const { readdir } = require("fs").promises
  704. dirs(perform_git_remove)
  705. }
  706. , 'init-gitea': (user) => {
  707. user = user || processedArgs._[1]
  708. if (!user) throw 'User name required'
  709. var serial_perform_init_gitea = (repo) => {
  710. var options = { cwd: instanceroot + '/' + repo }
  711. // console.log(repo)
  712. return [
  713. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  714. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  715. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  716. ]
  717. }
  718. var x = (args) => {
  719. return () => {
  720. // console.log(args)
  721. return nodeShellExec.apply(null, args)
  722. }
  723. // return Promise.resolve(true)
  724. }
  725. var perform_init_gitea = (dir) => {
  726. op['is-git-repo'](dir).then((logEntry) => {
  727. // console.log(code)
  728. if (logEntry.success) {
  729. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  730. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  731. })
  732. .catch((e) => {
  733. any(serial_perform_init_gitea(dir.name).map(x))
  734. })
  735. }
  736. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  737. }).catch((e) => {
  738. // console.log('Failed : ' + dir.name)
  739. })
  740. }
  741. const { readdir } = require("fs").promises
  742. dirs(perform_init_gitea)
  743. }
  744. , 'syncmaster': (label) => {
  745. // Usage :
  746. // elxr pull -- Defaults to run config
  747. var env = Object.assign({}, process.env); // Shallow clone it.
  748. // console.dir(env)
  749. console.log('Running exlr pull : ' + path.dirname(__dirname))
  750. if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'))
  751. if (__isElevated) {
  752. return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
  753. fs.writeFileSync('run.done', 'success')
  754. }).catch(() => {
  755. fs.writeFileSync('run.done', 'error')
  756. })
  757. }
  758. else return op['runas']()
  759. }
  760. , 'repo-relocate' : function(args){
  761. // relocate a subfolder in source repo to same subfolder in target repo with history.
  762. var args = args || {
  763. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  764. , folder : processedArgs._[3] || 'server'
  765. , sourcerepo : processedArgs._[2] || 'client'
  766. , targetrepo : processedArgs._[1] || 'elixir-server'
  767. }
  768. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  769. // , stdio: ['pipe', process.stdout, process.stderr]
  770. , inherit: true,
  771. shell: true,
  772. env: process.env
  773. , runas: processedArgs.runas
  774. }
  775. return op['repo-split'](args).then(()=>{
  776. return op['repo-merge'](args).then(()=>{
  777. // cleanup folder from source.
  778. var cmdseq = [
  779. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  780. // commits have to intentional...
  781. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  782. ]
  783. return any(cmdseq.map(callsheltask))
  784. })
  785. }).catch(e=>{console.error(e)})
  786. }
  787. , 'repo-split' : function(args) {
  788. // https://gist.github.com/smdabdoub/17065c348289158277b5
  789. /**
  790. * Eg : folder, remotebase, sourcerepo, targetrepo
  791. * args.folder = 'server'
  792. * args.remotebase = 'https://git.bbh/chess/'
  793. * args.sourcerepo = 'client'
  794. * args.targetrepo = 'elixir-server'
  795. */
  796. var args = args || {
  797. folder : 'server'
  798. , remotebase : 'http://git.bbh/chess/'
  799. , sourcerepo : 'client'
  800. , targetrepo : 'elixir-server'
  801. }
  802. var options = { cwd: `${instanceroot}/relocate`
  803. // , stdio: ['pipe', process.stdout, process.stderr]
  804. , inherit: true,
  805. shell: true,
  806. env: process.env
  807. , runas: processedArgs.runas
  808. }
  809. var cmdseq = [
  810. // create a temporary working dir in current folder where we started execution.
  811. ['mkdir', [ '-p', 'relocate']]
  812. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  813. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  814. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  815. ]
  816. return any(cmdseq.map(callsheltask)).then(() => {
  817. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  818. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  819. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  820. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  821. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  822. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  823. // subtree split and filter-branch are options. We currently use repo-filter.
  824. return op['filter-repo'](args)
  825. }).catch(e=>{console.error(e); throw 'failed'})
  826. }
  827. , 'repo-merge' : function(args) {
  828. // Merge source repo into target repo
  829. var args = args || {
  830. folder : 'server'
  831. , remotebase : 'http://git.bbh/chess/'
  832. , sourcerepo : 'client'
  833. , targetrepo : 'elixir-server'
  834. }
  835. var sourcerepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  836. // , stdio: ['pipe', process.stdout, process.stderr]
  837. , inherit: true,
  838. shell: true,
  839. env: process.env
  840. , runas: processedArgs.runas
  841. }
  842. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  843. // , stdio: ['pipe', process.stdout, process.stderr]
  844. , inherit: true,
  845. shell: true,
  846. env: process.env
  847. , runas: processedArgs.runas
  848. }
  849. var cmdseq = [
  850. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  851. , targetrepooptions ]
  852. // , ['git', ['push', targetrepooptions ] // manual push for now..
  853. ]
  854. return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e)})
  855. }
  856. , 'filter-repo' : function(args){
  857. // Merge source repo into target repo
  858. var args = args || {
  859. folder : 'server'
  860. , remotebase : 'http://git.bbh/chess/'
  861. , targetrepo : 'elixir-server'
  862. }
  863. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  864. , inherit: true, shell: true
  865. , env: process.env
  866. , runas: processedArgs.runas
  867. }
  868. var cmdseq = [
  869. // git checkout -b feature/merge-old-project
  870. // git remote add src-project ../src-project
  871. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  872. ]
  873. return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e); throw 'failed' })
  874. }
  875. , 'filter-branch' : function(preservefolder, repo){
  876. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  877. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  878. // Preserve a specific folder.
  879. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  880. /*
  881. git clone repo reposplit
  882. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  883. git remote rm origin
  884. */
  885. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  886. }
  887. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  888. // // Merge repo2 into a subfolder in repo1
  889. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  890. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  891. // /*
  892. // cd repo1
  893. // git remote add -f tempmergesource ../{{mergesource}}/.git
  894. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  895. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  896. // git commit
  897. // // Repair History
  898. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  899. // #!/usr/bin/env bash
  900. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  901. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  902. // subdir=server
  903. // git filter-branch --tree-filter '
  904. // first='"$first"'
  905. // last='"$last"'
  906. // subdir='"$subdir"'
  907. // log_file=/tmp/filter.log
  908. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  909. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  910. // echo "=== $GIT_COMMIT: making changes"
  911. // files=$(git ls-tree --name-only $GIT_COMMIT)
  912. // mkdir -p $subdir
  913. // for i in $files; do
  914. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  915. // done
  916. // else
  917. // echo "=== $GIT_COMMIT: ignoring"
  918. // fi \
  919. // >> $log_file
  920. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  921. // status=0 # tell tree-filter never to fail
  922. // '
  923. // git remote rm tempmergesource
  924. // */
  925. // // better alternative for history
  926. // /**
  927. // *
  928. // git clone git@server.com:old-project.git
  929. // git clone git@server.com:new-project.git
  930. // cd old-project
  931. // mkdir old-project
  932. // git mv !(old-project) old-project
  933. // ls -la and gt mv hidden files ....
  934. // git commit -a -S -m “Moving old project into its own subdirectory”
  935. // cd ../new-project
  936. // git remote add old-project ../old-project
  937. // git fetch old-project
  938. // git checkout -b feature/merge-old-project
  939. // git merge -S --allow-unrelated-histories old-project/master
  940. // git push origin feature/merge-old-project
  941. // git remote rm old-project
  942. // */
  943. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  944. // }
  945. , 'pull' : (label) => {
  946. // Usage :
  947. // elxr pull -- Defaults to run config
  948. return elxr.getpulltask(selectedinstance)()
  949. }
  950. , 'isInstalled': () => {
  951. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  952. console.log(processedArgs._[1] + ' exists.')
  953. return true;
  954. });
  955. }
  956. , 'i' : () => {
  957. var tasks = []
  958. // tasks.push(op['pull']);
  959. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
  960. tasks.push(op['use'])
  961. if (!__isElevated) {
  962. tasks.push(op['npmi'])
  963. }
  964. // var tasksdefs = [
  965. // ['elxr', ['pull']]
  966. // , ['elxr', ['use', 'elixir']]
  967. // , ['elxr', ['npmi']]
  968. // ]
  969. // tasksdefs.forEach(tasksdef=>{
  970. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  971. // })
  972. return any(tasks);
  973. }
  974. , 'npmi': () => {
  975. var tasks = [];
  976. // Build fails without babel...
  977. tasks.push(getShellTask(
  978. 'npm',[ 'i', '-g', 'babel-cli' ]
  979. ) )
  980. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  981. npmbuildrepos = []
  982. npmbuildrepos.forEach(repo => {
  983. tasks.push(() => {
  984. return nodeShellExec('npm', ['i --force'], {
  985. inherit: true, shell: true
  986. , cwd: instanceroot + '/' + repo
  987. , env: process.env
  988. , title: `npm i for ${repo}`
  989. }).catch((e) => {
  990. console.error('Ignoring Benign Error'); console.error(e);
  991. }).then(() => {
  992. console.log(`--npm run build for ${repo}--------------------`)
  993. return nodeShellExec('npm', ['run build'], {
  994. inherit: true, shell: true
  995. , cwd: instanceroot + '/' + repo
  996. , env: process.env
  997. , title: `npm run build for ${repo}`
  998. }).then(Tasq.then).catch(Tasq.catch)
  999. })
  1000. })
  1001. })
  1002. any(tasks).then(() => {
  1003. gitRepos.push('client/server');
  1004. gitRepos = gitRepos.concat(elevatedRunasRepos);
  1005. // gitRepos = [
  1006. // // 'bbhverse', 'serververse', 'elixir-server',
  1007. // // 'clientverse',
  1008. // 'client'
  1009. // ];
  1010. var rmtasks = []
  1011. var repotasks = []
  1012. var env = Object.assign({}, process.env)
  1013. delete env.NODE_ENV
  1014. gitRepos.forEach(repodef => {
  1015. rmtasks.push(
  1016. // () => {
  1017. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1018. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  1019. (callShellTask(['rm', ['package-lock.json'], {
  1020. inherit: true, shell: true
  1021. , cwd: instanceroot + '/' + repodef.repo
  1022. , env: process.env
  1023. , title: `rm 'package-lock.json' for ${repodef.repo}`
  1024. }]))()
  1025. .then(()=>{
  1026. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1027. }).catch((e) => { console.error(e) })
  1028. // }
  1029. )
  1030. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  1031. repotasks.push(
  1032. () => {
  1033. console.log(`--npm i for ${repodef.repo}--------------------`)
  1034. var p = nodeShellExec('npm', ['i', '--force'], {
  1035. inherit: true, shell: true
  1036. , cwd: instanceroot + '/' + repodef.repo
  1037. , env
  1038. , title: `npm i for ${repodef.repo}`
  1039. }).then(Tasq.then).catch(Tasq.catch)
  1040. return p;
  1041. })
  1042. }
  1043. })
  1044. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  1045. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  1046. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  1047. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  1048. // Second time try also doesnt work.
  1049. // repotasks.push(
  1050. // () => {
  1051. // var env = Object.assign({}, process.env)
  1052. // delete env.NODE_ENV
  1053. // console.log(`--------------------second time npm i for client--------------------`)
  1054. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  1055. // // return nodeShellExec('npm', ['i --force'], {
  1056. // inherit: true, shell: true
  1057. // , cwd: instanceroot + '/' + 'client'
  1058. // , env
  1059. // , title: `npm i for client`
  1060. // }).then(Tasq.then).catch(Tasq.catch)
  1061. // })
  1062. var bowerRepos = [{ repo : 'client'}]
  1063. bowerRepos.forEach(repodef => {
  1064. repotasks.push(() => {
  1065. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
  1066. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  1067. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  1068. inherit: true, shell: true
  1069. , cwd: instanceroot + '/' + repodef.repo
  1070. , env: process.env
  1071. , title: `bower i for ${repodef.repo}`
  1072. }).then(Tasq.then).catch(Tasq.catch)
  1073. return p;
  1074. })
  1075. })
  1076. // console.log('rmtasks.length : ' + rmtasks.length)
  1077. return Promise.all(rmtasks).then(() => any(repotasks));
  1078. }).catch(e => {
  1079. }).finally(statuslog.finally)
  1080. }
  1081. , 'start': (label) => {
  1082. console.log('Starting Elixir Server.');
  1083. var env = Object.assign({}, process.env); // Shallow clone it.
  1084. // console.dir(env)
  1085. env.NODE_ENV = process.env.NODE_ENV || 'development';
  1086. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  1087. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  1088. // cmd = 'node'
  1089. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
  1090. var childPromise = nodeShellExec(...cmd, {
  1091. // inherit : true,
  1092. shell: true,
  1093. detached: true,
  1094. stdio: 'ignore',
  1095. cwd: instanceroot + '/' + 'elixir-server'
  1096. , env: env
  1097. })
  1098. var child = childPromise.process;
  1099. if (typeof child.pid !== 'undefined') {
  1100. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1101. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  1102. encoding: 'utf8'
  1103. })
  1104. }
  1105. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  1106. // inherit : true,
  1107. // shell: true, detached: true,
  1108. // cwd : 'qms/server',
  1109. // env: env,
  1110. // shell : true
  1111. // })
  1112. // nodeShellExec('ember', ['s'], {
  1113. // // inherit : true,
  1114. // shell: true, detached: true,
  1115. // cwd : 'client/',
  1116. // env: env
  1117. // })
  1118. console.log('Starting Elixir Client Host.');
  1119. var cmd = ['ember', ['s']]
  1120. var childPromise = nodeShellExec(...cmd, {
  1121. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  1122. // PB : TODO -- ember debugging.
  1123. // inherit : true,
  1124. shell: true,
  1125. detached: true,
  1126. stdio: 'ignore',
  1127. cwd: instanceroot + '/' + 'client'
  1128. , env: env
  1129. })
  1130. // .catch(e=>console.error(e))
  1131. child = childPromise.process;
  1132. if (typeof child.pid !== 'undefined') {
  1133. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1134. fs.writeFileSync('.client.server.pid', child.pid, {
  1135. encoding: 'utf8'
  1136. })
  1137. }
  1138. }
  1139. , 'stop': (label) => {
  1140. const kill = require('tree-kill');
  1141. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  1142. encoding: 'utf8'
  1143. })
  1144. fs.unlinkSync('.elixir-server.elixir.server.pid')
  1145. console.log(serverPid)
  1146. kill(serverPid)
  1147. serverPid = fs.readFileSync('.client.server.pid', {
  1148. encoding: 'utf8'
  1149. })
  1150. fs.unlinkSync('.client.server.pid')
  1151. console.log(serverPid)
  1152. kill(serverPid)
  1153. }
  1154. , 'model' : () => {
  1155. if (__isElevated) {
  1156. var tasks = [
  1157. () => {
  1158. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  1159. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  1160. inherit: true, shell: true
  1161. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  1162. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  1163. , env: process.env
  1164. }).catch((e) => { console.error(e) })
  1165. return p;
  1166. }
  1167. ];
  1168. return any(tasks).then(() => {
  1169. fs.writeFileSync('run.done', 'success')
  1170. }).catch(() => {
  1171. fs.writeFileSync('run.done', 'error')
  1172. })
  1173. }
  1174. else return op['runas']()
  1175. }
  1176. , 'use' : () => {
  1177. // use a certain named instance.
  1178. // Eg :
  1179. // 1) elxr use elixir
  1180. // 2) elxr use cihsr
  1181. // If environment is not specified defaults to development.
  1182. // 1) NODE=test elxr use elixir
  1183. /*// Steps
  1184. 1) Delete Config and Data symlinks
  1185. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  1186. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  1187. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1188. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  1189. */
  1190. var runconfig = { NODE_ENV: selectedinstance.node_env }
  1191. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  1192. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  1193. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  1194. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  1195. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  1196. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  1197. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  1198. return
  1199. }
  1200. var tasks = [
  1201. () => {
  1202. if (existsSync('config')) {
  1203. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  1204. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  1205. return p;
  1206. }
  1207. else return Promise.resolve(true);
  1208. },
  1209. () => {
  1210. if (existsSync('data')) {
  1211. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  1212. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  1213. return p;
  1214. }
  1215. else return Promise.resolve(true);
  1216. },
  1217. ];
  1218. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  1219. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  1220. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  1221. // console.log(process.env.cwd)
  1222. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  1223. // Maps an environment to a branch. Not required if the branch is appropriately named.
  1224. var checkoutMap = { 'development': 'master' }
  1225. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  1226. var performPullOrCloneForBranch = (def)=>{
  1227. var promise = Promise.resolve(true)
  1228. if (!branch) {
  1229. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1230. promise = nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{ branch = __branch})
  1231. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1232. }
  1233. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e )})
  1234. }
  1235. var performCloneAndCheckout = null;
  1236. // cant use git checkout -b it fails when branch already exists.
  1237. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1238. return performPullOrCloneForBranch(def).then(()=>{
  1239. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1240. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1241. // inherit : true, shell: true,
  1242. cwd: instanceroot + '/' + def.repo
  1243. // , stdio : ignore // Use when we want to silence output completely.
  1244. , runas: processedArgs.runas
  1245. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  1246. }).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 } })
  1247. })
  1248. }
  1249. // var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  1250. // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  1251. var elevatedqueue = [];
  1252. var enqueueOnce = (queue, task, def) => {
  1253. var found = queue.find(element => {
  1254. var keys = Object.keys( element )
  1255. for(var k=0; k < keys.length; k++) {
  1256. if(element[keys[k]] !== def[k]) return false;
  1257. }
  1258. })
  1259. queue.push(function(){ return task(this)}.bind(def));
  1260. }
  1261. var enqueue = (queue, task, def) => {
  1262. queue.push(function(){ return task(def)}.bind(def));
  1263. }
  1264. var mergeSources = {
  1265. 'development': null,
  1266. 'test': 'master',
  1267. 'production': 'master'
  1268. }
  1269. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1270. // Checkout is reduced to pull provided the current branch is the targetbranch
  1271. if(branch === mergesource) performCheckout = (def) => {
  1272. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1273. return nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{
  1274. if(branch === __branch) return performCloneAndCheckout(def)
  1275. return performPullOrCloneForBranch(def)
  1276. })
  1277. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1278. }
  1279. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  1280. var performPullAll = (def) => {
  1281. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1282. return nodeShellExec('git', ['pull', '--all'], {
  1283. // inherit : true, shell: true,
  1284. cwd: instanceroot + '/' + def.repo
  1285. , runas: processedArgs.runas
  1286. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  1287. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  1288. }
  1289. var excludeCheckouts = Object.assign(exludeMergeRepos)
  1290. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  1291. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  1292. var performMerge = (def) => {
  1293. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  1294. return nodeShellExec('git', ['merge', mergesource], {
  1295. inherit: true, shell: true,
  1296. cwd: instanceroot + '/' + def.repo
  1297. , runas: processedArgs.runas
  1298. }).catch((e) => { console.error(e) })
  1299. }
  1300. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
  1301. // var performRepoOperation = function(def) {
  1302. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  1303. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  1304. // }
  1305. return any(tasks).then(() => {
  1306. var pr = Promise.resolve(true)
  1307. if (!__isElevated) {
  1308. pr = op['runas']()
  1309. return pr.then(()=>{
  1310. //target is the env is we specify in elxr use command. Default is dev
  1311. //Switch to target branch
  1312. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  1313. // pull or clone target branch
  1314. .then(() => {
  1315. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1316. return any(gitRepos.map((repo) => performPullAll(repo)))
  1317. })
  1318. // switch to source branch
  1319. .then( () => {
  1320. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  1321. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  1322. })
  1323. //Pull on merge source branch
  1324. .then( () => {
  1325. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1326. return any(gitRepos.map((repo) => performPullAll(repo)))
  1327. })
  1328. //Switch to target branch
  1329. .then( () => {
  1330. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1331. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  1332. })
  1333. .then( //Merge source branch to target branch
  1334. () => {
  1335. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1336. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
  1337. })
  1338. })
  1339. }
  1340. else {
  1341. tasks = [
  1342. () => {
  1343. // Use junctions to avoid npm package issues
  1344. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  1345. inherit: true, shell: true
  1346. , cwd : instanceroot
  1347. , env: process.env
  1348. }).catch((e) => { console.error(e) })
  1349. return p;
  1350. }
  1351. ];
  1352. if (processedArgs._[1]) {
  1353. tasks = tasks.concat(
  1354. [
  1355. () => {
  1356. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  1357. inherit: true, shell: true
  1358. , cwd : instanceroot
  1359. , env: process.env
  1360. }).catch((e) => { console.error(e) })
  1361. return p;
  1362. }
  1363. ]
  1364. )
  1365. }
  1366. return any(tasks).then(()=>{
  1367. // checkout target branch
  1368. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1369. // pull or clone target branch
  1370. .then(() => {
  1371. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1372. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  1373. })
  1374. // switch to source branch
  1375. .then( () => {
  1376. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1377. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  1378. })
  1379. //Pull on merge source branch
  1380. .then( () => {
  1381. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1382. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  1383. })
  1384. //Switch to target branch
  1385. .then( () => {
  1386. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1387. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1388. })
  1389. .then( //Merge source branch to target branch
  1390. () => {
  1391. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1392. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
  1393. })
  1394. .then(() => {
  1395. fs.writeFileSync('run.done', 'success')
  1396. }).catch(() => {
  1397. fs.writeFileSync('run.done', 'error')
  1398. })
  1399. })
  1400. }
  1401. }).catch(() => {
  1402. fs.writeFileSync('run.done', 'error')
  1403. })
  1404. // Antibiotic stewardship program.
  1405. // 1st use is fine.
  1406. // Max vials dispense
  1407. // 2nd use Pharmacy needs justification Form.
  1408. // Approval after a certain period of time.
  1409. }
  1410. , 'g': () => {
  1411. if (processedArgs.h) {
  1412. console.log('elxr g [modelname] => generate a model named [modelname]');
  1413. console.log('elxr g => regenerate all known models');
  1414. return
  1415. }
  1416. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1417. // console.log('Starting directory: ' + process.cwd());
  1418. // try {
  1419. // child = child.on('close', () => { process.chdir(label) } );
  1420. // console.log('New directory: ' + process.cwd());
  1421. // }
  1422. // catch (err) {
  1423. // console.log('chdir: ' + err);
  1424. // }
  1425. // child.on('close', function(){
  1426. // var options = {
  1427. // shell : true
  1428. // , inherit : true
  1429. // // , cwd : '' + process.cwd
  1430. // // , env : process.env
  1431. // };
  1432. // nodeShellExec('git', ['init'], { inherit : true});
  1433. if (0) {
  1434. // PB : TODO -- Special google chrome profile for tests etc.
  1435. nodeShellExec('pwd', { inherit: true });
  1436. // /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"
  1437. // "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
  1438. // "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
  1439. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1440. "--profile-directory=Profile 1"
  1441. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1442. }
  1443. // nodeShellExec('npm', ['init', '-y'], options);
  1444. // nodeShellExec('npm', ['init', '-y'], options);
  1445. // })
  1446. var g = {
  1447. 'client': () => {
  1448. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  1449. console.info('Creating new ember client named : ' + processedArgs._[2]);
  1450. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1451. stdio: ['pipe', process.stdout, process.stderr],
  1452. inherit: true,
  1453. shell: true,
  1454. cwd: path.dirname(__dirname),
  1455. env: env
  1456. })
  1457. },
  1458. 'modelr': () => {
  1459. var tasks = [
  1460. () => {
  1461. var p = nodeShellExec('"ember"', [
  1462. 'g'
  1463. , 'modelr'
  1464. , processedArgs._[2]], {
  1465. inherit: true, shell: true, env: process.env
  1466. }).then(() => {
  1467. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  1468. return true;
  1469. }).catch((e) => { console.error(e) })
  1470. return p;
  1471. },
  1472. () => {
  1473. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1474. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  1475. chromeprefs = JSON.parse(chromeprefs)
  1476. var previous = chromeprefs.download.default_directory;
  1477. var parentDir = path.dirname(__dirname);
  1478. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1479. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1480. // PB : TODO -- detect where chrome is installed.
  1481. // PB : TODO -- set the download dir to the place where files are needed.
  1482. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1483. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1484. , '--profile-directory="chess"'
  1485. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1486. inherit: true, shell: true
  1487. , env: process.env
  1488. }).then(() => {
  1489. chromeprefs.download.default_directory = previous;
  1490. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1491. return true;
  1492. }).catch((e) => { console.error(e) })
  1493. return p;
  1494. }
  1495. ,
  1496. () => {
  1497. console.log('Browser process should have closed here....')
  1498. return true;
  1499. }
  1500. ]
  1501. any(tasks)
  1502. }
  1503. }
  1504. g[processedArgs._[1]]();
  1505. }
  1506. }
  1507. var util = require('util');
  1508. var cliname = 'elxr';
  1509. var ver = '1.1';
  1510. var readme = `
  1511. Command syntax examples
  1512. elxr
  1513. Displays help. Same as elxr h
  1514. elxr i
  1515. Runs interactive propmts to help choose installation options.
  1516. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  1517. General command syntax.
  1518. Eg: NODE_ENV=development elxr pull elixir
  1519. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  1520. The specific cmd defines what the value is interpreted as.
  1521. There are several cmds that do not require an {{instancename}} parameter.
  1522. Eg: elxr remote remove origin
  1523. Git operations or passthrough external commands on all repository folders in you working directory.
  1524. Main objectives.
  1525. elxr cli is a wrapper around other shell commands and api based operations.
  1526. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  1527. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  1528. `;
  1529. var help = `
  1530. ${readme}
  1531. # list of commands... please refer dveloper documentation for ${cliname}
  1532. ${
  1533. // util.inspect(
  1534. [Object.keys(op)]
  1535. // )
  1536. }
  1537. `;
  1538. var elxr = {
  1539. help() {
  1540. return chalk.cyanBright(`
  1541. -------------------------------------------------------------------------------
  1542. *** BBH Elixir ***
  1543. -------------------------------------------------------------------------------
  1544. elxr ${ver}
  1545. A cli tool for chess
  1546. ${help}
  1547. -------------------------------------------------------------------------------
  1548. `)
  1549. }
  1550. , info() {
  1551. return chalk.cyanBright(`
  1552. -------------------------------------------------------------------------------
  1553. *** BBH Elixir ***
  1554. -------------------------------------------------------------------------------
  1555. elxr ${ver}
  1556. A cli tool for chess
  1557. -------------------------------------------------------------------------------
  1558. `)
  1559. }
  1560. , getpulltask(def){
  1561. // def can be an instance config
  1562. // Or an object with many repos and elevated repos
  1563. // Or a single repo ( Either Elevated or normal. )
  1564. def = def || {
  1565. repos : selectedinstance.repos,
  1566. elevated : selectedinstance.elevated
  1567. }
  1568. var elevatedpulltasks = null;
  1569. if(def.repo) {
  1570. // Single repo case.
  1571. if(def.repo.requiresElevation) {
  1572. elevatedpulltasks = function() {
  1573. return performPull(def.repo).then(() => {
  1574. return true;
  1575. }).catch((e) => {
  1576. console.error(e)
  1577. })
  1578. }
  1579. return
  1580. }
  1581. else {
  1582. var regularpulltasks = function(){
  1583. var pendingpulls = [];
  1584. pendingpulls.push(performPull(def.repo))
  1585. return Promise.all(pendingpulls).finally(Traq.finally)
  1586. }
  1587. }
  1588. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1589. else return getTaskWithoutElevation({ regularpulltasks})
  1590. }
  1591. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  1592. console.dir(def)
  1593. var env = Object.assign({}, process.env); // Shallow clone it.
  1594. console.log('Running exlr pull : ' + path.dirname(__dirname))
  1595. var useGitPull = processedArgs.useGitPull || false;
  1596. if(def.elevated || def.repos) {
  1597. if(def.elevated) def.requiresElevation = true;
  1598. else delete def.requiresElevation;
  1599. }
  1600. else {
  1601. if(def.requiresElevation) def.elevated = [def]
  1602. else def.repos = [def]
  1603. }
  1604. var regularpulltasks = function(){ return Promise.resolve(true) }
  1605. if(def.elevated){
  1606. elevatedpulltasks = function() {
  1607. return any(def.elevated.map((def) => performPull(def.repo))).then(() => {
  1608. return true;
  1609. }).catch((e) => {
  1610. console.error(e)
  1611. })
  1612. }
  1613. }
  1614. if(def.repos) {
  1615. var regularpulltasks = function(){
  1616. var pendingpulls = [];
  1617. def.repos.forEach((def) => { pendingpulls.push(performPull(def.repo)) })
  1618. return Promise.all(pendingpulls).finally(Traq.finally)
  1619. }
  1620. }
  1621. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1622. else return getTaskWithoutElevation({ regularpulltasks})
  1623. }
  1624. }
  1625. function preworkerconfig(){
  1626. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  1627. gitRepos = selectedinstance.repos
  1628. // gitRepos = ['chess-server-lib'];
  1629. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  1630. elevatedRunasRepos = selectedinstance.elevated
  1631. // Repos that should excluded from merge for releases...
  1632. exludeMergeRepos = selectedinstance.exludeMergeRepos
  1633. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  1634. // mysql -u root -p db_name < drop_all_tables.sql
  1635. var mysql = '../xampp/mysql/bin/mysql'
  1636. var mysqldump = '../xampp/mysql/bin/mysqldump'
  1637. }
  1638. // The main elxr cli process
  1639. function elxrworker() {
  1640. var subcommandlabels = {
  1641. remote : (`remote ${processedArgs._[1] || ''}`).trim()
  1642. }
  1643. var __runcmd = function (label) {
  1644. var distinquishedlabel = subcommandlabels[label] || label
  1645. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  1646. }
  1647. // --runas
  1648. if (processedArgs.runas) {
  1649. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  1650. return __runcmd('runas')
  1651. }
  1652. else return __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  1653. }
  1654. function acquireChoices(selectedinstance) {
  1655. var hasconfig = false;
  1656. console.warn(chalk.cyan(`
  1657. -------------------------------------------------------------------------------
  1658. Warning : Cannot locate your preferred configuration since it was not specified
  1659. You should fork the default chess configuration to customize and make it
  1660. your own instance with a named config as
  1661. {{yourowninstancename}}-config-{{yourchosenenvironment}}
  1662. And then run this tool as follows
  1663. NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  1664. OR
  1665. Run this tool with the following command to use a quick start default.
  1666. elxr --default
  1667. OR
  1668. Choose one of the options below to run interactively.
  1669. We will run your choice at the next prompt.
  1670. -------------------------------------------------------------------------------
  1671. `))
  1672. var prompt = cli.prompter;
  1673. return prompt.ask(`Choose an option :
  1674. d) Install the default chess instance.
  1675. => elxr i chess node_env=development --default
  1676. n) Create your custom new instance interactively
  1677. => elxr i {{instanceName}} node_env={{environment}}
  1678. i) Choose an instance and environment to install
  1679. => elxr i {{instanceName}} node_env={{environment}}
  1680. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  1681. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  1682. h) Help
  1683. q) Quit
  1684. Default <= d
  1685. : `).then((choice) => {
  1686. if (choice && choice === 'd' || !choice) {
  1687. processedArgs._[0] = 'i'
  1688. selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  1689. selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  1690. selectedinstance.reposerver = 'https://git.bbh.org.in'
  1691. }
  1692. else if (choice === 'h') {
  1693. processedArgs._[0] = 'h'
  1694. fs.writeFileSync('run.done', 'noop help');
  1695. console.log(elxr.help()); process.exit()
  1696. }
  1697. else if (choice === 'n' || choice === 'i') {
  1698. var p1 = cli.prompter;
  1699. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1700. processedArgs._[0] = 'i'
  1701. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  1702. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1703. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1704. if (choice === 'n') {
  1705. selectedinstance.reposerver = 'https://git.bbh.org.in'
  1706. console.warn(
  1707. chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  1708. process.exit();
  1709. }
  1710. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1711. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1712. })
  1713. })
  1714. })
  1715. } else if (choice === 'c') {
  1716. var p1 = cli.prompter;
  1717. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1718. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  1719. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1720. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1721. return p1.ask(`Enter cmd :
  1722. p) pull
  1723. Default <= p
  1724. : `).then(function (cmd) {
  1725. if (!cmd || cmd === 'p') {
  1726. processedArgs._[0] = 'pull'
  1727. }
  1728. else processedArgs._[0] = cmd
  1729. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1730. selectedinstance.reposerver = reposerver || selectedinstance.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1731. })
  1732. })
  1733. })
  1734. })
  1735. } else {
  1736. 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.`));
  1737. fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  1738. fs.writeFileSync('run.done', 'noop quit');
  1739. process.exit()
  1740. }
  1741. })
  1742. }
  1743. var mergeObjByKey = function(arrOfObjs, keyName) {
  1744. var keyedDistinct = {}
  1745. var distinctArrOfObjs = []
  1746. arrOfObjs.forEach( o => {
  1747. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o)
  1748. })
  1749. Object.keys(keyedDistinct).forEach(key => {
  1750. distinctArrOfObjs.push( utils.assign( ...keyedDistinct[key] ) ) // PB : TODO -- Shallow use utils.assign
  1751. })
  1752. return distinctArrOfObjs;
  1753. }
  1754. var cacheWriteInstanceConfig = function(chessinstances){
  1755. var instanceName = chessinstances['current_run'].instanceName;
  1756. var node_env = chessinstances['current_run'].node_env;
  1757. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos, 'repo') ;
  1758. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated, 'repo') ;
  1759. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  1760. }
  1761. var acquireConfig = function (selected) {
  1762. var configrepo = selected.instanceName + '-config-' + selected.node_env;
  1763. return performPull(configrepo).then(() => {
  1764. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  1765. selectedinstance = require(manifestpath)()
  1766. // Config from server always override merges into selection ecept for the current selection.
  1767. // PB : TODO -- utils.assign Array merges are non-distinct...
  1768. if(!selectedinstance.repos[0].repo) {
  1769. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  1770. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  1771. }
  1772. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  1773. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  1774. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  1775. }
  1776. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = utils.assign(selected, selectedinstance)
  1777. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  1778. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  1779. cacheWriteInstanceConfig(chessinstances)
  1780. ENV.NODE_ENV = selectedinstance.node_env;
  1781. })
  1782. .catch((e) => {
  1783. console.error(e)
  1784. console.error('Config acquisition failed.')
  1785. })
  1786. }
  1787. var launchpath = path.normalize(process.cwd())
  1788. var thisscriptdir = path.normalize(__dirname); // PB : TODO -- Thisscriptdir could be dislocated when run as a standalone file... We need to detect this where and how we were run.
  1789. // The easisest would be to ask for a target directory and default to current dir....
  1790. var instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
  1791. var __default = {
  1792. // Default is public server only.
  1793. // All public repos are by default available.
  1794. reposervers: ['https://git.bbh.org.in']
  1795. , repos: [
  1796. { repo : 'setup' }
  1797. , { repo : 'elxr' }
  1798. , { repo : 'loopback-connector-mysql' }
  1799. , { repo : 'loopback-jsonapi-model-serializer' }
  1800. , { repo : 'loopback-component-jsonapi' }
  1801. , { repo : 'ember-service-worker' }
  1802. , { repo : 'ember-service-worker-asset-cache' }
  1803. , { repo : 'ember-service-worker-cache-fallback' }
  1804. , { repo : 'ember-service-worker-index' }
  1805. , { repo : 'ember-sw-client-route' }
  1806. ]
  1807. , elevated: []
  1808. , exludeMergeRepos: {}
  1809. , instanceName: 'chess'
  1810. // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
  1811. , node_env: 'development'
  1812. }
  1813. var hasElxr = function(path, options, cb) {
  1814. // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
  1815. options = options || {};
  1816. var tasks = [
  1817. '/elxr' // Is there a subfolder named elxr
  1818. , '/elxr/.git' // which is self git repository
  1819. , '/elxr/.elxr' // and has .elxr subfolder
  1820. , '/elxr/.elxr/' + __ALIAS__STAMP__ // Which has our stamp.
  1821. ]
  1822. if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
  1823. var value = existsFolderSync(path + tpath);
  1824. return { value, done : acc && !value };
  1825. }).value }
  1826. if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
  1827. var value = existsFolderSync(path + tpath);
  1828. return { value, done : acc && !value };
  1829. }).value );
  1830. return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
  1831. var value = existsFolderSync(path + tpath);
  1832. return { value, done : acc && !value };
  1833. }).value);
  1834. }
  1835. var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); }
  1836. var detectfromroot = function(root){
  1837. return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(root) ) }
  1838. }
  1839. var detectinstances = function () {
  1840. console.log(`launchpath = ${launchpath}`)
  1841. console.log(`thisscriptdir = ${thisscriptdir}`)
  1842. // PB : TODO -- !Postpone this.
  1843. console.log(`instanceroot = ${instanceroot}`) // Not yet confirmed...
  1844. // Note : Paths should already be normalized fefore this.
  1845. var root = instanceroot;
  1846. var detected = { root };
  1847. var instanceoptions = [clioverrides]
  1848. return hasElxr(launchpath).then( (elxrCliExists) => {
  1849. // We need a reference to the root director for elxr cli to be properly oriented.
  1850. if (( elxrCliExists && path.normalize(launchpath + '/elxr')) === thisscriptdir) {
  1851. // We were run from the proper root with elxr cli in the subfolder.
  1852. instanceroot = root = launchpath;
  1853. instanceoptions.splice( 0, 0, detected = { root })
  1854. instanceoptions.splice( 0, 0, detectfromroot(root))
  1855. }
  1856. else {
  1857. if(path.normalize(launchpath + '/elxr') === thisscriptdir) {
  1858. // elxrCliExists is false -- and yet thiscriptdir is still proper.
  1859. // PB : TODO -- Maybe a warning / abort if for some reason this scriptdir should not be taken over...
  1860. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.')
  1861. instanceroot = root = launchpath;
  1862. instanceoptions.splice( 0, 0, detected = { root })
  1863. instanceoptions.splice( 0, 0, detectfromroot(root))
  1864. }
  1865. else if (launchpath === thisscriptdir) {
  1866. var parentHasElxr = hasElxrSync(launchpath + '/..')
  1867. // PB : TODO -- verify if we have .elxr folder in the parent...
  1868. if(!parentHasElxr) {
  1869. // ! thisscriptdir is not elxr.
  1870. console.error('Invalid run location in subfolder that looks like elxr. We should probably abort as elxr will not sync.')
  1871. }
  1872. // Same directory doesn't mean we are being run from elxr sub directory.
  1873. // In standalone build script we may or not be in the same location.
  1874. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  1875. // Unbuilt therefore we are in the elxr sub directory.
  1876. instanceroot = root = path.normalize(launchpath + '/..');
  1877. instanceoptions.splice( 0, 0, detected = { root });
  1878. instanceoptions.splice( 0, 0, detectfromroot(root));
  1879. }
  1880. else {
  1881. // Built version.
  1882. // We could have been run from the elxr subfolder. Highly likely that the built version isn't the full elxr.
  1883. if(parentHasElxr) {
  1884. // Built version was run from the full elxr subfolder. Should work
  1885. // PB : TODO -- but we should switch to the full version...
  1886. instanceroot = root = path.normalize(launchpath + '/..');
  1887. instanceoptions.splice( 0, 0, detected = { root })
  1888. instanceoptions.splice( 0, 0, detectfromroot(root))
  1889. }
  1890. else {
  1891. instanceroot = root = launchpath;
  1892. instanceoptions.splice( 0, 0, detected = { root })
  1893. instanceoptions.splice( 0, 0, detectfromroot(root))
  1894. // Assume current launchpath is a new instance and create.
  1895. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  1896. // if(clioverrides.instanceName) {
  1897. // if(clioverrides.node_env) {
  1898. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  1899. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  1900. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  1901. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  1902. // // eg : floder name can be elixir01 but instance name is elixr
  1903. // }
  1904. // else {
  1905. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + 'development')
  1906. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  1907. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  1908. // }
  1909. // }
  1910. // else {
  1911. // instanceroot = root = launchpath;
  1912. // if(clioverrides.node_env) {
  1913. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  1914. // instanceoptions.splice( 0, 0, detectfromroot(root))
  1915. // }
  1916. // else {
  1917. // // Nothing was specified... We only have one option from root.
  1918. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  1919. // }
  1920. // }
  1921. }
  1922. }
  1923. }
  1924. else {
  1925. if(elxrCliExists) {
  1926. instanceroot = root = launchpath;
  1927. instanceoptions.splice( 0, 0, detected = { root })
  1928. instanceoptions.splice( 0, 0, detectfromroot(root))
  1929. }
  1930. }
  1931. }
  1932. instanceroot = detected.root
  1933. __default.root = root;
  1934. clioverrides.root = clioverrides.root || root;
  1935. // Resolves empty array when No known instances detected.
  1936. return Promise.resolve(instanceoptions)
  1937. })
  1938. }
  1939. if(clioverrides.reconfirm) {
  1940. var reconfirm = { 'instanceName' : clioverrides['instanceName'] === 'chess' }
  1941. }
  1942. else { var reconfirm = {}; }
  1943. var getBoundEachPrompt = function(target, mustPrompt, promptables, choices) {
  1944. return function(prompts, k, i, a){
  1945. // No local instances config found. We use a default initialized instance available in selectedinstance
  1946. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  1947. // PB : TODO -- selectedinstance === __default check to prompt everything...
  1948. if( (mustPrompt[k] !== undefined && mustPrompt[k] !== null) && target[k] !== mustPrompt[k]
  1949. || (mustPrompt[k] === undefined || mustPrompt[k] === null) && (target[k] === undefined || target[k] === null)
  1950. || reconfirm[k]) {
  1951. prompts.push(async ()=>{
  1952. // PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
  1953. // We take a snapshot... Shallow.. !! If required deep should be used based on use case.
  1954. // If latest altered state is required we can reerence this directly.
  1955. // var asyncthis = Object.assign(this);
  1956. promptables[k].choices = choices[k]
  1957. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  1958. return await target[k]
  1959. })
  1960. }
  1961. delete mustPrompt[k]
  1962. return prompts
  1963. }
  1964. }
  1965. var __interactive_prompts = function( target, choices ){
  1966. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  1967. var interactionpoints = {
  1968. runchoice : {
  1969. label :
  1970. `Choose an option :
  1971. d) Install the default chess instance.
  1972. => elxr i chess node_env=development --default
  1973. n) Create your custom new instance interactively
  1974. => elxr i {{instanceName}} node_env={{environment}}
  1975. i) Choose an instance and environment to install
  1976. => elxr i {{instanceName}} node_env={{environment}}
  1977. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  1978. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  1979. h) Help
  1980. q) Quit
  1981. : `
  1982. , choices : []
  1983. , defaultchoice : 'c'
  1984. , interpret : function(choice){
  1985. var interpret_map = {
  1986. d : function(){
  1987. processedArgs._[0] = 'i'
  1988. target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  1989. target.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  1990. target.reposerver = 'https://git.bbh.org.in'
  1991. }
  1992. , n : function() { processedArgs._[0] = 'i' }
  1993. , i : function() { processedArgs._[0] = 'i' }
  1994. , c : async function() {
  1995. Object.defineProperty(this, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  1996. label : `Enter cmd :
  1997. p) pull
  1998. Default <= p
  1999. : `
  2000. , defaultchoice : 'pull'
  2001. }
  2002. ));
  2003. var cmd = await target['cmd'];
  2004. if (!cmd || cmd === 'p') { target['cmd'] = processedArgs._[0] = 'pull' }
  2005. else target['cmd'] = processedArgs._[0] = cmd
  2006. return cmd;
  2007. }
  2008. , h : function() { console.log(elxr.help()); process.exit() } // PB : TODO -- Why do we need log.
  2009. , q : function() { process.exit() }
  2010. }
  2011. var __interpreter = interpret_map['c']
  2012. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  2013. if(interpret_map[choice]) __interpreter = interpret_map[choice];
  2014. return __interpreter.call(target)
  2015. }
  2016. }
  2017. , instanceName : { label : `Enter Instance Name ( <= ${target.instanceName || 'chess'} ) : `, choices : [], defaultchoice : 'chess'}
  2018. , instanceType : { label : `Enter Instance Type ( <= ${target.instanceType || 'development'} ) : `, choices : [], defaultchoice : 'development'}
  2019. , reposerver : { label : `Enter Instance Name ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `, choices : [], defaultchoice : 'https://git.bbh.org.in'}
  2020. }
  2021. var eachPrompt = getBoundEachPrompt( target, promptkeys, interactionpoints, choices)
  2022. return Object.keys(interactionpoints).reduce(eachPrompt, [])
  2023. }
  2024. var downloadsdir = '../Downloads';
  2025. var prerequisites = [
  2026. {
  2027. shellcmd: 'git',
  2028. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  2029. , installer: 'Git-2.31.0-64-bit.exe'
  2030. , installcmd: ['cmd', ['/c', 'start',
  2031. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  2032. , '/VERYSILENT'
  2033. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  2034. ]]
  2035. , preinstallsteps: function() {
  2036. var prompt = cli.prompter;
  2037. var steps = [
  2038. () => {
  2039. if (!existsSync(downloadsdir + '/' + this.installer)) {
  2040. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  2041. }
  2042. else return Promise.resolve(true)
  2043. }
  2044. ]
  2045. var prompts = [
  2046. () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
  2047. , () => prompt.ask(`git email : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
  2048. ]
  2049. return any([any(steps), any(prompts)])
  2050. }
  2051. , installsteps: function () {
  2052. return any([this.installcmd].map(callsheltask))
  2053. }
  2054. , postinstallsteps: function(){
  2055. var prompt = cli.prompter;
  2056. var gitUser = 'guest';
  2057. var gitEmail = 'guest@bbh.org.in';
  2058. var prompts = [];
  2059. prompts.push(
  2060. ()=>{
  2061. var choices = { 0 : 'guest', 1 : 'chessdemo' }
  2062. return cli.prompt(choices, 'git user name').then(gituser => gitUser = gituser)
  2063. }
  2064. )
  2065. prompts.push(
  2066. ()=>{
  2067. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  2068. return cli.prompt(choices, 'git user email').then(gitemail => gitEmail = gitemail)
  2069. }
  2070. )
  2071. return any(prompts).then(()=>{
  2072. var steps = [
  2073. ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  2074. , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  2075. ]
  2076. return any(steps.map(callsheltask)).then(() => {
  2077. })
  2078. });
  2079. }
  2080. , install: function () {
  2081. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  2082. }
  2083. , verifyAndInstall : function(){
  2084. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  2085. if(exists) {
  2086. // return any(['git', ['config', '--global', '-l']].map(callsheltask))
  2087. return this.getUser(null, this.postinstallsteps.bind(this))
  2088. }
  2089. return this.install();
  2090. });
  2091. }
  2092. , getUser : function(repo, onNoResult){
  2093. onNoResult = onNoResult || function(){return false}
  2094. var globalOrLocal = '--global';
  2095. if(!repo) globalOrLocal = '--global';
  2096. else globalOrLocal = '--local'
  2097. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(callsheltask)).then((result)=>{
  2098. // not yet configured.
  2099. if(!result.success) return onNoResult()
  2100. else {
  2101. var users = result.messages[0].trim().split('\n');
  2102. if(users.length === 0 ||
  2103. users.length === 1 && users[0] === 'guest') {
  2104. return onNoResult()
  2105. }
  2106. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  2107. }
  2108. })
  2109. .catch((e)=>{
  2110. console.log(e)
  2111. return onNoResult()
  2112. })
  2113. }
  2114. }
  2115. ,
  2116. {
  2117. shellcmd: 'node',
  2118. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  2119. , installer: 'node-v14.16.0-x64.msi'
  2120. , installcmd: ['MSIEXEC.exe', ['/i'
  2121. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  2122. , 'ACCEPT=YES', '/passive']]
  2123. , install : function() { return any([this.installcmd].map(callsheltask)).then(() => { }) }
  2124. }
  2125. ]
  2126. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  2127. function ensureDirectoryExistence(filePath) {
  2128. var dirname = path.dirname(filePath);
  2129. if (fs.existsSync(dirname)) {
  2130. return filePath;
  2131. }
  2132. ensureDirectoryExistence(dirname);
  2133. fs.mkdirSync(dirname);
  2134. return filePath;
  2135. }
  2136. var mainTasks = [];
  2137. function verifyAndInstallPrerequisites() {
  2138. fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
  2139. // PB : TODO include and build from files... using rollup..
  2140. var downloadbatch =
  2141. `::**************************************************************************
  2142. :Download_ <url> <File>
  2143. Powershell.exe ^
  2144. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  2145. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  2146. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  2147. exit /b
  2148. ::**************************************************************************`
  2149. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch)
  2150. var windowselevate =
  2151. `
  2152. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  2153. <script language="vbscript">
  2154. document.title = "elxr control panel"
  2155. self.ResizeTo 200,600
  2156. Sub Window_Onload
  2157. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  2158. End Sub
  2159. Set objShell = CreateObject("WScript.Shell")
  2160. Set objENV = objShell.Environment("Process")
  2161. dim NODE_ENV
  2162. NODE_ENV = objENV("NODE_ENV")
  2163. </script>
  2164. <script language="javascript">
  2165. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  2166. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  2167. // alert(windowselevate.commandLine)
  2168. var args = windowselevate.commandLine.split('"').slice(3);
  2169. // alert(args)
  2170. var processedArgs = { _ : [] }
  2171. var namedArgs = [];
  2172. for(var item in args){
  2173. if(args[item].charAt(0) === '-'){
  2174. namedArgs.push(args[item])
  2175. var split = args[item].split('=');
  2176. processedArgs[split[0].slice(2)] = split[1] || true;
  2177. }
  2178. else processedArgs._.push(args[item]);
  2179. }
  2180. // args = args.forEach(function(item){ })
  2181. // alert('processedArgs._ : ' + processedArgs._);
  2182. // alert(processedArgs.runas);
  2183. // PB : TODO -- Convert all the cli args back to string.
  2184. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  2185. // alert(cargs)
  2186. var shell = new ActiveXObject('shell.application');
  2187. // alert('launching node privilged. ' + processedArgs['nodepath'])
  2188. // shell.ShellExecute('where', 'node', '', '', 10);
  2189. shell.ShellExecute('node', cargs, '', 'runas', 1);
  2190. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  2191. var fso = new ActiveXObject('Scripting.FileSystemObject');
  2192. window.onload = function() {
  2193. document.body.style.backgroundColor = 'black';
  2194. document.body.style.fontFamily = 'arial';
  2195. var log = document.createElement('div');
  2196. log.innerHTML='Please Wait';
  2197. function l(msg){ log.innerHTML+= msg; };
  2198. log.style.color = 'blue';
  2199. log.style.width = '95%';
  2200. log.id = 'log';
  2201. document.body.appendChild(log);
  2202. l('<Br/>Current config : ')
  2203. l('<Br/>NODE_ENV = ' + NODE_ENV)
  2204. l('<Br/>cmd = ' + processedArgs._[0])
  2205. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  2206. l('<Br/><Br/>')
  2207. var timer = function(){
  2208. l('.');
  2209. if(fso.FileExists("run.done")) close();
  2210. else window.setTimeout(timer, 1000);
  2211. };
  2212. window.setTimeout(timer, 3000);
  2213. };
  2214. </script>
  2215. </html>
  2216. `
  2217. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate)
  2218. var downloadtasks = [];
  2219. var installtasks = [];
  2220. prerequisites.forEach(preq => {
  2221. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  2222. if (exists) console.log(`${preq.shellcmd} exists`)
  2223. else {
  2224. console.log(`${preq.shellcmd} is not installed`)
  2225. return preq.preinstallsteps.call(preq).then(() => {
  2226. installtasks.push(preq.install.bind(preq))
  2227. })
  2228. }
  2229. }))
  2230. })
  2231. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  2232. }
  2233. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  2234. return {
  2235. get (){
  2236. return cli.prompt( promptable.choices, promptable.label, promptable.defaultchoice ).then(propValue => {
  2237. var asyncprop = Promise.resolve(propValue)
  2238. if(promptable.interpret){
  2239. asyncprop = promptable.interpret(propValue)
  2240. }
  2241. return asyncprop.then(
  2242. ()=>{
  2243. Object.defineProperty(this, propName, {
  2244. value: propValue,
  2245. writable: true,
  2246. configurable : true,
  2247. enumerable : true
  2248. });
  2249. return propValue
  2250. }
  2251. )
  2252. })
  2253. }
  2254. // , set (propValue){
  2255. // Object.defineProperty(this, propName, {
  2256. // value: propValue,
  2257. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  2258. // configurable : true,
  2259. // enumerable : true
  2260. // })
  2261. // return propValue;
  2262. // }
  2263. , configurable : true
  2264. , enumerable : true
  2265. }
  2266. }
  2267. function acquirelocalinstances(selected){
  2268. // utils.assign is used to cleanup duplicates...
  2269. var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
  2270. return chessinstances
  2271. }
  2272. function findlocalinstances(chessinstances, instanceoptions){
  2273. // We can expect a .elxr at each level.
  2274. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../..' /* instanceNames */].
  2275. earlyreduce( ( value, p, i, a )=>{
  2276. var localinstancesPath = `${instanceroot}/${p}.elxr`;
  2277. if(existsSync( localinstancesPath )) {
  2278. try {
  2279. var chessinstances = acquirelocalinstances( { localinstancesPath } )
  2280. return Object.keys(chessinstances).earlyreduce( ( value, instanceName) => {
  2281. return Object.keys(chessinstances[instanceName]).earlyreduce( (value, instanceType) => {
  2282. if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize( instanceroot) ) {
  2283. instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType])
  2284. return {
  2285. value : chessinstances[instanceName][instanceType]
  2286. , done : true
  2287. };
  2288. }
  2289. })
  2290. })
  2291. }
  2292. catch(e){
  2293. return { }
  2294. }
  2295. }
  2296. else return { }
  2297. }
  2298. )
  2299. }
  2300. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  2301. var selectedinstance = null;
  2302. var chessinstances = { current_run : {} };
  2303. var promptkeys = {
  2304. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  2305. // 'instanceName' : true
  2306. // , 'node_env' : true
  2307. }
  2308. function createChessInsance( cfg ){
  2309. var inst = {};
  2310. var __new = Object.assign({}, __default, cfg)
  2311. inst[cfg.node_env] = __new; return inst;
  2312. }
  2313. acquireElevationState().then(() => {
  2314. var skipprerequisites = false;
  2315. function initinstances(selected_overrides) {
  2316. var root = selected_overrides.root // We should always have this coz we are running at some place which is fixed by detectinstances.
  2317. var instanceName = selected_overrides.instanceName
  2318. || clioverrides.instanceName
  2319. // || processedArgs._[1]
  2320. || chessinstances.current_run.instanceName
  2321. var node_env = selected_overrides.node_env
  2322. || clioverrides.node_env
  2323. // || processedArgs.node_env
  2324. || chessinstances.current_run.node_env
  2325. var reposerver = selected_overrides.reposerver
  2326. || clioverrides.reposerver
  2327. // || processedArgs.node_env
  2328. || chessinstances.current_run.reposerver
  2329. if(!instanceName) {
  2330. promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  2331. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  2332. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  2333. }
  2334. if(!node_env) {
  2335. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  2336. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  2337. }
  2338. if(!reposerver) {
  2339. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  2340. }
  2341. chessinstances[instanceName] = chessinstances[instanceName] || createChessInsance( {
  2342. instanceName, node_env, root : selected_overrides.root, reposerver : promptkeys['reposerver'] } );
  2343. chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root }
  2344. if(path.normalize(selected_overrides.root) !== path.normalize(chessinstances[instanceName][node_env].root)) {
  2345. throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selected_overrides.root
  2346. }
  2347. // Override sequence.
  2348. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  2349. selectedinstance = utils.assign(
  2350. chessinstances[instanceName][node_env]
  2351. , clioverrides
  2352. , selected_overrides
  2353. // , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
  2354. );
  2355. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  2356. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  2357. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  2358. // // Brand New.
  2359. // selectedinstance = Object.assign( __default, selectedinstance )
  2360. // }
  2361. if(!selectedinstance.repos[0].repo) {
  2362. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  2363. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  2364. }
  2365. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  2366. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  2367. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  2368. }
  2369. // Config from server always override merges into selection except for the current selection.
  2370. // PB : TODO -- utils.assign Array merges are non-distinct...
  2371. chessinstances[instanceName][node_env] = selectedinstance;
  2372. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  2373. cacheWriteInstanceConfig(chessinstances)
  2374. // PB : TODO -- We should probably write the new server config also...
  2375. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  2376. return chessinstances
  2377. }
  2378. var noprerequisites = {
  2379. add : true, 'set-url' : true, 'repo-relocate' : true
  2380. , remote : true
  2381. }
  2382. var skipprereqs = {}
  2383. var maintask = () => {
  2384. // Default cmd to run !
  2385. processedArgs._[0] === processedArgs._[0] || 'pull';
  2386. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  2387. if(!noprerequisites[processedArgs._[0]]
  2388. && !skipprereqs[processedArgs._[0]]
  2389. ) {
  2390. return prerequisites.git.verifyAndInstall().then(()=>{
  2391. var e = { message : 'verifyAndInstall', success : true}
  2392. return acquireConfig(selectedinstance).catch((err) => {
  2393. e = err;
  2394. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  2395. console.error(err)
  2396. }).then(() => { preworkerconfig(); return elxrworker(true) })
  2397. // .finally(()=>{
  2398. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  2399. // if(!e.success) fs.writeFileSync('run.done', 'error');
  2400. // // return process.exit()
  2401. // })
  2402. })
  2403. }
  2404. else {
  2405. console.log('cmd has no preqs or has been configured to skip preqs')
  2406. preworkerconfig()
  2407. return elxrworker()
  2408. }
  2409. }
  2410. const retaincount = 2
  2411. var min = runtimestamp;
  2412. var collect = []
  2413. if(noprerequisites[processedArgs._[0]]
  2414. || skipprereqs[processedArgs._[0]]
  2415. ) {
  2416. return elxrworker()
  2417. }
  2418. var getchoices = function(detectedinstanceoptions, promptkeys){
  2419. var instances = []
  2420. var reposervers = [];
  2421. var instnaceNames = []
  2422. var instanceTypes = ['development', 'production'];
  2423. Object.keys( chessinstances).forEach(instanceName => {
  2424. if(instanceName === 'current_run') return;
  2425. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  2426. var instance = chessinstances[instanceName][node_env];
  2427. reposervers = reposervers.concat(instance.reposervers)
  2428. if(instance.reposerver) reposervers.push(instance.reposerver)
  2429. instances.push(instance)
  2430. instanceTypes.push(instance.node_env)
  2431. instnaceNames.push(instance.instanceName)
  2432. })
  2433. })
  2434. instances = instances.concat(detectedinstanceoptions)
  2435. if(selectedinstance['instanceName']) instnaceNames.push(selectedinstance['instanceName'])
  2436. if(promptkeys['instanceName']) instnaceNames.push(promptkeys['instanceName'])
  2437. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers'])
  2438. var choices = {
  2439. 'instanceName' : Array.from( new Set(instnaceNames) )
  2440. , 'reposerver' : Array.from( new Set(reposervers) )
  2441. , 'instanceType' : Array.from( new Set(instanceTypes) )
  2442. }
  2443. return choices;
  2444. }
  2445. return detectinstances().then((detectedinstanceoptions)=>{
  2446. detectedinstanceoptions.splice(0,0, __default)
  2447. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  2448. selectedinstance = utils.assign( ...detectedinstanceoptions.slice(-2) )
  2449. // promptkeys = utils.assign(promptkeys, clioverrides)
  2450. try {
  2451. chessinstances = acquirelocalinstances(selectedinstance);
  2452. findlocalinstances(chessinstances, detectedinstanceoptions)
  2453. initinstances(selectedinstance) // use the local instances for defaults if at all possible.
  2454. var choices = getchoices(detectedinstanceoptions, promptkeys)
  2455. var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  2456. return initinstances(selectedinstance)
  2457. })
  2458. }
  2459. catch (e) {
  2460. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  2461. var choices = getchoices(detectedinstanceoptions, promptkeys)
  2462. var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  2463. return initinstances(selectedinstance)
  2464. })
  2465. // if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  2466. // // Weve not been told what to do.
  2467. // todo = todo.then(() => { return acquireChoices(selectedinstance) })
  2468. // }
  2469. todo = todo.then(() => {
  2470. try {
  2471. chessinstances = acquirelocalinstances(selectedinstance)
  2472. findlocalinstances(chessinstances, detectedinstanceoptions)
  2473. detectedinstanceoptions.splice(0,0, __default)
  2474. initinstances(selectedinstance)
  2475. }
  2476. catch (e) {
  2477. console.error(e)
  2478. console.log('No local instances config found in current root = ' + selectedinstance.root);
  2479. console.log('A config will be createed with the instance and environment chosen...')
  2480. // return (async ()=>{return await __default.reposerver})().then(()=>{
  2481. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  2482. // return selectedinstance = Object.assign(__default, selectedinstance);
  2483. // })
  2484. return selectedinstance
  2485. }
  2486. })
  2487. }
  2488. return todo
  2489. })
  2490. .then(()=>{
  2491. if(!__isElevated) {
  2492. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`)
  2493. // collect garbage
  2494. return dirs( (dir)=>{
  2495. var matches = /run-(.*)/gm.exec(dir.name)
  2496. if(matches) {
  2497. if(+(matches[1]) < min) {
  2498. min = matches[1]
  2499. collect.splice( 0, 0, matches[1] )
  2500. }
  2501. else collect.push(matches[1])
  2502. }
  2503. }, `${selectedinstance.root}/.elxr` ).then(()=>{
  2504. // delete garbage
  2505. if(collect.length > retaincount) {
  2506. var asyncs = [];
  2507. while((collect.length - asyncs.length) > retaincount) {
  2508. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  2509. }
  2510. return Promise.all(asyncs)
  2511. }
  2512. else return true
  2513. })
  2514. }
  2515. else return true;
  2516. })
  2517. .then(()=>{
  2518. // PB : TODO -- Keep only the last n runs...
  2519. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  2520. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
  2521. if (!skipprerequisites && !__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
  2522. mainTasks.push(maintask)
  2523. return any(mainTasks);
  2524. })
  2525. })
  2526. // detect if alread installed -> Take no action.
  2527. // download if no installer avalable -> next()
  2528. // install
  2529. function chackandinstall(items) {
  2530. var tasks = []
  2531. items.forEach(item => {
  2532. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  2533. })
  2534. return Promise.all(tasks).then(existances => {
  2535. existances.forEach((exists, i) => {
  2536. if (!exists) {
  2537. return downloadandinstall([items[i]])
  2538. }
  2539. })
  2540. })
  2541. }
  2542. function downloadandinstall(items) {
  2543. var tasks = []
  2544. items.forEach(item => {
  2545. tasks.push(getTaskDownload(item))
  2546. })
  2547. return Promise.all(tasks)
  2548. }
  2549. // Sample instances config.
  2550. // var instances = {
  2551. // "elixir": {
  2552. // "production": {
  2553. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  2554. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  2555. // , "exludeMergeRepos": {
  2556. // "elixir-config-development": true, "elixir-config-test": true
  2557. // , "elixir-config-production": true, "elixir-data": true
  2558. // }
  2559. // , "instanceName": "elixir", "node_env": "production"
  2560. // }
  2561. // },
  2562. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  2563. // }
  2564. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...