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

index.js 164KB

3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
2 lat temu
3 lat temu
2 lat temu
2 lat temu
2 lat temu
3 lat temu
2 lat temu
3 lat temu
2 lat temu
3 lat temu
4 lat temu
3 lat temu
3 lat temu
2 lat temu
5 lat temu
3 lat temu
3 lat temu
3 lat temu
2 lat temu
2 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
2 lat temu
3 lat temu
2 lat temu
3 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
2 lat temu
2 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
5 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
3 lat temu
2 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
2 lat temu
3 lat temu
2 lat temu
3 lat temu
3 lat temu
3 lat temu
5 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
2 lat temu
2 lat temu
2 lat temu
2 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
2 lat temu
2 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
2 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
2 lat temu
3 lat temu
2 lat temu
2 lat temu
3 lat temu
2 lat temu
3 lat temu
3 lat temu
3 lat temu
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334
  1. global.env = process.env
  2. global.env.NODE_ENV = global.env.NODE_ENV || 'development'
  3. const fs = require('fs')
  4. var path = require('path');
  5. var utils = require('bbhverse');
  6. var any = utils.any;
  7. var Tasq = utils.Tasq
  8. var statuslog = utils.Traq
  9. var Traq = utils.Traq
  10. Tasq.addlistener(statuslog.statuslog)
  11. fs.writeFileSync('run.log', ', ' + JSON.stringify( { m : 'Hello'} ), { 'flag': 'a+' })
  12. Tasq.addlistener((e)=>{ fs.writeFileSync('run.log', ', ' + JSON.stringify( e ), { 'flag': 'a+' }) })
  13. var cli = require('./cliverse')
  14. function isWin(){ return /^win/.test(process.platform) }
  15. if(isWin()) {
  16. var win_verse = require('./win_verse')
  17. var shell_verse = win_verse;
  18. }
  19. else {
  20. var lin_verse = require('./lin_verse')
  21. var shell_verse = lin_verse;
  22. }
  23. var nodeShellExec = cli.nodeShellExec;
  24. var chalk = require('chalk')
  25. const homedir = require('os').homedir();
  26. function sysAddPathVar(addpath){
  27. // Object.assign({
  28. // inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  29. // }, options)
  30. // powershell $env:Path -split ';'
  31. var etask = ()=>{
  32. return nodeShellExec('Powershell.exe', [
  33. `$path = [Environment]::GetEnvironmentVariable('PATH', 'Machine')
  34. $newpath = $path + ';${addpath}'
  35. [Environment]::SetEnvironmentVariable("PATH", $newpath, 'Machine')`
  36. ]).then(() => {
  37. fs.writeFileSync('run.done', 'success')
  38. }).catch(() => {
  39. fs.writeFileSync('run.done', 'error')
  40. })
  41. }
  42. etask.statuslog = statuslog
  43. etask.selectedinstance = selectedinstance
  44. etask.processedArgs = processedArgs
  45. etask.runtimestamp = runtimestamp
  46. etask.ENV = ENV
  47. return shell_verse.runElevated(etask)
  48. // var newpath = addpath.split(';');
  49. // newpath.push(addpath)
  50. // newpath = Array.from(new Set(newpath)).join(';')
  51. // // addpath.split(';').forEach(pel => { var kv = pel.split('='); kv[0] === key ? null : newpath.push(pel); } )
  52. // // setx /M PATH "%PATH%;<path-to-executable-folder>"
  53. // // %AppData%\npm
  54. // return nodeShellExec('setx', ['/m', 'PATH', `%PATH%;${addpath}` ]);
  55. }
  56. // singleton one time lazy
  57. var getCredentials = function(){
  58. // First call
  59. var creds = fs.readFileSync(path.normalize(`${homedir}/.elxrcredentials`), { encoding: 'utf8' });
  60. var creds = creds.split('\n').map( c => c.trim() && new URL(c));
  61. console.log(creds);
  62. creds.forEach(cred => {console.log( cred.hostname ); console.log( cred.username )} );
  63. // Subsequent calls
  64. getCredentials = ()=>{ return creds }
  65. return getCredentials();
  66. }
  67. function getCurrentFolder(){
  68. var tasks = [
  69. // () => {
  70. // // Use junctions to avoid npm package issues
  71. // var p = nodeShellExec('cd').then((result)=>{
  72. // console.dir(result)
  73. // }).catch((e) => { console.error(e) })
  74. // return p;
  75. // }
  76. ()=>{
  77. return Promise.resolve(process.cwd())
  78. }
  79. ];
  80. return any(tasks);
  81. }
  82. const __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b'
  83. const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  84. const runtimestamp = (new Date()).getTime();
  85. function getVersion() { return BUILD_VERSION; }
  86. console.log(getVersion());
  87. // 'use strict';
  88. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  89. // PB : TODO --
  90. // runas bypass non elevated tasks when we request privelege
  91. // runas message is always error needs to be fixed.
  92. // runas wait needs to be parallelized.
  93. // suppress elevation check error messages
  94. // support runas lauched directly from shell.
  95. // pass in environment in hta to shellexecute.
  96. // PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
  97. (function () {
  98. "use strict";
  99. if (!Array.prototype.earlyreduce) {
  100. Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
  101. var iterable = this;
  102. var donecallback = donecallback || (a=>a)
  103. var result = { value : initialValue === undefined ? iterable[0] : initialValue };
  104. initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
  105. // function *earlyReduceGenerator(acc, v, i, a) {
  106. for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
  107. var element = iterable[i]
  108. result = eachcallback(result, element, i, iterable)
  109. if(result.done) return donecallback(result)
  110. }
  111. // }
  112. return donecallback(result)
  113. }
  114. }
  115. }());
  116. const { existsSync } = require('fs');
  117. const existslink = function(name, cb){
  118. fs.lstat(name, (error, stats) => {
  119. if (error) {
  120. console.log(error);
  121. cb(error)
  122. }
  123. else {
  124. console.log("Stats object for: example_directory.txt");
  125. console.log(stats);
  126. // Using methods of the Stats object
  127. console.log("Path is file:", stats.isFile());
  128. console.log("Path is directory:", stats.isDirectory());
  129. cb(null, true)
  130. }
  131. });
  132. }
  133. const existsFolderSync = existsSync;
  134. const cliargs = utils.cliargs;
  135. const processedArgs = cliargs(process.argv.slice(2));
  136. if(!processedArgs.wd){
  137. if(process.env.wd){
  138. }
  139. else {
  140. process.env.wd = process.cwd();
  141. if(process.cwd() === __dirname) {
  142. // This script was launched in the same dir.
  143. // We do not know if it was copied to some random location. Check if we have elxr installed in current location. Or subidr.
  144. process.env.wd = path.dirname( process.env.wd ); // Default to the parent.
  145. }
  146. }
  147. }
  148. else process.env.wd = processedArgs.wd
  149. var ENV = Object.assign({}, process.env); // Shallow clone it.
  150. console.dir(processedArgs)
  151. // PB : TODO -- defaults for valuless arguments if passed.
  152. // Object.keys(processedArgs).forEach(a=>{
  153. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  154. // }
  155. // })
  156. //
  157. // Object.keys(clioverrides).forEach( prop => { })
  158. var globSync = require('glob').sync;
  159. const { readdir } = require("fs").promises
  160. // Directory shallow walk and do perform on each dir.
  161. const dirs = async (perform, path) => {
  162. for (const dir of await readdir(path || selectedinstance.root, { withFileTypes: true })) {
  163. if (dir.isDirectory()) perform(dir)
  164. }
  165. }
  166. var templateprocess = function(str, substitutes){
  167. const regex = /__(.*?)__/gm;
  168. // const str = `__link____instance__server-lib__name__`;
  169. let m;
  170. return str.replace(regex, function(match, key) {
  171. console.log(`Found match, group ${match}: ${key}`);
  172. return substitutes[key] || match;
  173. })
  174. // while ((m = regex.exec(str)) !== null) {
  175. // // This is necessary to avoid infinite loops with zero-width matches
  176. // if (m.index === regex.lastIndex) {
  177. // regex.lastIndex++;
  178. // }
  179. // var rstr = str;
  180. // // The result can be accessed through the `m`-variable.
  181. // m.forEach((match, groupIndex) => {
  182. // // rstr = rstr.replace( groupIndex
  183. // console.log(`Found match, group ${groupIndex}: ${match}`);
  184. // if(groupIndex === 0) return
  185. // });
  186. // }
  187. }
  188. function copyFileSync( source, target , options) {
  189. var targetFile = target;
  190. // If target is a directory, a new file with the same name will be created
  191. if ( fs.existsSync( target ) ) {
  192. if ( fs.lstatSync( target ).isDirectory() ) {
  193. targetFile = path.join( target, path.basename( source ) );
  194. }
  195. }
  196. fs.writeFileSync(targetFile, fs.readFileSync(source));
  197. }
  198. function copyFolderRecursiveSync( source, target, options ) {
  199. var files = [];
  200. // Check if folder needs to be created or integrated
  201. var targetFolder = path.join( target, path.basename( source ) );
  202. if ( !fs.existsSync( targetFolder ) ) {
  203. fs.mkdirSync( targetFolder );
  204. }
  205. // Copy
  206. if ( fs.lstatSync( source ).isDirectory() ) {
  207. files = fs.readdirSync( source );
  208. files.forEach( function ( file ) {
  209. var curSource = path.join( source, file );
  210. if ( fs.lstatSync( curSource ).isDirectory() ) {
  211. copyFolderRecursiveSync( curSource, targetFolder );
  212. } else {
  213. copyFileSync( curSource, targetFolder );
  214. }
  215. } );
  216. }
  217. }
  218. var getShellTask = (command, args, options) => {
  219. options = options || {}
  220. var callshell = command === 'rm' ? getgitbashtask : getshelltask;
  221. return () => {
  222. var p = callshell( [command, args, Object.assign({
  223. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  224. }, options)
  225. ])()
  226. if (options.ignorefailures) {
  227. return p.catch(e => {
  228. // Ignore. Not a major error.
  229. })
  230. }
  231. else return p;
  232. }
  233. }
  234. var callshelltask = (args) => {
  235. // console.dir(args)
  236. if( Object.prototype.toString.call(args) === '[object Function]' ) {
  237. return args;
  238. }
  239. return getshelltask(args)()
  240. }
  241. var getCmdString = function(args){ return `"${args[0]} ${args[1].join(' ')}"` }
  242. var getshelltask = (args) => {
  243. return args[0] === 'rm' ? getgitbashtask(args) : () => { return nodeShellExec.apply(null, args) } }
  244. var getgitbashtask = (args, onEachError) => { return () => {
  245. return nodeShellExec( `"${gitbash}"`, ['-c', getCmdString(args)], args[2]).catch( onEachError || function(e){ console.error(e) }) }
  246. }
  247. var getTaskCheckExists = shell_verse.getTaskCheckExists
  248. // var getTaskWithElevation = function(tasdef){ return shell_verse.getElevatedTask( tasdef.elevatedpulltasks ) }
  249. // var getTaskWithoutElevation = function(tasdef){
  250. // return ()=>{
  251. // if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  252. // else Promise.resolve(true)
  253. // }
  254. // }
  255. var gitops = {
  256. getdiscoverbranchcmd : function(repo){
  257. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  258. var cmd = [gitbash
  259. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  260. , { cwd: instanceroot + '/' + repo, title: 'discoverbranch for ' + repo + ' ' + parameters.join(' ') }]
  261. return cmd
  262. }
  263. }
  264. var getPullCmd = (repo, branch) => {
  265. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  266. // console.log(useGitPull)
  267. var pullCmd = []
  268. if(!branch) {
  269. // console.warn('No branch was specified detecting from working client.')
  270. // First check if working client exists.
  271. // if (existsSync(instanceroot + '/' + repo)) {
  272. pullCmd= gitops.getdiscoverbranchcmd(repo)
  273. // }
  274. // else performpull
  275. }
  276. // var pullCmd = [gitInstallDir
  277. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  278. // , { cwd: instanceroot + '/' + repo, title: 'pull all remotes for ' + repo }]
  279. if(branch) {
  280. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  281. var pullCmd = [ gitbash
  282. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  283. , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  284. }
  285. // var pullCmd = ['pullall', [], { cwd : repo }]
  286. if (useGitPull) pullCmd = ['git', ['pull'], {
  287. inherit: true, shell: true,
  288. cwd: instanceroot + '/' + repo
  289. // , env: process.env
  290. , runas: processedArgs.runas
  291. , title: `git pull ${repo}`
  292. }]
  293. return pullCmd
  294. }
  295. // PB : TODO -- Use queueing with async tasks..
  296. var performPull = (repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch) => {
  297. var __inelevatedBatch = elevatedBatch, __inregularBatch = regularBatch;
  298. var pT = getPullTask(repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch)
  299. // var waitForBatchAdditions = function(){
  300. // return pT;
  301. // }
  302. // Execute is implied.
  303. // if(false && (__inelevatedBatch || __inregularBatch) ) return waitForBatchAdditions() // PB : Todo Implemnt a trigger which starts execution.
  304. // else
  305. return pT() // Execute it.
  306. }
  307. var getPullTask = (repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch) => {
  308. // PB : TODO -- Handle no branch passed in case.
  309. // if(!branch) { throw 'No branch specified' }
  310. var repo = repodef.repo;
  311. elevatedBatch = elevatedBatch || [];
  312. regularBatch = regularBatch || [];
  313. try{
  314. var exists = existsSync(instanceroot + '/' + repo)
  315. }
  316. catch(e){
  317. exists = false
  318. console.log(e)
  319. }
  320. function initTask(etask){
  321. etask.info = { repo }
  322. etask.errHandler = errHandler
  323. etask.statuslog = statuslog
  324. etask.processedArgs = processedArgs
  325. etask.selectedinstance = selectedinstance
  326. etask.runtimestamp = runtimestamp
  327. etask.ENV = ENV
  328. elevatedBatch.info = { repo }
  329. elevatedBatch.errHandler = errHandler
  330. elevatedBatch.statuslog = statuslog
  331. elevatedBatch.processedArgs = processedArgs
  332. elevatedBatch.selectedinstance = selectedinstance
  333. elevatedBatch.runtimestamp = runtimestamp
  334. elevatedBatch.ENV = ENV
  335. }
  336. if (exists) {
  337. var branchprint = branch ? ' branch :' + branch : '';
  338. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  339. var task = ()=>{
  340. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  341. return true;
  342. })
  343. }
  344. initTask(task)
  345. if(repodef.requiresElevation) {
  346. elevatedBatch.push(shell_verse.getElevatedTask( task ));
  347. return elevatedBatch[elevatedBatch.length-1]
  348. }
  349. else {
  350. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  351. return regularBatch[regularBatch.length-1]
  352. }
  353. }
  354. else {
  355. console.log('cloning ' + repo)
  356. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  357. var task = ()=>{
  358. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${repoowner || defaultRepoOwner}/` + repo + '.git'],
  359. {
  360. inherit: true, shell: true,
  361. env: process.env
  362. , cwd : instanceroot
  363. , runas: processedArgs.runas
  364. }).then(() => {
  365. var task = ()=>{
  366. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  367. {
  368. inherit: true, shell: true,
  369. env: process.env
  370. , cwd: instanceroot + '/' + repo
  371. , runas: processedArgs.runas
  372. , title: `'git', ${['config', '--replace-all', 'core.symlinks', selectedinstance.username].join(' ')}`
  373. })
  374. }
  375. initTask(task)
  376. if(repodef.requiresElevation) {
  377. elevatedBatch.push(shell_verse.getElevatedTask( task ));
  378. return elevatedBatch[elevatedBatch.length-1]
  379. }
  380. else {
  381. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  382. return regularBatch[regularBatch.length-1]
  383. }
  384. })
  385. }
  386. initTask(task)
  387. if(repodef.requiresElevation) {
  388. elevatedBatch.push(shell_verse.getElevatedTask( task ));
  389. return elevatedBatch[elevatedBatch.length-1]
  390. }
  391. else {
  392. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  393. return regularBatch[regularBatch.length-1]
  394. }
  395. }
  396. }
  397. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current GITEA username
  398. var defaultRepoOwner = 'chess';
  399. var elevatedRunasRepos = null
  400. var gitRepos = null
  401. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  402. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  403. var dbForLabel = function (label) {
  404. var dbsForLabel = {
  405. devmysql: 'mysql'
  406. , development: 'mssql'
  407. , production: 'mssql'
  408. }
  409. return dbsForLabel[label] || 'mysql'
  410. }
  411. // SAM : TODO Use nodeshellexec where to detect git installation dir
  412. var gitbash = shell_verse.getbash()
  413. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  414. // Relevant git repos
  415. var exludeMergeRepos = [];
  416. var useGitPull = processedArgs.useGitPull || false;
  417. var configPromise = null
  418. var op = {
  419. 'h': () => { console.log(elxr.help()); return '-h' }
  420. , 'clean' : () => {
  421. // delete all node_module folders and links.
  422. var tasklist = [];
  423. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot )
  424. return Promise.all(tasklist)
  425. }
  426. // , 'undefined': () => { return acquireChoices( {} ); }
  427. , 'reset': () => {
  428. // Reset NPM packages semver so major versions can be updated.
  429. const fs = require('fs')
  430. const wipeDependencies = (__package) => {
  431. const file = fs.readFileSync(__package + '/package.json')
  432. const content = JSON.parse(file)
  433. for (var devDep in content.devDependencies) {
  434. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  435. content.devDependencies[devDep] = '*';
  436. }
  437. }
  438. for (var dep in content.dependencies) {
  439. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  440. content.dependencies[dep] = '*';
  441. }
  442. }
  443. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  444. }
  445. var repos = ['client'];
  446. // repos = gitRepos;
  447. repos.forEach(wipeDependencies)
  448. // if (require.main === module) {
  449. // } else {
  450. // module.exports = wipeDependencies
  451. // }
  452. }
  453. , 'upgrade': () => {
  454. console.log('upgrade.......')
  455. var tasks = [
  456. () => {
  457. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  458. inherit: true, shell: true
  459. , env: process.env
  460. }).catch((e) => { console.error(e) })
  461. p.position = 1;
  462. console.log('One')
  463. return p;
  464. }
  465. , () => {
  466. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  467. inherit: true, shell: true
  468. , env: process.env
  469. }).catch((e) => { console.error(e) })
  470. p.position = 2;
  471. console.log('Two')
  472. return p;
  473. }
  474. , () => {
  475. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  476. inherit: true, shell: true
  477. , env: process.env
  478. }).catch((e) => { console.error(e) })
  479. p.position = 3;
  480. console.log('Three')
  481. return p;
  482. }
  483. , () => {
  484. var p = nodeShellExec('n', ['latest'], {
  485. inherit: true, shell: true
  486. , env: process.env
  487. }).catch((e) => { console.error(e) })
  488. p.position = 4;
  489. console.log('Four')
  490. return p;
  491. }
  492. ]
  493. any(tasks)
  494. console.log('.......done')
  495. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  496. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  497. console.info('Uninstalling existing ember globally');
  498. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  499. stdio: ['pipe', process.stdout, process.stderr],
  500. inherit: true,
  501. shell: true,
  502. cwd: path.dirname(__dirname),
  503. env: env
  504. })
  505. step1.on('close', () => {
  506. console.info('Installing ember globally');
  507. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  508. stdio: ['pipe', process.stdout, process.stderr],
  509. inherit: true,
  510. shell: true,
  511. cwd: path.dirname(__dirname),
  512. env: env
  513. })
  514. step2.on('close', () => {
  515. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  516. stdio: ['pipe', process.stdout, process.stderr],
  517. inherit: true,
  518. shell: true,
  519. cwd: path.dirname(__dirname),
  520. env: env
  521. })
  522. })
  523. })
  524. }
  525. , 'push': () => {
  526. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  527. // init remote bare from local
  528. // pushandinitremotebare
  529. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  530. // connect to repo server -- net use 172.16.0.27
  531. // cd 172.16.0.27/repos/
  532. // mkdir repo.git
  533. // cd repo.git
  534. // git init --bare
  535. // cd localrepo
  536. // git remote rename origin githubclone
  537. // git remote add origin //172.16.0.27/repos/repo.git
  538. // git push origin master
  539. var repo = processedArgs._[1];
  540. var sequentialTaskShellCommands = [];
  541. if (!existsSync(`Z:/${repo}.git`)) {
  542. sequentialTaskShellCommands = [
  543. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  544. // inherit : true, shell: true
  545. // , env: process.env
  546. // }]
  547. ['pwd', { cwd: 'Z:', inherit: true }]
  548. , ['mkdir', [`${repo}.git`], {
  549. cwd: `Z:`
  550. , inherit: true, shell: true
  551. , env: process.env
  552. }]
  553. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  554. , ['git', ['init', '--bare'], {
  555. cwd: `Z:/${repo}.git`
  556. , inherit: true, shell: true
  557. , env: process.env
  558. }]
  559. // PB : TODO -- Do this conditionally only...
  560. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  561. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  562. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  563. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  564. // PB : TODO -- If threre is a gitbubclone origin
  565. // Set the master to pull from the local repo.
  566. ]
  567. if (!existsSync(`Z:`)) {
  568. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  569. inherit: true, shell: true
  570. , env: process.env
  571. }])
  572. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  573. // throw 'done'
  574. }
  575. }
  576. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }])
  577. // console.dir(sequentialTaskShellCommands);
  578. var tasks = [];
  579. sequentialTaskShellCommands.forEach(shellcmd => {
  580. // console.log(shellcmd)
  581. tasks.push(() => {
  582. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
  583. return p;
  584. })
  585. })
  586. any(tasks);
  587. }
  588. , 'is-git-repo': (dir) => {
  589. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  590. }
  591. // git remote equivalents...
  592. // git branch --set-upstream-to=elixir-unc/master master
  593. // git push --set-upstream elixir-unc branch..
  594. , 'remote': (args) => {
  595. // Subcommands!
  596. // PB : TODO -- we can now pass in hypehnated args...
  597. if(!processedArgs.v) return false; // Only -v is supported presently..
  598. var serial_perform = (repo) => {
  599. var options = { cwd: instanceroot + '/' + repo }
  600. return [
  601. ['git', ['remote', '-v'], options]
  602. ]
  603. }
  604. var x = (args) => {
  605. var tasq = () => {
  606. // console.log(args)
  607. return nodeShellExec.apply(null, args).catch(e => {
  608. // We continue on failure.
  609. console.error(tasq.toString())
  610. })
  611. }
  612. tasq.toString = function(){
  613. return JSON.stringify(args)
  614. }
  615. return tasq;
  616. }
  617. var perform = (dir) => {
  618. return any(serial_perform(dir.name).map(x))
  619. }
  620. dirs(perform)
  621. }
  622. , 'remote set-url': (args) => {
  623. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  624. var __args = {
  625. remotename : args.remotename || processedArgs._[2]
  626. , url : args.url || processedArgs._[3]
  627. }
  628. // pushable doesn't mean the remote doesn't support being pushed to.
  629. // 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.
  630. // PB : TODO -- change this to enablepushing.
  631. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  632. var pushable = processedArgs.pushable || false;
  633. remotename = __args.remotename
  634. url = __args.url
  635. var serial_perform_git_seturl = (repo) => {
  636. var options = { cwd: instanceroot + '/' + repo }
  637. // console.log(repo)
  638. if (pushable) {
  639. return [
  640. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  641. , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  642. ]
  643. }
  644. else {
  645. return [
  646. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  647. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  648. ]
  649. }
  650. }
  651. var x = (args) => {
  652. var tasq = () => {
  653. // console.log(args)
  654. return nodeShellExec.apply(null, args).catch(e => {
  655. // We continue on failure.
  656. console.error(tasq.toString())
  657. })
  658. }
  659. tasq.toString = function(){
  660. return JSON.stringify(args)
  661. }
  662. return tasq;
  663. }
  664. var perform_git_seturl = (dir) => {
  665. op['is-git-repo'](dir).then((logEntry) => {
  666. return any(serial_perform_git_seturl(dir.name).map(x))
  667. }).catch((e) => {
  668. // console.log('Failed : ' + dir.name)
  669. })
  670. }
  671. dirs(perform_git_seturl)
  672. }
  673. // , 'reset' : ()=>{
  674. // PB : TODO -- Cant have 2 resets !! | There is an npm reset that should be bundled.
  675. // // Reset the whole installation pertaining to this elxr folder.
  676. // }
  677. , 'remote exists': (args) => {
  678. var __args = {
  679. remotename : args.remotename|| processedArgs._[2]
  680. , url : args.url || processedArgs._[3]
  681. , branch : args.branch || processedArgs._[4]
  682. }
  683. var options = args.repo ? { cwd: instanceroot + '/' + args.repo } : {}
  684. // PB : TODO -- We should evaluate a whole list of remotes passed in from args instead of just one.
  685. var commands = [
  686. // git remote -v| while read remote; do "${remote#origin/}" "$remote"; done
  687. // ['git', ['remote', '-v', '| while read remote; do "${remote#origin/}" "$remote"; done'], utils.assign( {
  688. ['git', ['remote', '-v'], utils.assign( {
  689. evaluateResult : function(err, result){
  690. // var found = result.messages.find( (r)=> { return r.includes( __args.remotename ) })
  691. var remotes = []
  692. var found = false;
  693. console.dir(result.messages)
  694. console.log(result + '---------------')
  695. result.messages.forEach( (line)=> {
  696. console.log(line + '$$$$$$$$$$$$$$$$$$$$')
  697. var matches = line.match(/(.*)?\s\s([^\(]*)?\s?\(?([^\)]*)\)?/);
  698. if(matches) {
  699. var remote = {};
  700. remote[matches[1]] = matches[2];
  701. if( (!matches[3].trim() || matches[3].trim() === 'fetch') && matches[1].trim() === remotename.trim()) {
  702. found = true;
  703. result.url = remote[remotename];
  704. }
  705. }
  706. })
  707. console.dir(remotes)
  708. return [
  709. found
  710. , result
  711. ]
  712. }
  713. } , options) ]
  714. , function(prevserialtaskresult) {
  715. console.log('================================')
  716. var url = __args || prevserialtaskresult.url;
  717. console.dir(prevserialtaskresult)
  718. return getshelltask(['git', ['ls-remote', url], utils.assign( {
  719. evaluateResult : function(err, result){
  720. // fatal: unable to access '${__args.url}/': Failed to connect to git.bbh port 80 after 21025 ms: Timed out
  721. // `fatal: repository '${__args.url}/' not found`
  722. var hasfailed = /^fatal: .*/.test(result.messages.join(' '))
  723. return [
  724. !hasfailed, result
  725. ]
  726. }
  727. } , options) ])()
  728. }
  729. ]
  730. var mapped = commands.map(callshelltask) //.map( p => p.catch(e => e)) // Handle errors later.
  731. return any(mapped).then( allresolved =>{
  732. console.dir(allresolved)
  733. !allresolved[0][0] && !allresolved[1][0] ? console.log('was not added as a remote and url is currently inaccessible.')
  734. : allresolved[0][0] && allresolved[1][0] ? console.log('was added as a remote and url is accessible.')
  735. : allresolved[0][0] && !allresolved[1][0] ? console.log('was added as a remote but url is currently inaccessible.')
  736. : console.log('was not added as a remote but url is currently accessible.')
  737. return !allresolved[0][0] && !allresolved[1][0] ? [0, 0]
  738. : allresolved[0][0] && allresolved[1][0] ? [1, 1] // => was added as a remote and url is accessible.
  739. : allresolved[0][0] && !allresolved[1][0] ? [1, 0] // => was added as a remote but url is currently inaccessible.
  740. : [0, 1] // => was not added and remote and url is accessible.
  741. })
  742. }
  743. , 'remote refresh': (args) => {
  744. var __args = {
  745. remotename : args.remotename|| processedArgs._[2]
  746. , url : args.url || processedArgs._[3]
  747. , branch : args.branch || processedArgs._[4]
  748. }
  749. // use the repo manifest to create missing remotes.
  750. function perform_remote_refresh(dir){
  751. var repo = dir.name
  752. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  753. try {
  754. var remotes = require(`${selectedinstance.root}/${dir.name}/repo-manifest.js`)( null, selectedinstance).remotes || [];
  755. }
  756. catch(e){
  757. var remotes = []
  758. }
  759. // console.log(`${dir.name}/repo-manifest.js` + '---------------------------')
  760. // console.dir(remotes)
  761. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  762. console.log('Processing : ' + dir.name)
  763. var branch = __branch
  764. __args.repo = repo
  765. __args.branch = __branch
  766. var promises = []
  767. remotes.forEach(remote =>{
  768. Object.keys(remote).forEach(remotename => {
  769. __args.remotename = remotename
  770. __args.url = remote[remotename]
  771. promises.push( op['remote exists']( __args ).then( exists => {
  772. if(!exists[0]) {
  773. if(!exists[1]) { console.error( `Skipping inaccessible remote url ${__args.url}` ) }
  774. else return op['remote add']( { remotename,
  775. // PB : TODO -- use the most accessible remote instead of the first available.
  776. url : (utils.js.isArray(remote[remotename]) ? remote[remotename][0] : remote[remotename]), branch
  777. } )
  778. }
  779. })
  780. )
  781. })
  782. })
  783. return Promise.all(promises)
  784. })
  785. .catch((e) => { console.log('Processing Error : ' + dir.name); console.error(e); return { error: true, message: repo } })
  786. }
  787. return dirs(perform_remote_refresh)
  788. }
  789. , 'remote add': (args) => {
  790. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  791. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  792. // That explicitly has a remote name prefix.
  793. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  794. // git branch branch_name -u your_new_remote/branch_name -- older versions
  795. // git branch -vv -- Detect which branch are we tracking.
  796. // default upstream should be users own fork.
  797. // Also need alias branches to
  798. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  799. // probably git merge from all remotes... and relevant branches...
  800. // alias pushall='for i in `git remote`; do git push $i; done;'
  801. // alias pullall='for i in `git remote`; do git pull $i; done;'
  802. // args === processedArgs ? args = {} : null;
  803. var __args = {
  804. remotename : args.remotename|| processedArgs._[2]
  805. , url : args.url || processedArgs._[3]
  806. , branch : args.branch || processedArgs._[4]
  807. }
  808. var remotename = __args.remotename
  809. var url = __args.url
  810. var branch = __args.branch
  811. var pushable = processedArgs.pushable || false;
  812. var serial_perform_git_add = (repo) => {
  813. var options = { cwd: instanceroot + '/' + repo }
  814. // console.log(repo)
  815. if (pushable) {
  816. return [
  817. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  818. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  819. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  820. ]
  821. }
  822. else {
  823. return [
  824. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  825. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  826. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  827. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  828. ]
  829. }
  830. }
  831. var x = (args) => {
  832. return () => {
  833. // console.log(args)
  834. return nodeShellExec.apply(null, args)
  835. }
  836. // return Promise.resolve(true)
  837. }
  838. var perform_git_add = (dir) => {
  839. op['is-git-repo'](dir).then((logEntry) => {
  840. // console.log(code)
  841. if (logEntry.success) {
  842. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  843. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  844. })
  845. .catch((e) => {
  846. any(serial_perform_git_add(dir.name).map(x))
  847. })
  848. }
  849. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  850. }).catch((e) => {
  851. console.log('Failed : ' + dir.name)
  852. })
  853. }
  854. const { readdir } = require("fs").promises
  855. dirs(perform_git_add)
  856. }
  857. , 'remote remove': (args) => {
  858. var __args = {
  859. remotename : args.remotename|| processedArgs._[2]
  860. }
  861. var remotename = __args.remotename
  862. var serial_perform_git_remove = (repo) => {
  863. var options = { cwd: instanceroot + '/' + repo }
  864. // console.log(repo)
  865. return [
  866. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  867. ]
  868. }
  869. var x = (args) => {
  870. return () => {
  871. // console.log(args)
  872. return nodeShellExec.apply(null, args)
  873. }
  874. // return Promise.resolve(true)
  875. }
  876. var perform_git_remove = (dir) => {
  877. op['is-git-repo'](dir).then((logEntry) => {
  878. // console.log(code)
  879. if (logEntry.success) {
  880. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  881. any(serial_perform_git_remove(dir.name).map(x))
  882. })
  883. .catch((e) => {
  884. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`)
  885. })
  886. }
  887. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  888. }).catch((e) => {
  889. // console.log('Failed : ' + dir.name)
  890. })
  891. }
  892. const { readdir } = require("fs").promises
  893. dirs(perform_git_remove)
  894. }
  895. , 'init-gitea': (user) => {
  896. user = user || processedArgs._[1]
  897. if (!user) throw 'User name required'
  898. var serial_perform_init_gitea = (repo) => {
  899. var options = { cwd: instanceroot + '/' + repo }
  900. // console.log(repo)
  901. return [
  902. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  903. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  904. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  905. ]
  906. }
  907. var x = (args) => {
  908. return () => {
  909. // console.log(args)
  910. return nodeShellExec.apply(null, args)
  911. }
  912. // return Promise.resolve(true)
  913. }
  914. var perform_init_gitea = (dir) => {
  915. op['is-git-repo'](dir).then((logEntry) => {
  916. // console.log(code)
  917. if (logEntry.success) {
  918. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  919. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  920. })
  921. .catch((e) => {
  922. any(serial_perform_init_gitea(dir.name).map(x))
  923. })
  924. }
  925. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  926. }).catch((e) => {
  927. // console.log('Failed : ' + dir.name)
  928. })
  929. }
  930. const { readdir } = require("fs").promises
  931. dirs(perform_init_gitea)
  932. }
  933. , 'syncmaster': (label) => {
  934. // Usage :
  935. // elxr pull -- Defaults to run config
  936. var env = Object.assign({}, process.env); // Shallow clone it.
  937. // console.dir(env)
  938. console.log('Running exlr pull : ' + path.dirname(__dirname))
  939. if (!processedArgs.runas) gitRepos.map((def) => performPull(def, def.branch || 'master'))
  940. var etask = ()=>{
  941. return any(elevatedRunasRepos.map((def) => performPull(def, def.branch || 'master'))).then(() => {
  942. fs.writeFileSync('run.done', 'success')
  943. }).catch(() => {
  944. fs.writeFileSync('run.done', 'error')
  945. })
  946. }
  947. etask.statuslog = statuslog
  948. etask.selectedinstance = selectedinstance
  949. etask.processedArgs = processedArgs
  950. etask.runtimestamp = runtimestamp
  951. etask.ENV = ENV
  952. return shell_verse.runElevated(etask)
  953. }
  954. , 'repo-relocate' : function(args){
  955. // relocate a subfolder in source repo to same subfolder in target repo with history.
  956. var args = args || {
  957. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  958. , folder : processedArgs._[3] || 'server'
  959. , sourcerepo : processedArgs._[2] || 'client'
  960. , targetrepo : processedArgs._[1] || 'elixir-server'
  961. }
  962. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  963. // , stdio: ['pipe', process.stdout, process.stderr]
  964. , inherit: true,
  965. shell: true,
  966. env: process.env
  967. , runas: processedArgs.runas
  968. }
  969. return op['repo-split'](args).then(()=>{
  970. return op['repo-merge'](args).then(()=>{
  971. // cleanup folder from source.
  972. var cmdseq = [
  973. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  974. // commits have to intentional...
  975. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  976. ]
  977. return any(cmdseq.map(getshelltask))
  978. })
  979. }).catch(e=>{console.error(e)})
  980. }
  981. , 'repo-split' : function(args) {
  982. // https://gist.github.com/smdabdoub/17065c348289158277b5
  983. /**
  984. * Eg : folder, remotebase, sourcerepo, targetrepo
  985. * args.folder = 'server'
  986. * args.remotebase = 'https://git.bbh/chess/'
  987. * args.sourcerepo = 'client'
  988. * args.targetrepo = 'elixir-server'
  989. */
  990. var args = args || {
  991. folder : 'server'
  992. , remotebase : 'http://git.bbh/chess/'
  993. , sourcerepo : 'client'
  994. , targetrepo : 'elixir-server'
  995. }
  996. var options = { cwd: `${instanceroot}/relocate`
  997. // , stdio: ['pipe', process.stdout, process.stderr]
  998. , inherit: true,
  999. shell: true,
  1000. env: process.env
  1001. , runas: processedArgs.runas
  1002. }
  1003. var cmdseq = [
  1004. // create a temporary working dir in current folder where we started execution.
  1005. ['mkdir', [ '-p', `${instanceroot}/relocate`]]
  1006. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  1007. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  1008. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  1009. ]
  1010. return any(cmdseq.map(getshelltask)).then(() => {
  1011. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  1012. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  1013. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  1014. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  1015. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  1016. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  1017. // subtree split and filter-branch are options. We currently use repo-filter.
  1018. return op['filter-repo'](args)
  1019. }).catch(e=>{console.error(e); throw 'failed'})
  1020. }
  1021. , 'repo-merge' : function(args) {
  1022. // Merge source repo into target repo
  1023. var args = args || {
  1024. folder : 'server'
  1025. , remotebase : 'http://git.bbh/chess/'
  1026. , sourcerepo : 'client'
  1027. , targetrepo : 'elixir-server'
  1028. }
  1029. var sourcerepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  1030. // , stdio: ['pipe', process.stdout, process.stderr]
  1031. , inherit: true,
  1032. shell: true,
  1033. env: process.env
  1034. , runas: processedArgs.runas
  1035. }
  1036. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  1037. // , stdio: ['pipe', process.stdout, process.stderr]
  1038. , inherit: true,
  1039. shell: true,
  1040. env: process.env
  1041. , runas: processedArgs.runas
  1042. }
  1043. var cmdseq = [
  1044. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  1045. , targetrepooptions ]
  1046. // , ['git', ['push', targetrepooptions ] // manual push for now..
  1047. ]
  1048. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e)})
  1049. }
  1050. , 'filter-repo' : function(args){
  1051. // Merge source repo into target repo
  1052. var args = args || {
  1053. folder : 'server'
  1054. , remotebase : 'http://git.bbh/chess/'
  1055. , targetrepo : 'elixir-server'
  1056. }
  1057. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  1058. , inherit: true, shell: true
  1059. , env: process.env
  1060. , runas: processedArgs.runas
  1061. }
  1062. var cmdseq = [
  1063. // git checkout -b feature/merge-old-project
  1064. // git remote add src-project ../src-project
  1065. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  1066. ]
  1067. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e); throw 'failed' })
  1068. }
  1069. , 'filter-branch' : function(preservefolder, repo){
  1070. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  1071. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  1072. // Preserve a specific folder.
  1073. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  1074. /*
  1075. git clone repo reposplit
  1076. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  1077. git remote rm origin
  1078. */
  1079. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  1080. }
  1081. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  1082. // // Merge repo2 into a subfolder in repo1
  1083. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  1084. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  1085. // /*
  1086. // cd repo1
  1087. // git remote add -f tempmergesource ../{{mergesource}}/.git
  1088. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  1089. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  1090. // git commit
  1091. // // Repair History
  1092. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  1093. // #!/usr/bin/env bash
  1094. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  1095. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  1096. // subdir=server
  1097. // git filter-branch --tree-filter '
  1098. // first='"$first"'
  1099. // last='"$last"'
  1100. // subdir='"$subdir"'
  1101. // log_file=/tmp/filter.log
  1102. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  1103. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  1104. // echo "=== $GIT_COMMIT: making changes"
  1105. // files=$(git ls-tree --name-only $GIT_COMMIT)
  1106. // mkdir -p $subdir
  1107. // for i in $files; do
  1108. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  1109. // done
  1110. // else
  1111. // echo "=== $GIT_COMMIT: ignoring"
  1112. // fi \
  1113. // >> $log_file
  1114. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  1115. // status=0 # tell tree-filter never to fail
  1116. // '
  1117. // git remote rm tempmergesource
  1118. // */
  1119. // // better alternative for history
  1120. // /**
  1121. // *
  1122. // git clone git@server.com:old-project.git
  1123. // git clone git@server.com:new-project.git
  1124. // cd old-project
  1125. // mkdir old-project
  1126. // git mv !(old-project) old-project
  1127. // ls -la and gt mv hidden files ....
  1128. // git commit -a -S -m “Moving old project into its own subdirectory”
  1129. // cd ../new-project
  1130. // git remote add old-project ../old-project
  1131. // git fetch old-project
  1132. // git checkout -b feature/merge-old-project
  1133. // git merge -S --allow-unrelated-histories old-project/master
  1134. // git push origin feature/merge-old-project
  1135. // git remote rm old-project
  1136. // */
  1137. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  1138. // }
  1139. , 'pull' : (label) => {
  1140. // Usage :
  1141. // elxr pull -- Defaults to run config
  1142. return elxr.getpulltask(selectedinstance)
  1143. }
  1144. , 'isInstalled': () => {
  1145. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  1146. console.log(processedArgs._[1] + ' exists.')
  1147. return true;
  1148. });
  1149. }
  1150. , 'c' : ()=>{
  1151. }
  1152. , 'i' : () => {
  1153. var tasks = []
  1154. // tasks.push(op['pull']);
  1155. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
  1156. tasks.push(op['use']) // Will pull repos...
  1157. op['npmi'].statuslog = statuslog
  1158. tasks.push(shell_verse.getNonElevatedTask(op['npmi'])) // We do not run npm i with elevated privilege for security reasons.
  1159. // var tasksdefs = [
  1160. // ['elxr', ['pull']]
  1161. // , ['elxr', ['use', 'elixir']]
  1162. // , ['elxr', ['npmi']]
  1163. // ]
  1164. // tasksdefs.forEach(tasksdef=>{
  1165. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  1166. // })
  1167. return any(tasks);
  1168. }
  1169. , 'npmi': () => {
  1170. var tasks = [];
  1171. // Build fails without babel...
  1172. tasks.push(getShellTask(
  1173. 'npm',[ 'i', '-g', 'babel-cli' ]
  1174. ) )
  1175. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  1176. // npmbuildrepos = []
  1177. npmbuildrepos.forEach(repo => {
  1178. tasks.push(() => {
  1179. return nodeShellExec('npm', ['i --force'], {
  1180. inherit: true, shell: true
  1181. , cwd: instanceroot + '/' + repo
  1182. , env: process.env
  1183. , title: `npm i for ${repo}`
  1184. }).catch((e) => {
  1185. console.error('Ignoring Benign Error'); console.error(e);
  1186. }).then(() => {
  1187. console.log(`--npm run build for ${repo}--------------------`)
  1188. return nodeShellExec('npm', ['run build'], {
  1189. inherit: true, shell: true
  1190. , cwd: instanceroot + '/' + repo
  1191. , env: process.env
  1192. , title: `npm run build for ${repo}`
  1193. }).then(Tasq.then).catch(Tasq.catch)
  1194. })
  1195. })
  1196. })
  1197. return any(tasks).then(() => {
  1198. gitRepos.push({ repo : 'chess-server-lib/server'});
  1199. gitRepos = gitRepos.concat(elevatedRunasRepos);
  1200. // console.dir(gitRepos)
  1201. // throw ""
  1202. // gitRepos = [
  1203. // // 'bbhverse', 'serververse', 'elixir-server',
  1204. // // 'clientverse',
  1205. // 'client'
  1206. // ];
  1207. var rmtasks = []
  1208. var repotasks = []
  1209. var env = Object.assign({}, process.env)
  1210. delete env.NODE_ENV
  1211. gitRepos.forEach(repodef => {
  1212. rmtasks.push(
  1213. // () => {
  1214. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1215. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  1216. callshelltask(['rm', ['package-lock.json'], {
  1217. inherit: true, shell: true
  1218. , cwd: instanceroot + '/' + repodef.repo
  1219. , env: process.env
  1220. , title: `rm 'package-lock.json' for ${repodef.repo}`
  1221. }])
  1222. .then(()=>{
  1223. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1224. }).catch((e) => { console.error(e) })
  1225. // }
  1226. )
  1227. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  1228. repotasks.push(
  1229. () => {
  1230. console.log(`--npm i for ${repodef.repo}--------------------`)
  1231. var p = nodeShellExec('npm', ['i', '--force'], {
  1232. inherit: true, shell: true
  1233. , cwd: instanceroot + '/' + repodef.repo
  1234. , env
  1235. , title: `npm i for ${repodef.repo}`
  1236. }).then(Tasq.then).catch(Tasq.catch)
  1237. return p;
  1238. })
  1239. }
  1240. })
  1241. // NODE_ENV=development DEBUG=loopback:connector:mssql node --tls-min-v1.0 --inspect elixir/server.js
  1242. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  1243. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  1244. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  1245. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  1246. // Second time try also doesnt work.
  1247. // repotasks.push(
  1248. // () => {
  1249. // var env = Object.assign({}, process.env)
  1250. // delete env.NODE_ENV
  1251. // console.log(`--------------------second time npm i for client--------------------`)
  1252. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  1253. // // return nodeShellExec('npm', ['i --force'], {
  1254. // inherit: true, shell: true
  1255. // , cwd: instanceroot + '/' + 'client'
  1256. // , env
  1257. // , title: `npm i for client`
  1258. // }).then(Tasq.then).catch(Tasq.catch)
  1259. // })
  1260. var bowerRepos = [{ repo : 'client'}]
  1261. var bowertasks = []
  1262. bowerRepos.forEach(repodef => {
  1263. bowertasks.push(() => {
  1264. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
  1265. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  1266. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  1267. inherit: true, shell: true
  1268. , cwd: instanceroot + '/' + repodef.repo
  1269. , env: process.env
  1270. , title: `bower i for ${repodef.repo}`
  1271. }).then(Tasq.then).catch(Tasq.catch)
  1272. return p;
  1273. })
  1274. })
  1275. // console.log('rmtasks.length : ' + rmtasks.length)
  1276. return Promise.all(rmtasks).then(() => any(repotasks)).then(()=>any(bowertasks));
  1277. }).catch(e => {
  1278. console.error(e)
  1279. }).finally(statuslog.finally)
  1280. }
  1281. , 'start': (args) => {
  1282. var label = clioverrides.cmd
  1283. var env = Object.assign({}, process.env); // Shallow clone it.
  1284. env.NODE_ENV = clioverrides.node_env || 'development';
  1285. var nodecmd = clioverrides.node_env === 'development' ? 'nodemon' : 'node';
  1286. function startFn( o ){
  1287. var cmd = [nodecmd, [`--inspect=${o.debugport}`, '--preserve-symlinks', o.script]]
  1288. console.log(`Starting ${o.name}.`);
  1289. var childPromise = nodeShellExec('cmd', ['/k', getCmdString(cmd) ], {
  1290. // inherit : true,
  1291. shell: true,
  1292. detached: true,
  1293. stdio: 'ignore',
  1294. cwd: instanceroot + o.path
  1295. , env: env
  1296. })
  1297. var child = childPromise.process;
  1298. var cpid = child.pid
  1299. if (typeof child.pid !== 'undefined') {
  1300. childPromise.then(()=>{
  1301. console.log(` *** started Elixir Loopback Server PID(${cpid}) : NODE_ENV=${clioverrides.node_env} ${cmd}`);
  1302. fs.writeFileSync('.elixir-server.elixir.server.pid', '' + cpid)
  1303. })
  1304. .catch(e => console.errror(e) )
  1305. }
  1306. }
  1307. if(clioverrides.node_env === 'development') {
  1308. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  1309. startFn( { debugport : 9228, script : 'elixir/server.js', name : 'Elixir Loopback Server', path : '/' + 'elixir-server' } )
  1310. startFn( { debugport : 9227, script : 'bin/www', name : 'Express Server', path : '/' + 'chess-server-lib/server' } )
  1311. // cmd = 'node'()
  1312. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  1313. // inherit : true,
  1314. // shell: true, detached: true,
  1315. // cwd : 'qms/server',
  1316. // env: env,
  1317. // shell : true
  1318. // })
  1319. // nodeShellExec('ember', ['s'], {
  1320. // // inherit : true,
  1321. // shell: true, detached: true,
  1322. // cwd : 'client/',
  1323. // env: env
  1324. // })
  1325. console.log('Starting Elixir Client Host.');
  1326. var cmd = ['ember', ['s']]
  1327. var childPromise = nodeShellExec(...cmd, {
  1328. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  1329. // PB : TODO -- ember debugging.
  1330. // inherit : true,
  1331. shell: true,
  1332. detached: true,
  1333. stdio: 'ignore',
  1334. cwd: instanceroot + '/' + 'client'
  1335. , env: env
  1336. })
  1337. // .catch(e=>console.error(e))
  1338. child = childPromise.process;
  1339. if (typeof child.pid !== 'undefined') {
  1340. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1341. fs.writeFileSync('.client.server.pid', child.pid, {
  1342. encoding: 'utf8'
  1343. })
  1344. }
  1345. }
  1346. }
  1347. , 'stop': (label) => {
  1348. const kill = require('tree-kill');
  1349. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  1350. encoding: 'utf8'
  1351. })
  1352. fs.unlinkSync('.elixir-server.elixir.server.pid')
  1353. console.log(serverPid)
  1354. kill(serverPid)
  1355. serverPid = fs.readFileSync('.express.server.pid', {
  1356. encoding: 'utf8'
  1357. })
  1358. fs.unlinkSync('.express.server.pid')
  1359. console.log(serverPid)
  1360. kill(serverPid)
  1361. }
  1362. , 'model' : () => {
  1363. var etask = ()=>{
  1364. var tasks = [
  1365. () => {
  1366. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  1367. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  1368. inherit: true, shell: true
  1369. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  1370. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  1371. , env: process.env
  1372. }).catch((e) => { console.error(e) })
  1373. return p;
  1374. }
  1375. ];
  1376. return any(tasks).then(() => {
  1377. fs.writeFileSync('run.done', 'success')
  1378. }).catch(() => {
  1379. fs.writeFileSync('run.done', 'error')
  1380. })
  1381. }
  1382. etask.statuslog = statuslog
  1383. etask.selectedinstance = selectedinstance
  1384. etask.processedArgs = processedArgs
  1385. etask.runtimestamp = runtimestamp
  1386. etask.ENV = ENV
  1387. return shell_verse.runElevated(etask)
  1388. }
  1389. , 'use' : () => {
  1390. // use a certain named instance.
  1391. // Eg :
  1392. // 1) elxr use elixir
  1393. // 2) elxr use cihsr
  1394. // If environment is not specified defaults to development.
  1395. // 1) NODE=test elxr use elixir
  1396. /*// Steps
  1397. 1) Delete Config and Data symlinks
  1398. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  1399. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  1400. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1401. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  1402. */
  1403. var runconfig = { NODE_ENV: selectedinstance.node_env }
  1404. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  1405. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  1406. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  1407. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  1408. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  1409. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  1410. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  1411. if (existsSync('config') && existsSync('data')){
  1412. return
  1413. }
  1414. }
  1415. var tasks = [
  1416. () => {
  1417. var promise = new Promise((resolve, reject)=>{
  1418. existslink('config', function(err, data){
  1419. if(data) {
  1420. var p = shell_verse.removeJuncionOrLink('config')
  1421. .then(()=>{resolve(true)})
  1422. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
  1423. }
  1424. else resolve(false)
  1425. })
  1426. })
  1427. return promise;
  1428. },
  1429. () => {
  1430. var promise = new Promise((resolve, reject)=>{
  1431. existslink('data', function(err, data){
  1432. if(data) {
  1433. var p = shell_verse.removeJuncionOrLink('data')
  1434. .then(()=>{resolve(true)})
  1435. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
  1436. }
  1437. else resolve(false)
  1438. })
  1439. })
  1440. return promise;
  1441. },
  1442. ];
  1443. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  1444. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  1445. if (!runconfig.use && selectedinstance.instanceName) runconfig.use = selectedinstance.instanceName;
  1446. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  1447. // console.log(process.env.cwd)
  1448. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  1449. // Maps an environment to a branch. Not required if the branch is appropriately named.
  1450. var checkoutMap = { 'development': 'master' }
  1451. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  1452. var performPullOrCloneForBranch = (def)=>{
  1453. var promise = Promise.resolve(true)
  1454. if (!branch) {
  1455. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1456. promise = nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{ branch = __branch})
  1457. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1458. }
  1459. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e )})
  1460. }
  1461. var performCloneAndCheckout = null;
  1462. // cant use git checkout -b it fails when branch already exists.
  1463. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1464. return performPullOrCloneForBranch(def).then(()=>{
  1465. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1466. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1467. // inherit : true, shell: true,
  1468. cwd: instanceroot + '/' + def.repo
  1469. // , stdio : ignore // Use when we want to silence output completely.
  1470. , runas: processedArgs.runas
  1471. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  1472. }).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 } })
  1473. })
  1474. }
  1475. // var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  1476. // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  1477. var elevatedqueue = [];
  1478. var enqueueOnce = (queue, task, def) => {
  1479. var found = queue.find(element => {
  1480. var keys = Object.keys( element )
  1481. for(var k=0; k < keys.length; k++) {
  1482. if(element[keys[k]] !== def[k]) return false;
  1483. }
  1484. })
  1485. queue.push(function(){ return task(this)}.bind(def));
  1486. }
  1487. var enqueue = (queue, task, def) => {
  1488. queue.push(function(){ return task(def)}.bind(def));
  1489. }
  1490. var mergeSources = {
  1491. 'development': null,
  1492. 'test': 'master',
  1493. 'production': 'master'
  1494. }
  1495. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1496. // Checkout is reduced to pull provided the current branch is the targetbranch
  1497. if(branch === mergesource) performCheckout = (def) => {
  1498. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1499. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  1500. if(branch === __branch) return performCloneAndCheckout(def)
  1501. return performPullOrCloneForBranch(def)
  1502. })
  1503. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1504. }
  1505. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  1506. var performPullAll = (def) => {
  1507. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1508. return nodeShellExec('git', ['pull', '--all'], {
  1509. // inherit : true, shell: true,
  1510. cwd: instanceroot + '/' + def.repo
  1511. , runas: processedArgs.runas
  1512. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  1513. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  1514. }
  1515. var excludeCheckouts = Object.assign(exludeMergeRepos)
  1516. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  1517. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  1518. var performMerge = (def) => {
  1519. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  1520. return nodeShellExec('git', ['merge', mergesource], {
  1521. inherit: true, shell: true,
  1522. cwd: instanceroot + '/' + def.repo
  1523. , runas: processedArgs.runas
  1524. }).catch((e) => { console.error(e) })
  1525. }
  1526. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
  1527. // var performRepoOperation = function(def) {
  1528. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  1529. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  1530. // }
  1531. return any(tasks).then(() => {
  1532. var task = ()=>{
  1533. //target is the env is we specify in elxr use command. Default is dev
  1534. //Switch to target branch
  1535. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  1536. // pull or clone target branch
  1537. .then(() => {
  1538. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1539. return any(gitRepos.map((repo) => performPullAll(repo)))
  1540. })
  1541. // switch to source branch
  1542. .then( () => {
  1543. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  1544. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  1545. })
  1546. //Pull on merge source branch
  1547. .then( () => {
  1548. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1549. return any(gitRepos.map((repo) => performPullAll(repo)))
  1550. })
  1551. //Switch to target branch
  1552. .then( () => {
  1553. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1554. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  1555. })
  1556. .then( //Merge source branch to target branch
  1557. () => {
  1558. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1559. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
  1560. })
  1561. }
  1562. task.statuslog = statuslog
  1563. var netask = shell_verse.getNonElevatedTask(task)
  1564. var eltask = ()=> {
  1565. var opts = {
  1566. inherit: true, shell: true
  1567. , cwd : instanceroot
  1568. , env: process.env
  1569. }
  1570. var tasks = [
  1571. () => {
  1572. // Use junctions to avoid npm package issues
  1573. var target = runconfig.use + '-' + 'config' + '-' + process.env.NODE_ENV
  1574. var p = shell_verse.createJuntionOrLink('config', target, opts)
  1575. return p;
  1576. }
  1577. ];
  1578. // if (processedArgs._[1]) {
  1579. tasks = tasks.concat( [
  1580. () => {
  1581. var dataToLink = runconfig.use + '-data' + '-' + process.env.NODE_ENV
  1582. if(!existsSync(dataToLink)) dataToLink = runconfig.use + '-data';
  1583. var p = shell_verse.createJuntionOrLink('data', dataToLink, opts)
  1584. return p;
  1585. }
  1586. ]
  1587. )
  1588. // }
  1589. return any(tasks).then(()=>{
  1590. // checkout target branch
  1591. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1592. // pull or clone target branch
  1593. .then(() => {
  1594. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1595. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  1596. })
  1597. // switch to source branch
  1598. .then( () => {
  1599. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1600. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  1601. })
  1602. //Pull on merge source branch
  1603. .then( () => {
  1604. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1605. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  1606. })
  1607. //Switch to target branch
  1608. .then( () => {
  1609. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1610. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1611. })
  1612. .then( //Merge source branch to target branch
  1613. () => {
  1614. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1615. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
  1616. })
  1617. .then(() => {
  1618. fs.writeFileSync('run.done', 'success')
  1619. }).catch(() => {
  1620. fs.writeFileSync('run.done', 'error')
  1621. })
  1622. })
  1623. }
  1624. eltask.statuslog = statuslog
  1625. eltask.selectedinstance = selectedinstance
  1626. eltask.processedArgs = processedArgs
  1627. var etask = shell_verse.getElevatedTask(eltask)
  1628. return etask().then( ()=>{ return netask() })
  1629. }).catch((e) => {
  1630. fs.writeFileSync('run.done', 'error : ' + e)
  1631. })
  1632. // Antibiotic stewardship program.
  1633. // 1st use is fine.
  1634. // Max vials dispense
  1635. // 2nd use Pharmacy needs justification Form.
  1636. // Approval after a certain period of time.
  1637. }
  1638. , 'g' : () => {
  1639. if (processedArgs.h) {
  1640. console.log('elxr g model [modelname] => generate a model named [modelname]');
  1641. console.log('elxr g vmodel [modelname] => generate a model named [modelname]');
  1642. console.log('elxr g => regenerate all known models');
  1643. return
  1644. }
  1645. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1646. // console.log('Starting directory: ' + process.cwd());
  1647. // try {
  1648. // child = child.on('close', () => { process.chdir(label) } );
  1649. // console.log('New directory: ' + process.cwd());
  1650. // }
  1651. // catch (err) {
  1652. // console.log('chdir: ' + err);
  1653. // }
  1654. // child.on('close', function(){
  1655. // var options = {
  1656. // shell : true
  1657. // , inherit : true
  1658. // // , cwd : '' + process.cwd
  1659. // // , env : process.env
  1660. // };
  1661. // nodeShellExec('git', ['init'], { inherit : true});
  1662. if (0) {
  1663. // PB : TODO -- Special google chrome profile for tests etc.
  1664. nodeShellExec('pwd', { inherit: true });
  1665. // /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"
  1666. // "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
  1667. // "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
  1668. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1669. "--profile-directory=Profile 1"
  1670. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1671. }
  1672. // nodeShellExec('npm', ['init', '-y'], options);
  1673. // nodeShellExec('npm', ['init', '-y'], options);
  1674. // })
  1675. var g = {
  1676. 'client': () => {
  1677. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  1678. console.info('Creating new ember client named : ' + processedArgs._[2]);
  1679. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1680. stdio: ['pipe', process.stdout, process.stderr],
  1681. inherit: true,
  1682. shell: true,
  1683. cwd: path.dirname(__dirname),
  1684. env: env
  1685. })
  1686. },
  1687. 'modelr': () => {
  1688. var tasks = [
  1689. () => {
  1690. var p = nodeShellExec('"ember"', [
  1691. 'g'
  1692. , 'modelr'
  1693. , processedArgs._[2]], {
  1694. inherit: true, shell: true, env: process.env
  1695. }).then(() => {
  1696. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  1697. return true;
  1698. }).catch((e) => { console.error(e) })
  1699. return p;
  1700. },
  1701. () => {
  1702. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1703. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  1704. chromeprefs = JSON.parse(chromeprefs)
  1705. var previous = chromeprefs.download.default_directory;
  1706. var parentDir = path.dirname(__dirname);
  1707. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1708. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1709. // PB : TODO -- detect where chrome is installed.
  1710. // PB : TODO -- set the download dir to the place where files are needed.
  1711. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1712. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1713. , '--profile-directory="chess"'
  1714. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1715. inherit: true, shell: true
  1716. , env: process.env
  1717. }).then(() => {
  1718. chromeprefs.download.default_directory = previous;
  1719. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1720. return true;
  1721. }).catch((e) => { console.error(e) })
  1722. return p;
  1723. }
  1724. ,
  1725. () => {
  1726. console.log('Browser process should have closed here....')
  1727. return true;
  1728. }
  1729. ]
  1730. any(tasks)
  1731. }
  1732. , 'undefined' : ()=>{
  1733. console.warn('Are you sure you want to refresh all the models.');
  1734. throw 'NOT YET IMPLMENTED'
  1735. }
  1736. , 'vmodel' : ()=>{
  1737. var verse = [ '__universe__/vmodel' ]
  1738. // console.dir(templateprocess(`__link____instance__server-lib__name__`, { link( ){
  1739. // return processed }, instance : 'elixir-', name : 'newmodel' } )
  1740. // )
  1741. }
  1742. }
  1743. g[processedArgs._[1]]();
  1744. }
  1745. , 'create' : () => { return createInstance(selectedinstance) }
  1746. , 'httpget' : () => {
  1747. // RESTAPI.get({
  1748. // hostname: 'git.bbh',
  1749. // // port: 443,
  1750. // protocol : 'http:',
  1751. // path: '/',
  1752. // method: 'GET'
  1753. // }, function(data){ console.log(data)}, function(error){ console.log(error)} )
  1754. return createInstance(selectedinstance)
  1755. }
  1756. , 'getuser' : ()=>{ return prerequisites.git.getuser().then(u=>{ console.log(u)}) }
  1757. , 'switch user' : (tousername)=>{ return GIT['switch user'](tousername) }
  1758. }
  1759. // independent elxr cli operations
  1760. var noprerequisites = {
  1761. add : true, 'set-url' : true, 'repo-relocate' : true
  1762. , remote : true, 'c' : true, 'h' : true
  1763. , httpget : true, getuser : true
  1764. , 'switch user' : true
  1765. , 'switch' : true
  1766. // , 'undefined' : true
  1767. }
  1768. var reconfirmcmds = { create : true }
  1769. var subcommandlabels = {
  1770. remote : (`remote ${processedArgs._[1] || ''}`).trim()
  1771. , switch : (`switch ${processedArgs._[1] || ''}`).trim()
  1772. }
  1773. var independentcmd = function(){
  1774. return false;
  1775. }
  1776. var cmds = {
  1777. remote : {
  1778. // return a interpreted set of arguments for this comd run context.
  1779. interpret() {
  1780. return { cmd : subcommandlabels['remote'], runchoice : 'c' }
  1781. }
  1782. }
  1783. , resetgitconfig : {
  1784. // return a interpreted set of arguments for this comd run context.
  1785. cmdFn : resetgitconfig
  1786. , interpret() { return { cmd : 'resetgitconfig' } }
  1787. , getPossiblePrompts(){ return {} }
  1788. , noprerequisites : true
  1789. , independentcmd : true
  1790. }
  1791. , reinit : {
  1792. // return a interpreted set of arguments for this comd run context.
  1793. cmdFn : reinit
  1794. , interpret() { return { cmd : 'reinit' } }
  1795. , getPossiblePrompts(){ return {} }
  1796. , noprerequisites : true
  1797. , independentcmd : true
  1798. , requiresElevation : true
  1799. , requires : [ generateDependencies ]
  1800. }
  1801. , init : {
  1802. // return a interpreted set of arguments for this comd run context.
  1803. cmdFn : init
  1804. , interpret() { return { cmd : 'init' } }
  1805. , getPossiblePrompts(){ return {} }
  1806. , noprerequisites : true
  1807. , independentcmd : true
  1808. , requiresElevation : true
  1809. , requires : [ generateDependencies ]
  1810. }
  1811. , switch : {
  1812. interpret() {
  1813. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2]
  1814. , reposerver : __default.reposerver
  1815. }
  1816. }
  1817. , getPossiblePrompts(){ return { username : true, reposerver : 'http://git.bbh' } } // Requires only one argument...
  1818. }
  1819. , 'switch user' : {
  1820. interpret() {
  1821. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2] }
  1822. }
  1823. , getPossiblePrompts(){ return { username : true } } // Requires only one argument...
  1824. }
  1825. // Flat linear structure. Every subcommand should have a top level 'label'
  1826. , 'users' : {
  1827. // default to the users list
  1828. subcommands : { list : {} }
  1829. , cmdFn : ()=>getCredentials() // default
  1830. , cmd : 'users'
  1831. , noprerequisites : true
  1832. }
  1833. , 'users list' : {
  1834. cmdFn : ()=>getCredentials()
  1835. , cmd : 'users list'
  1836. , noprerequisites : true
  1837. }
  1838. , 'g' : {
  1839. cmdFn : op['g'] // default
  1840. , cmd : 'g'
  1841. , noprerequisites : true
  1842. , getPossiblePrompts(){ return {} }
  1843. }
  1844. , 'link' : {
  1845. 'cmd' : 'link'
  1846. // , cmdFn : function( sourecpath, filename, dir ){
  1847. // var afterTargetPath = (dir)=>{
  1848. // console.dir(dir);
  1849. // // var tasks = [
  1850. // // () => {
  1851. // // // Use junctions to avoid npm package issues
  1852. // // var p = nodeShellExec('mklink', ['/J', filename, sourecpath], {
  1853. // // inherit: true, shell: true
  1854. // // , cwd : dir || instanceroot
  1855. // // , env: process.env
  1856. // // }).catch((e) => { console.error(e) })
  1857. // // return p;
  1858. // // }
  1859. // // ];
  1860. // }
  1861. // // console.dir(process.env)
  1862. // if(!dir) getCurrentFolder().then(afterTargetPath);
  1863. // else afterTargetPath(dir)
  1864. // }
  1865. , cmdFn : function( cmdopts ){
  1866. // sourecpathandfile should include name of file name
  1867. targetfilename = cmdopts.targetfilename || processedArgs._[1]
  1868. // console.log(processedArgs)
  1869. if(!targetfilename) return Promise.reject('error no file provided for linking')
  1870. targetdir = cmdopts.targetdir || process.env.wd
  1871. sourecpathandfile = cmdopts.sourecpathandfile || path.normalize(`../../node_modules/chess-server-lib/common/models/${targetfilename}`)
  1872. var tasks = [
  1873. () => {
  1874. // Use junctions to avoid npm package issues
  1875. var p = nodeShellExec('mklink', [path.normalize(`${targetdir + '/' + targetfilename}`), sourecpathandfile], {
  1876. inherit: true, shell: true
  1877. , cwd : targetdir
  1878. , env: process.env
  1879. }).catch((e) => { console.error(e) })
  1880. return p;
  1881. }
  1882. ];
  1883. var etask = ()=>{
  1884. return any(tasks).then(() => {
  1885. fs.writeFileSync('run.done', 'success')
  1886. }).catch(() => {
  1887. fs.writeFileSync('run.done', 'error')
  1888. })
  1889. }
  1890. etask.statuslog = statuslog
  1891. etask.selectedinstance = selectedinstance
  1892. etask.processedArgs = processedArgs
  1893. etask.runtimestamp = runtimestamp
  1894. etask.ENV = ENV
  1895. return shell_verse.runElevated(etask)
  1896. }
  1897. , noprerequisites : true
  1898. , privileged : true
  1899. }
  1900. }
  1901. var elxrcmd = (function(){
  1902. var __cmdprototype = function(){}
  1903. function subcommandlabelFor(cmd, sub){ return (`${cmd} ${sub || ''}`).trim() }
  1904. var __cmd = {
  1905. interpret() { return { cmd : this.cmd } }
  1906. , getPossiblePrompts(){ return {} } // Requires only one argument...
  1907. , cmdFn : ()=>{ throw "Elxr Unknown command."}
  1908. , finalized : true
  1909. }
  1910. function __createO(o){
  1911. if(o.finalized) return o;
  1912. var subs = Object.keys(cmds[o.cmd].subcommands || {})
  1913. // console.log(subs)
  1914. // console.log(o)
  1915. subs.forEach(sub=>elxrcmd.create( cmds[subcommandlabelFor(o.cmd, sub)] ))
  1916. var created = utils.assign_strict({}, __cmd, cmds[o.cmd], o)
  1917. cmds[o.cmd] = created;
  1918. op[o.cmd] = created.cmdFn;
  1919. noprerequisites[o.cmd] = created.noprerequisites
  1920. return created.cmdFn;
  1921. }
  1922. function create(o){ return __createO(o) }
  1923. __cmdprototype.create = create;
  1924. return __cmdprototype;
  1925. })()
  1926. elxrcmd.create(cmds['users'])
  1927. elxrcmd.create(cmds['g'])
  1928. elxrcmd.create(cmds['link'])
  1929. var interpretrun = function(){
  1930. var cmd = processedArgs._[0];
  1931. var clioverrides = { cmd }
  1932. processedArgs.node_env ? clioverrides.node_env = processedArgs.node_env
  1933. : (process.env.NODE_ENV && process.env.NODE_ENV.trim())
  1934. ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) : null;
  1935. return cmds[cmd] ? cmds[cmd].interpret() : (function(){
  1936. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  1937. // return clioverrides
  1938. cmds[cmd] = {
  1939. interpret() {
  1940. return Object.assign(clioverrides, { cmd, runchoice : 'c' })
  1941. }
  1942. , getPossiblePrompts(){ return { cmd, username : true, password : true,
  1943. instanceName : true, instanceType : true, reposerver : true } }
  1944. }
  1945. return cmds[cmd].interpret()
  1946. })()
  1947. }
  1948. var clioverrides = interpretrun()
  1949. console.dir(clioverrides)
  1950. var util = require('util');
  1951. var cliname = 'elxr';
  1952. var ver = '1.1';
  1953. var readme = `
  1954. Command syntax examples
  1955. elxr
  1956. Displays help. Same as elxr h
  1957. elxr i
  1958. Runs interactive propmts to help choose installation options.
  1959. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  1960. General command syntax.
  1961. Eg: NODE_ENV=development elxr pull elixir
  1962. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  1963. The specific cmd defines what the value is interpreted as.
  1964. There are several cmds that do not require an {{instancename}} parameter.
  1965. Eg: elxr remote remove origin
  1966. Git operations or passthrough external commands on all repository folders in you working directory.
  1967. Main objectives.
  1968. elxr cli is a wrapper around other shell commands and api based operations.
  1969. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  1970. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  1971. `;
  1972. var help = `
  1973. ${readme}
  1974. # list of commands... please refer dveloper documentation for ${cliname}
  1975. \r\n\t${
  1976. Object.keys(op).join('\r\n\t')
  1977. }
  1978. `;
  1979. var elxr = {
  1980. help() {
  1981. return chalk.cyanBright(`
  1982. -------------------------------------------------------------------------------
  1983. *** BBH Elixir ***
  1984. -------------------------------------------------------------------------------
  1985. elxr ${ver}
  1986. A cli tool for chess
  1987. ${help}
  1988. -------------------------------------------------------------------------------
  1989. `)
  1990. }
  1991. , info() {
  1992. return chalk.cyanBright(`
  1993. -------------------------------------------------------------------------------
  1994. *** BBH Elixir ***
  1995. -------------------------------------------------------------------------------
  1996. elxr ${ver}
  1997. A cli tool for chess
  1998. -------------------------------------------------------------------------------
  1999. `)
  2000. }
  2001. , getpulltask(args){
  2002. // def can be an instance config
  2003. // Or an object with many repos and elevated repos
  2004. // Or a single repo ( Either Elevated or normal. )
  2005. // USAGE
  2006. // elxr pull elixir origin master
  2007. // elxr pull
  2008. // not all remote branches are setup to be tracked locally (respective remotes and branches).
  2009. // pull --all is useless. As it fetches all remotes and branches but only merges current branch.
  2010. // apart from remote tracking branches We are interested in pulling from all remotes and relavant branches.
  2011. // The branch pipline should feed back to master
  2012. // master -> test -> stage -> release[nnnn] -> production
  2013. // (master) <= git merge [all remotes] production && git merge [all remotes] release[nnnn]
  2014. // git merge [all remotes] stage && git merge [all remotes] test && git merge [all remotes] master
  2015. var __args = {
  2016. remotename : args.remotename|| processedArgs._[2]
  2017. , url : args.url || processedArgs._[3]
  2018. , branch : args.branch || processedArgs._[4] // If branch not specified opearte on the current branch of each working directorys
  2019. }
  2020. // var commands = [
  2021. // // ['git', ['checkout', __args.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]]
  2022. // ,
  2023. // ]
  2024. // var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  2025. // var pullCmd = [ gitbash
  2026. // , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  2027. // , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  2028. var def = args || {
  2029. repos : selectedinstance.repos,
  2030. elevated : selectedinstance.elevated
  2031. }
  2032. var elevatedpulltasks = null;
  2033. if(def.repo) {
  2034. // Single repo case.
  2035. if(def.repo.requiresElevation) {
  2036. var t1 = function() {
  2037. return performPull(def).then(() => {
  2038. return true;
  2039. }).catch((e) => {
  2040. console.error(e)
  2041. }).finally(Traq.finally)
  2042. }
  2043. t1.statuslog = statuslog
  2044. t1.selectedinstance = selectedinstance
  2045. t1.processedArgs = processedArgs
  2046. elevatedpulltasks = shell_verse.getElevatedTask( t1 )
  2047. }
  2048. else {
  2049. var t2 = function(){
  2050. return performPull(def).then(() => {
  2051. console.log('pulled ' + JSON.stringify(def.repo))
  2052. return true;
  2053. }).catch((e) => {
  2054. console.error(e)
  2055. }).finally(Traq.finally)
  2056. }
  2057. t2.statuslog = statuslog
  2058. var regularpulltasks = shell_verse.getNonElevatedTask( t2 )
  2059. }
  2060. if(elevatedpulltasks) return elevatedpulltasks //getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  2061. else return regularpulltasks // getTaskWithoutElevation({ regularpulltasks})
  2062. }
  2063. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  2064. console.dir(def)
  2065. var env = Object.assign({}, process.env); // Shallow clone it.
  2066. console.log('Running exlr pull : ' + path.dirname(__dirname))
  2067. var useGitPull = processedArgs.useGitPull || false;
  2068. if(def.elevated || def.repos) {
  2069. if(def.elevated) def.requiresElevation = true;
  2070. else delete def.requiresElevation;
  2071. }
  2072. else {
  2073. if(def.requiresElevation) def.elevated = [def]
  2074. else def.repos = [def]
  2075. }
  2076. var regularpulltasks = function(){ return Promise.resolve(true) }
  2077. if(def.elevated){
  2078. elevatedpulltasks = function() {
  2079. // shell_verse.getElevatedTask( t1 )
  2080. var eBatch = []
  2081. def.elevated.map((def) => getPullTask(def, null, null, null, eBatch))
  2082. return any(shell_verse.runElevatedBatch(eBatch)).then(() => {
  2083. return true;
  2084. }).catch((e) => {
  2085. console.error(e)
  2086. })
  2087. }
  2088. elevatedpulltasks.statuslog = statuslog
  2089. }
  2090. if(def.repos) {
  2091. var regularpulltasks = function(){
  2092. var pendingpulls = [];
  2093. def.repos.forEach((def) => {
  2094. pendingpulls.push(
  2095. performPull(def).then(()=>{ console.log('pulled ' + JSON.stringify(def.repo)) })
  2096. .catch(e => { console.log(e); throw e })
  2097. )
  2098. })
  2099. return any(pendingpulls).finally(Traq.finally)
  2100. }
  2101. regularpulltasks.statuslog = statuslog
  2102. }
  2103. // if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  2104. // else return getTaskWithoutElevation({ regularpulltasks})
  2105. return any([ elevatedpulltasks, regularpulltasks ])
  2106. }
  2107. }
  2108. function preworkerconfig(){
  2109. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  2110. gitRepos = selectedinstance.repos
  2111. // gitRepos = ['chess-server-lib'];
  2112. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  2113. elevatedRunasRepos = selectedinstance.elevated
  2114. // Repos that should excluded from merge for releases...
  2115. exludeMergeRepos = selectedinstance.exludeMergeRepos
  2116. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  2117. // mysql -u root -p db_name < drop_all_tables.sql
  2118. var mysql = '../xampp/mysql/bin/mysql'
  2119. var mysqldump = '../xampp/mysql/bin/mysqldump'
  2120. }
  2121. // The main elxr cli process
  2122. function elxrworker() {
  2123. var __runcmd = function (label) {
  2124. var distinquishedlabel = subcommandlabels[label] || label
  2125. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  2126. }
  2127. // --runas
  2128. if (processedArgs.runas) {
  2129. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  2130. return __runcmd('runas')
  2131. }
  2132. else return __runcmd(processedArgs.label || processedArgs._[0] || 'undefined');
  2133. }
  2134. // function acquireChoices(selectedinstance) {
  2135. // var hasconfig = false;
  2136. // console.warn(chalk.cyan(`
  2137. // -------------------------------------------------------------------------------
  2138. // Could not locate your preferred configuration (you may not specified it)
  2139. // You should fork the default chess configuration to customize and make it
  2140. // your own instance with a named config as
  2141. // {{yourowninstancename}}-config-{{yourchosenenvironment}}
  2142. // And then run this tool as follows
  2143. // NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  2144. // OR
  2145. // Run this tool with the following command to use a quick start default.
  2146. // elxr --default
  2147. // OR
  2148. // Choose one of the options below to run interactively.
  2149. // We will run your choice at the next prompt.
  2150. // -------------------------------------------------------------------------------
  2151. // `))
  2152. // var choices = getInteractionPoints(detectedinstanceoptions, __interactive_prompts)
  2153. // var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  2154. // return initinstances(selectedinstance)
  2155. // })
  2156. // // var prompt = cli.prompter;
  2157. // // return prompt.ask(`Choose an option :
  2158. // // d) Install the default chess instance.
  2159. // // => elxr i chess node_env=development --default
  2160. // // n) Create your custom new instance interactively
  2161. // // => elxr i {{instanceName}} node_env={{environment}}
  2162. // // i) Choose an instance and environment to install
  2163. // // => elxr i {{instanceName}} node_env={{environment}}
  2164. // // c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  2165. // // => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  2166. // // h) Help
  2167. // // q) Quit
  2168. // // Default <= d
  2169. // // : `).then((choice) => {
  2170. // // if (choice && choice === 'd' || !choice) {
  2171. // // processedArgs._[0] = 'i'
  2172. // // selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  2173. // // selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  2174. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  2175. // // }
  2176. // // else if (choice === 'h') {
  2177. // // processedArgs._[0] = 'h'
  2178. // // fs.writeFileSync('run.done', 'noop help');
  2179. // // console.log(elxr.help()); process.exit()
  2180. // // }
  2181. // // else if (choice === 'n' || choice === 'i') {
  2182. // // var p1 = cli.prompter;
  2183. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  2184. // // processedArgs._[0] = 'i'
  2185. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  2186. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  2187. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  2188. // // if (choice === 'n') {
  2189. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  2190. // // console.warn(
  2191. // // chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  2192. // // process.exit();
  2193. // // }
  2194. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  2195. // // selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  2196. // // })
  2197. // // })
  2198. // // })
  2199. // // } else if (choice === 'c') {
  2200. // // var p1 = cli.prompter;
  2201. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  2202. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  2203. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  2204. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  2205. // // return p1.ask(`Enter cmd :
  2206. // // p) pull
  2207. // // Default <= p
  2208. // // : `).then(function (cmd) {
  2209. // // if (!cmd || cmd === 'p') {
  2210. // // processedArgs._[0] = 'pull'
  2211. // // }
  2212. // // else processedArgs._[0] = cmd
  2213. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  2214. // // selectedinstance.reposerver = reposerver || selectedinstance.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  2215. // // })
  2216. // // })
  2217. // // })
  2218. // // })
  2219. // // } else {
  2220. // // 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.`));
  2221. // // fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  2222. // // fs.writeFileSync('run.done', 'noop quit');
  2223. // // process.exit()
  2224. // // }
  2225. // // })
  2226. // }
  2227. var mergeObjByKey = function(arrOfObjs, keyName) {
  2228. var keyedDistinct = {}
  2229. var distinctArrOfObjs = []
  2230. arrOfObjs.forEach( o => {
  2231. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o)
  2232. })
  2233. Object.keys(keyedDistinct).forEach(key => {
  2234. distinctArrOfObjs.push( utils.assign( ...keyedDistinct[key] ) ) // PB : TODO -- Shallow use utils.assign
  2235. })
  2236. return distinctArrOfObjs;
  2237. }
  2238. var cacheWriteInstanceConfig = function(chessinstances){
  2239. var instanceName = chessinstances['current_run'].instanceName;
  2240. var node_env = chessinstances['current_run'].node_env;
  2241. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos, 'repo') ;
  2242. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated, 'repo') ;
  2243. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  2244. }
  2245. var configs = (function(){
  2246. return {
  2247. clusterNodeInstance(selected) { var clusternodename = 'node01'
  2248. return __acquireConfig(selected, selected.username, clusternodename
  2249. , selected.instanceName + '-config-' + selected.node_env + `-${clusternodename}`
  2250. , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
  2251. return e; }
  2252. )
  2253. }
  2254. , ownerInstnace(selected) { return __acquireConfig(selected, selected.username, null, null
  2255. , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
  2256. return e }
  2257. )
  2258. }
  2259. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  2260. , commonInstance(selected) { return __acquireConfig(selected, defaultRepoOwner
  2261. // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
  2262. ) }
  2263. , genericChessInstance(selected) { return __acquireConfig(selected) }
  2264. }
  2265. })()
  2266. var eNotImplemented = function(){
  2267. console.error('Not yet implemented')
  2268. process.exit()
  2269. }
  2270. // PB : TODO -- accept additional arg - an array specifying custom configPriority.
  2271. var acquireConfig = function(slections){
  2272. var configPriority = [ 'clusterNodeInstance', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  2273. return any(configPriority.map(cfg => { return function() { return configs[cfg](slections) } } ), true, true).then(()=>{
  2274. return acquireData(slections)
  2275. })
  2276. }
  2277. var instanceData = (function(){
  2278. return {
  2279. clusterNodeInstance(selected) { var clusternodename = 'node01'
  2280. return __acquireData(selected, selected.username, clusternodename
  2281. , selected.instanceName + '-data-' + selected.node_env + `-${clusternodename}`
  2282. , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
  2283. return e; }
  2284. )
  2285. }
  2286. , ownerInstnace(selected) { return __acquireData(selected, selected.username, null
  2287. , selected.instanceName + '-data-' + selected.node_env
  2288. , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
  2289. return e }
  2290. )
  2291. }
  2292. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  2293. , commonInstance(selected) { return __acquireData(selected, defaultRepoOwner
  2294. // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
  2295. ) }
  2296. , genericChessInstance(selected) { return __acquireData(selected) }
  2297. }
  2298. })()
  2299. var acquireData = function(slections){
  2300. var configPriority = [ 'clusterNodeInstance', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  2301. return any(configPriority.map(cfg => { return function() { return instanceData[cfg](slections) } } ), true, true)
  2302. }
  2303. function reinit(){
  2304. sysAddPathVar('%AppData%\\npm')
  2305. resetgitconfig()
  2306. }
  2307. function init(){
  2308. sysAddPathVar('%AppData%\\npm')
  2309. resetgitconfig()
  2310. }
  2311. function resetgitconfig(){
  2312. // https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage
  2313. // Git Credential storage...
  2314. // git config --global credential.helper 'store --file ~/.gitcredentials'
  2315. // git credential-store --file ~/.gitcredentials store
  2316. // // notepad C:/Program Files/Git/etc/gitconfig
  2317. // git config --global --unset credential
  2318. // git config --edit --system
  2319. // git config --global credential.helper "store --file ~/gitcredentials"
  2320. // git credential fill
  2321. // git credential-store --file ~/git.store store
  2322. // Find system git config
  2323. // git config --global --edit
  2324. // git config --list --show-origin
  2325. // git config --list --show-origin --show-scope
  2326. // https://stackoverflow.com/questions/35942754/how-can-i-save-username-and-password-in-git
  2327. // Recipie
  2328. // git config --global --unset credentials.helper
  2329. // cd /path/to/my/repo
  2330. // git config --unset credential.helper
  2331. // git config credential.helper 'store --file ~/.git_repo_credentials'
  2332. // git config credential.*.username my_user_name
  2333. // git config credential.https://gitlab.com.username my_user_name
  2334. // git credential fill
  2335. // git config --global credential.modalprompt false // doesnst work.
  2336. // core askpass = ;;; https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows
  2337. var options = {
  2338. inherit: true, shell: true //, env: process.env
  2339. , cwd: instanceroot
  2340. , runas: processedArgs.runas
  2341. }
  2342. var task = ['git', ['config'], options]
  2343. var tasklist = [
  2344. // ['--global', '--unset credentials.helper']
  2345. // ['--unset', 'credentials.helper']
  2346. // ,
  2347. // ['credential.helper', `'store --file git_repo_credentials'`]
  2348. ['--global', 'credential.helper', "'store --file ~/.git_repo_credentials'"]
  2349. , ['--global', '--replace-all', 'user.name', 'pb']
  2350. , ['--global', '--replace-all', 'user.email', 'pradeep@bbh.org.in']
  2351. // , ['--list']
  2352. // , ['credential', 'fill']
  2353. ]
  2354. var onEachError = e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n')
  2355. var shellT = (args) => { return getgitbashtask(args, onEachError)
  2356. // .catch(e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n' + tasq.toString()) )
  2357. }
  2358. execserial(tasklist, task, shellT, onEachError )
  2359. }
  2360. var createTasq = (args, shellT, onEachError) => {
  2361. var tasq = shellT ? shellT(args) : (() => { return nodeShellExec.apply(null, args).catch( onEachError || function(e){ console.error(e) } ) })
  2362. tasq.toString = function(){ return JSON.stringify(args)}
  2363. return tasq;
  2364. }
  2365. var execserial = function(tasklist, task, shellT){
  2366. var exec = (taskArgs)=>{
  2367. var thistask = task.concat();
  2368. thistask[1] = thistask[1].concat()
  2369. thistask[1].push.apply(thistask[1], taskArgs)
  2370. return createTasq(thistask, shellT)
  2371. }
  2372. return any(tasklist.map(exec))
  2373. }
  2374. var execonce = function(taskArgs, task){ return any([task[1].push.apply(task[1], taskArgs)].map(createTasq)) }
  2375. var __acquireConfig = function (selected, owner, clusternodename, configrepo, errHandler) {
  2376. configrepo = configrepo || selected.instanceName + '-config-' + selected.node_env;
  2377. var errorHandler = (e) => {
  2378. if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${owner}/${configrepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
  2379. // console.error('Could not connect to repo server. Timed Out')
  2380. return cli.prompt( ['(y)es', '(n)o', '(r)etry'], 'Could not connect to repo server. Timed Out. Would you like to switch server ? (y/n) ', 'y' ).then(propValue => {
  2381. if(propValue === 'y') {
  2382. reconfirm = getReconfirmAll()
  2383. return startElxr()
  2384. }
  2385. else if(propValue === 'r'){
  2386. return acquireConfig(selected)
  2387. }
  2388. else process.exit()
  2389. })
  2390. }
  2391. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${owner}/${configrepo}.git/' not found`))){
  2392. var choices = {
  2393. t : `install a new temporary local instance with this name ( will not persist ).
  2394. Use your own username for additional options. You can request for a username at chess@bbh.org.in )`
  2395. , e : 'exit' }
  2396. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  2397. choices = utils.assign({
  2398. i : 'create a new instance with this name => will fork the default config under your username'
  2399. , f : 'fork a new instance with this name for yourself for this node from another instance'
  2400. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  2401. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  2402. , p : 'create a custom config for yourself '
  2403. }, choices)
  2404. }
  2405. return cli.prompt( choices
  2406. , 'Config for instance not found. Would you like to ', 'e' ).then(propValue => {
  2407. if(propValue === 't') {
  2408. selectedinstance.local = true; return createInstance(selectedinstance)
  2409. }
  2410. if(propValue === 'i') return eNotImplemented()
  2411. if(propValue === 'f') return eNotImplemented()
  2412. if(propValue === 'o') return eNotImplemented()
  2413. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  2414. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  2415. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  2416. else process.exit()
  2417. })
  2418. }
  2419. console.warn(e)
  2420. throw e; //('Config acquisition failed.')
  2421. }
  2422. var successHandler = () => {
  2423. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  2424. utils.assign_strict(selectedinstance, require(manifestpath)( null, selectedinstance))
  2425. console.dir(selectedinstance.repos)
  2426. // Config from server always override merges into selection except for the current selection.
  2427. // PB : TODO -- utils.assign Array merges are non-distinct...
  2428. if(!selectedinstance.repos[0].repo) {
  2429. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  2430. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  2431. }
  2432. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  2433. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  2434. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  2435. }
  2436. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = utils.assign(selected, selectedinstance)
  2437. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  2438. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  2439. cacheWriteInstanceConfig(chessinstances)
  2440. ENV.NODE_ENV = selectedinstance.node_env;
  2441. }
  2442. return performPull({repo : configrepo}, null, owner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  2443. .catch( (e)=>{
  2444. // if(e){
  2445. if(Promise.resolve(e) === e) return e;
  2446. // console.error(e)
  2447. throw e; // Not a hard error but we need this for bcontinueonfailure as we still want to stop on firstsuccess.
  2448. // }
  2449. })
  2450. }
  2451. var __acquireData = function (selected, owner, clusternodename, datarepo, errHandler) {
  2452. datarepo = datarepo || selected.instanceName + '-data';
  2453. var errorHandler = (e) => {
  2454. if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${owner}/${datarepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
  2455. // console.error('Could not connect to repo server. Timed Out')
  2456. return cli.prompt( ['(y)es', '(n)o', '(r)etry'], 'Could not connect to repo server. Timed Out. Would you like to switch server ? (y/n) ', 'y' ).then(propValue => {
  2457. if(propValue === 'y') {
  2458. reconfirm = getReconfirmAll()
  2459. return startElxr()
  2460. }
  2461. else if(propValue === 'r'){
  2462. return acquireConfig(selected)
  2463. }
  2464. else process.exit()
  2465. })
  2466. }
  2467. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${owner}/${datarepo}.git/' not found`))){
  2468. var choices = {
  2469. t : `install a temporary local data folder.
  2470. For more options. Request and use a personal username at chess@bbh.org.in )`
  2471. , e : 'exit' }
  2472. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  2473. choices = utils.assign({
  2474. i : 'create a new instance with this name => will fork the default config under your username'
  2475. , f : 'fork a new instance with this name for yourself for this node from another instance'
  2476. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  2477. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  2478. , p : 'create a custom config for yourself '
  2479. }, choices)
  2480. }
  2481. return cli.prompt( choices
  2482. , 'Data repo for instance not found. Would you like to ', 'e' ).then(propValue => {
  2483. if(propValue === 't') {
  2484. selectedinstance.local = true; return createInstanceData(selectedinstance)
  2485. }
  2486. if(propValue === 'i') return eNotImplemented()
  2487. if(propValue === 'f') return eNotImplemented()
  2488. if(propValue === 'o') return eNotImplemented()
  2489. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  2490. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  2491. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  2492. else process.exit()
  2493. })
  2494. }
  2495. console.warn(e)
  2496. throw e; //('Config acquisition failed.')
  2497. }
  2498. var successHandler = () => {
  2499. }
  2500. return performPull({ repo : datarepo }, null, owner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  2501. .catch( (e)=>{
  2502. // if(e){
  2503. if(Promise.resolve(e) === e) return e;
  2504. // console.error(e)
  2505. throw e; // Not a hard error but we need this for bcontinueonfailure
  2506. // }
  2507. })
  2508. }
  2509. var launchpath = path.resolve(path.normalize(process.env.wd))
  2510. 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.
  2511. // The easisest would be to ask for a target directory and default to current dir....
  2512. // path.dirname(launchpath).split(path.sep).pop()
  2513. var parent = path.dirname(launchpath);
  2514. var pp = launchpath;
  2515. var instancediscoverytasks = [];
  2516. while(parent !== pp){
  2517. instancediscoverytasks.push(
  2518. ((pa)=>{
  2519. var p = pa;
  2520. return function(){
  2521. return hasElxr(p).then((value)=>{
  2522. if(value) return p
  2523. // PB : TODO -- Using throw like this is not friendly with any...
  2524. throw { value : false };
  2525. })
  2526. }
  2527. })(pp)
  2528. )
  2529. pp = parent;
  2530. parent = path.dirname(parent);
  2531. }
  2532. var instanceroot = null
  2533. var detectInstanceRoot = any(instancediscoverytasks, true, true).then( ir => {
  2534. if(ir.error) { instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ; }
  2535. else instanceroot = ir.pVal
  2536. return instanceroot
  2537. }).catch(()=>{
  2538. instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
  2539. })
  2540. // PB : TODO -- Embed this in the build instead of inlining it.
  2541. // Also attepmt to load from ../chess-config/...
  2542. var __default = ((name, options)=>{
  2543. // Default set of users in main repos.
  2544. var users = [
  2545. { username : `${options.username}`, password : `${options.password}` }
  2546. , { username : `chess` }
  2547. // , { username : `baptistdev`, password : 'encrypted' }
  2548. // , { username : `guest`, password : 'encrypted' }
  2549. ]
  2550. // ${options.reposerver} should be used to lookup current config.
  2551. // User can always add more branches and remotes as needed. Mainifest only occupies
  2552. // well defined namespaces
  2553. var remotes = {
  2554. // these are both fetch and push remotes. Use push - remotes to override push.
  2555. 'chess' : {
  2556. server : `${options.reposerver}`, user : 'chess', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2557. , push : 'no-pushing' }
  2558. , 'baptistdev-public' : {
  2559. server : `https://github.com`, user : 'baptistdev', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2560. , push : 'no-pushing' }
  2561. // Multiple urls dont tell us the current origin which may be
  2562. // different based on currently available/accessible based on device and client.
  2563. // We just treat them as different remotes and merge as needed.
  2564. //
  2565. , 'origin' : {
  2566. server : `${options.reposerver}`, user : '${options.username}', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2567. }
  2568. , 'origin-public' : {
  2569. // export GIT_SSL_NO_VERIFY=true
  2570. server : `https://git.bbh.org.in`, user : 'chess', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2571. , push : {
  2572. server : `${options.reposerver}`, user : `${options.username}`, path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`}
  2573. }
  2574. }
  2575. , 'origin-unc' : {
  2576. server : `//172.16.0.27/repos`, user : '${options.username}', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2577. }
  2578. // , { `${options.username}` : `https://git.bbh.org.in/${options.username}/elxr.git` }
  2579. }
  2580. // , 'fetch-remotes' : [] // Multiple fetch remotes are not supported by git.
  2581. // We therefore need to use
  2582. // - a pullall
  2583. // - or branch alias for multiple remote branch tracking branch strategy.
  2584. // -- This is however limited to corresponding branch names
  2585. // tracking branches.
  2586. // We at least need one branch for each remote that we wish to track.
  2587. // , 'tracking-branches' : [
  2588. // { master : ['origin/master', 'chess/master'] }
  2589. // ]
  2590. var reposerverinstances = {
  2591. 'http://git.bbh' : { users, remotes }
  2592. , 'https://git.bbh.org.in' : { users, remotes, external : true }
  2593. , '//172.16.0.27/repos' : { users, remotes }
  2594. , 'https://github.com' : {
  2595. // We host a miniaml set of repositories in github.
  2596. get users() { return [{ username : `${this.username}` }]}, username : `baptistdev`
  2597. , remotes : {
  2598. 'baptistdev-public' : {
  2599. server : `https://github.com`, user : 'baptistdev', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2600. , push : 'no-pushing' }
  2601. // , Add other remotes here.
  2602. }
  2603. , external : true, public : true
  2604. }
  2605. }
  2606. return {
  2607. reposervers : Object.keys(reposerverinstances)
  2608. , reposerverinstances
  2609. // Common baseline repos for all chess instances.
  2610. , repos : [
  2611. { repo : 'ember-masonry-grid' /*, branch : master*/ } // Default need not be specified.
  2612. , { repo : 'bbhverse' }
  2613. , { repo : 'clientverse' }
  2614. , { repo : 'serververse' }
  2615. , { repo : 'elxr' }
  2616. , { repo : 'ember-searchable-select' }
  2617. , { repo : 'loopback-component-jsonapi' }
  2618. , { repo : 'loopback-jsonapi-model-serializer' }
  2619. , { repo : 'loopback-connector-mysql' }
  2620. , { repo : 'loopback-connector-ds' }
  2621. , { repo : 'ember-service-worker' }
  2622. , { repo : 'ember-service-worker-asset-cache' }
  2623. , { repo : 'ember-service-worker-cache-fallback' }
  2624. , { repo : 'ember-service-worker-index' }
  2625. , { repo : 'ember-sw-client-route' }
  2626. , { repo : 'global-this' }
  2627. ]
  2628. // Requires elevation only in windows
  2629. , elevated : [ { repo : 'chess-server-lib', requiresElevation : true } ]
  2630. , exludeMergeRepos : { }
  2631. }
  2632. })(
  2633. '__default' // name
  2634. , { username : 'guest', instanceName : 'chess', node_env : 'development', reposerver : 'https://git.bbh.org.in' } // options
  2635. )
  2636. // We first load the default and then override with a runconfig if it exists else we override with the interactive prompts.
  2637. // Then acquire and reload and replace this default.
  2638. var hasElxr = function(path, options, cb) {
  2639. // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
  2640. options = options || {};
  2641. var tasks = [
  2642. '/elxr' // Is there a subfolder named elxr
  2643. , '/elxr/.git' // which is self git repository
  2644. // , '/elxr/.elxr' // and has .elxr subfolder we now store this in the instanceroot.
  2645. , '/elxr/' + __ALIAS__STAMP__ // Which has our stamp.
  2646. ]
  2647. if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
  2648. var value = existsFolderSync(path + tpath);
  2649. return { value, done : acc && !value };
  2650. }).value }
  2651. if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
  2652. var value = existsFolderSync(path + tpath);
  2653. return { value, done : acc && !value };
  2654. }).value );
  2655. return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
  2656. var value = existsFolderSync(path + tpath);
  2657. return { value, done : acc && !value };
  2658. }).value);
  2659. }
  2660. var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); }
  2661. var detectfromroot = function(root){
  2662. return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(root) ) }
  2663. }
  2664. var detectLocalInstances = function () {
  2665. console.log(`launchpath = ${launchpath}`)
  2666. console.log(`thisscriptdir = ${thisscriptdir}`)
  2667. // PB : TODO -- !Postpone this.
  2668. console.log(`instanceroot = ${instanceroot}`) // Not yet confirmed...
  2669. // Note : Paths should already be normalized fefore this.
  2670. var root = instanceroot;
  2671. var detected = { root };
  2672. var instanceoptions = [clioverrides]
  2673. return hasElxr(launchpath).then( (elxrCliExists) => {
  2674. // We need a reference to the root director for elxr cli to be properly oriented.
  2675. if (( elxrCliExists && path.normalize(launchpath + '/elxr')) === thisscriptdir) {
  2676. // We were run from the proper root with elxr cli in the subfolder.
  2677. instanceroot = root = launchpath;
  2678. instanceoptions.splice( 0, 0, detected = { root })
  2679. instanceoptions.splice( 0, 0, detectfromroot(root))
  2680. }
  2681. else {
  2682. if(path.normalize(launchpath + '/elxr') === thisscriptdir) {
  2683. // elxrCliExists is false -- and yet thiscriptdir is still proper.
  2684. // PB : TODO -- Maybe a warning / abort if for some reason this scriptdir should not be taken over...
  2685. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.')
  2686. instanceroot = root = launchpath;
  2687. instanceoptions.splice( 0, 0, detected = { root })
  2688. instanceoptions.splice( 0, 0, detectfromroot(root))
  2689. }
  2690. else if (launchpath === thisscriptdir) {
  2691. var parentHasElxr = hasElxrSync(launchpath + '/..')
  2692. // PB : TODO -- verify if we have .elxr folder in the parent...
  2693. if(!parentHasElxr) {
  2694. // ! thisscriptdir is not elxr.
  2695. console.error('Invalid run location in subfolder that looks like elxr. We should probably abort as elxr will not sync.')
  2696. }
  2697. // Same directory doesn't mean we are being run from elxr sub directory.
  2698. // In standalone build script we may or not be in the same location.
  2699. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  2700. // Unbuilt therefore we are in the elxr sub directory.
  2701. instanceroot = root = path.normalize(launchpath + '/..');
  2702. instanceoptions.splice( 0, 0, detected = { root });
  2703. instanceoptions.splice( 0, 0, detectfromroot(root));
  2704. }
  2705. else {
  2706. // Built version.
  2707. // We could have been run from the elxr subfolder. Highly likely that the built version isn't the full elxr.
  2708. if(parentHasElxr) {
  2709. // Built version was run from the full elxr subfolder. Should work
  2710. // PB : TODO -- but we should switch to the full version...
  2711. instanceroot = root = path.normalize(launchpath + '/..');
  2712. instanceoptions.splice( 0, 0, detected = { root })
  2713. instanceoptions.splice( 0, 0, detectfromroot(root))
  2714. }
  2715. else {
  2716. instanceroot = root = launchpath;
  2717. instanceoptions.splice( 0, 0, detected = { root })
  2718. instanceoptions.splice( 0, 0, detectfromroot(root))
  2719. // Assume current launchpath is a new instance and create.
  2720. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  2721. // if(clioverrides.instanceName) {
  2722. // if(clioverrides.node_env) {
  2723. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  2724. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  2725. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  2726. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  2727. // // eg : floder name can be elixir01 but instance name is elixr
  2728. // }
  2729. // else {
  2730. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + 'development')
  2731. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  2732. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  2733. // }
  2734. // }
  2735. // else {
  2736. // instanceroot = root = launchpath;
  2737. // if(clioverrides.node_env) {
  2738. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  2739. // instanceoptions.splice( 0, 0, detectfromroot(root))
  2740. // }
  2741. // else {
  2742. // // Nothing was specified... We only have one option from root.
  2743. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  2744. // }
  2745. // }
  2746. }
  2747. }
  2748. }
  2749. else {
  2750. if(elxrCliExists) {
  2751. instanceroot = root = launchpath;
  2752. instanceoptions.splice( 0, 0, detected = { root })
  2753. instanceoptions.splice( 0, 0, detectfromroot(root))
  2754. }
  2755. }
  2756. }
  2757. instanceroot = detected.root
  2758. __default.root = root;
  2759. clioverrides.root = clioverrides.root || root;
  2760. // Resolves empty array when No known instances detected.
  2761. return Promise.resolve(instanceoptions)
  2762. })
  2763. }
  2764. var getReconfirmAll = ()=>{return { instanceName : true, instanceType : true, reposerver : true, username : true, password : true } }
  2765. if(clioverrides.reconfirm) {
  2766. var reconfirm = getReconfirmAll()
  2767. }
  2768. else { var reconfirm = {}; }
  2769. var shouldPrompt = function(k, possiblePrompts, target){
  2770. return ((possiblePrompts[k] !== undefined && possiblePrompts[k] !== null) && target[k] !== possiblePrompts[k]
  2771. || (possiblePrompts[k] === undefined || possiblePrompts[k] === null) && (target[k] === undefined || target[k] === null)
  2772. || reconfirm[k])
  2773. }
  2774. var getBoundEachPrompt = function(target, possiblePrompts, promptables, choices, promptsfilter) {
  2775. return function(prompts, k, i, a){
  2776. // No local instances config found. We use a default initialized instance available in selectedinstance
  2777. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  2778. // PB : TODO -- selectedinstance === __default check to prompt everything...
  2779. if( shouldPrompt(k, possiblePrompts, target) ) {
  2780. delete reconfirm[k];
  2781. // console.log(k)
  2782. // console.dir(possiblePrompts); //console.dir(target)
  2783. prompts.push(async ()=>{
  2784. // PB : NOTE -- Important in async cases when this {{target}} needs to be in the same state as when it was invoked.
  2785. // We need to take a snapshot... Shallow.. !! If required deep should be used based on use case.
  2786. // var asyncthis = Object.assign(this);
  2787. // By default Latest altered state is provided which is an implicit reference directly.
  2788. promptables[k].choices = choices[k]
  2789. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  2790. return await target[k]
  2791. })
  2792. }
  2793. delete possiblePrompts[k] // PB : TODO We should keep this around instead of deleting so we can do a second pass if required.
  2794. return prompts
  2795. }
  2796. }
  2797. var __interactive_prompts = function( target, choices, promptsfilter ){
  2798. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  2799. var interactionpoints = {
  2800. runchoice : {
  2801. label :
  2802. `Choose an option :
  2803. d) Install the default chess instance.
  2804. => elxr i chess node_env=development --default
  2805. n) Create your custom new instance interactively
  2806. => elxr i {{instanceName}} node_env={{environment}}
  2807. i) Choose an instance and environment to install
  2808. => elxr i {{instanceName}} node_env={{environment}}
  2809. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  2810. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  2811. h) Help
  2812. q) Quit
  2813. : `
  2814. , choices : []
  2815. , defaultchoice : 'c'
  2816. , selectedchoice : target.runchoice
  2817. , interpret : function(choice){
  2818. var interpret_map = {
  2819. d : function(){
  2820. processedArgs._[0] = 'i'
  2821. target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  2822. target.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  2823. target.reposerver = 'https://git.bbh.org.in'
  2824. }
  2825. , n : function() { processedArgs._[0] = 'i' }
  2826. , i : function() {
  2827. processedArgs._[0] = 'i'
  2828. // processedArgs._[1] = target.instanceName || processedArgs._[1] || 'chess';
  2829. }
  2830. , c : async function() {
  2831. // this here will always be the target.
  2832. Object.defineProperty(this, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  2833. label : `Enter cmd :
  2834. p) pull
  2835. Default <= p
  2836. : `
  2837. , defaultchoice : 'pull'
  2838. }
  2839. ));
  2840. var cmd = await target['cmd'];
  2841. if (!cmd || cmd === 'p') { target['cmd'] = processedArgs._[0] = 'pull' }
  2842. else target['cmd'] = processedArgs._[0] = cmd
  2843. return cmd;
  2844. }
  2845. , h : function() { console.log(elxr.help()); process.exit() } // PB : TODO -- Why do we need log.
  2846. , q : function() { process.exit() }
  2847. }
  2848. if(Promise.resolve(choice) === choice){
  2849. return choice.then( resolvedchoice => {
  2850. return (interpret_map[choice] || interpret_map['c']).call(target)
  2851. })
  2852. }
  2853. else return Promise.resolve( (interpret_map[choice] || interpret_map['c']).call(target) )
  2854. // var __interpreter = interpret_map[choice] || interpret_map['c']
  2855. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  2856. // if(interpret_map[choice]) __interpreter = interpret_map[choice];
  2857. // return __interpreter.call(target)
  2858. }
  2859. }
  2860. , instanceName : { label : `Enter Instance Name ( <= ${target.instanceName || 'chess'} ) : `
  2861. , choices : choices['instanceName'], defaultchoice : 'chess'
  2862. , selectedchoice : target.instanceName
  2863. }
  2864. , instanceType : { label : `Enter Instance Type ( <= ${target.instanceType || 'development'} ) : `
  2865. , choices : choices['instanceType'], defaultchoice : 'development'
  2866. , selectedchoice : target.instanceType
  2867. }
  2868. , reposerver : { label : `Enter Repo Url ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `
  2869. , choices : choices['reposerver'], defaultchoice : 'https://git.bbh.org.in'
  2870. , selectedchoice : target.reposerver
  2871. }
  2872. , get username() { return { label : `Enter User Id for ${target.reposerver} ( <= ${target.username || 'chess'} ) : `
  2873. , choices : choices['username'], defaultchoice : 'chess', selectedchoice : target.username } }
  2874. , get password() { return { label : `Enter Password for ${target.username} @ ${target.reposerver} ( <= ${target.password || ''} ) : `
  2875. , choices : choices['password'], defaultchoice : '***', selectedchoice : target.password } }
  2876. , get email() { return { label : `Enter Email for ${target.username} @ ${target.reposerver} ( <= ${target.email || ''} ) : `
  2877. , choices : choices['email'], defaultchoice : 'guest@bbh.org.in', selectedchoice : target.email } }
  2878. }
  2879. function getPromptKeys() {
  2880. if(! (processedArgs.label || processedArgs._[0]) ) return Object.assign({}, interactionpoints);
  2881. return promptkeys
  2882. }
  2883. var eachPrompt = getBoundEachPrompt( target, getPromptKeys() , interactionpoints, choices, promptsfilter)
  2884. return Object.keys(promptsfilter || interactionpoints).reduce(eachPrompt, [])
  2885. }
  2886. var downloadsdir = '../Downloads';
  2887. var prerequisites = [
  2888. {
  2889. shellcmd: 'git',
  2890. name : 'git',
  2891. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  2892. , installer: 'Git-2.31.0-64-bit.exe'
  2893. , installcmd: ['cmd', ['/c', 'start',
  2894. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  2895. , '/VERYSILENT'
  2896. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  2897. ]]
  2898. , preinstallsteps: function() {
  2899. var steps = [
  2900. () => {
  2901. if (!existsSync(downloadsdir + '/' + this.installer)) {
  2902. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  2903. }
  2904. else return Promise.resolve(true)
  2905. }
  2906. ]
  2907. var prompts = this.getuser(null, ()=>{
  2908. // console.log('preinstallsteps')
  2909. // var gitUser = 'guest';
  2910. // var gitEmail = 'guest@bbh.org.in';
  2911. // var prompts = [];
  2912. // prompts.push( ()=>{ return cli.prompt(choices['username'], 'git user name').then(gituser => gitUser = gituser) } )
  2913. // prompts.push( ()=>{ return cli.prompt(choices['useremail'], 'git user email').then(gitemail => gitEmail = gitemail) } )
  2914. // console.log('prompting in preinstallsteps')
  2915. // return any(prompts).then(()=>{
  2916. // var steps = [
  2917. // ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  2918. // , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  2919. // ]
  2920. // return any(steps.map(getshelltask)).then(() => {
  2921. // })
  2922. // });
  2923. return Promise.resolve(true)
  2924. })
  2925. return any([any(steps), prompts])
  2926. }
  2927. , installsteps: function () {
  2928. return any([this.installcmd].map(getshelltask))
  2929. }
  2930. , postinstallsteps: function(err, users){
  2931. return this.getuser(null, (err, data)=>{
  2932. // ignore err and proceed with data as guest.
  2933. console.dir(data)
  2934. if(data && data.length === 1 && !shouldPrompt('username', promptkeys, selectedinstance) ) {
  2935. return username = data[0];
  2936. }
  2937. data = data || ['guest']
  2938. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  2939. console.log('prompting in postinstallsteps')
  2940. var username = 'guest';
  2941. var email = 'guest@bbh.org.in';
  2942. var password = '***';
  2943. return any( getInteractionPoints(selectedinstance, promptkeys, { username, password, email}) ).then(()=>{
  2944. if(!data.find(e => e === selectedinstance.username)) {
  2945. var steps = [
  2946. ['git', ['config', '--global', '--add', 'user.name', `${username}`]]
  2947. , ['git', ['config', '--global', '--add', 'user.email', `${email}`]]
  2948. ]
  2949. return any(steps.map(getshelltask)).then(() => {
  2950. })
  2951. }
  2952. else {
  2953. return Promise.resolve(true)
  2954. }
  2955. });
  2956. })
  2957. }
  2958. , install: function () {
  2959. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  2960. }
  2961. , verifyAndInstall : function(){
  2962. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  2963. if(exists) {
  2964. // return any(['git', ['config', '--global', '-l']].map(getshelltask))
  2965. return this.postinstallsteps.bind(this)()
  2966. }
  2967. return this.install();
  2968. });
  2969. }
  2970. , getuser : function(repo, onResult){
  2971. var __onResult = onResult || function(e, data){
  2972. data = data || []
  2973. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  2974. // console.dir(choices)
  2975. return data[0]
  2976. }
  2977. var globalOrLocal = '--global';
  2978. if(repo) globalOrLocal = '--local'
  2979. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(getshelltask)).then((result)=>{
  2980. // not yet configured.
  2981. if(!result.success) return __onResult(result)
  2982. else {
  2983. var users = result.messages[0].trim().split('\n');
  2984. if(users.length === 0 ||
  2985. users.length === 1 && users[0] === 'guest') {
  2986. return __onResult(result)
  2987. }
  2988. else {
  2989. return __onResult(null, Array.from( new Set( users ) ) ); }// PB : TODO == We should probably prompt with all the users available for selection !
  2990. }
  2991. })
  2992. .catch((e)=>{
  2993. console.log(e)
  2994. return __onResult(e)
  2995. })
  2996. }
  2997. }
  2998. ,
  2999. {
  3000. shellcmd: 'node',
  3001. name : 'node',
  3002. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  3003. , installer: 'node-v14.16.0-x64.msi'
  3004. , installcmd: ['MSIEXEC.exe', ['/i'
  3005. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  3006. , 'ACCEPT=YES', '/passive']]
  3007. , install : function() { return any([this.installcmd].map(getshelltask)).then(() => { }) }
  3008. }
  3009. ]
  3010. for(var i=0; i<prerequisites.length; i++) {
  3011. prerequisites[prerequisites[i].name] = prerequisites[i];
  3012. }
  3013. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  3014. function ensureDirectoryExistence(filePath) {
  3015. var dirname = path.dirname(filePath);
  3016. if (fs.existsSync(dirname)) {
  3017. return filePath;
  3018. }
  3019. ensureDirectoryExistence(dirname);
  3020. fs.mkdirSync(dirname);
  3021. return filePath;
  3022. }
  3023. var mainTasks = [];
  3024. function verifyAndInstallPrerequisites() {
  3025. var downloadtasks = [];
  3026. var installtasks = [];
  3027. prerequisites.forEach(preq => {
  3028. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  3029. if (exists) console.log(`${preq.shellcmd} exists`)
  3030. else {
  3031. console.log(`${preq.shellcmd} is not installed`)
  3032. return preq.preinstallsteps.call(preq).then(() => {
  3033. installtasks.push(preq.install.bind(preq))
  3034. })
  3035. }
  3036. }))
  3037. })
  3038. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  3039. }
  3040. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  3041. return {
  3042. get (){
  3043. return cli.prompt( promptable.choices, promptable.label, promptable.defaultchoice, promptable.selectedchoice ).then(propValue => {
  3044. var asyncprop = Promise.resolve(propValue)
  3045. if(promptable.interpret){
  3046. asyncprop = promptable.interpret(propValue)
  3047. }
  3048. return asyncprop.then(
  3049. ()=>{
  3050. Object.defineProperty(this, propName, {
  3051. value: propValue,
  3052. writable: true,
  3053. configurable : true,
  3054. enumerable : true
  3055. });
  3056. return propValue
  3057. }
  3058. )
  3059. })
  3060. }
  3061. // , set (propValue){
  3062. // Object.defineProperty(this, propName, {
  3063. // value: propValue,
  3064. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  3065. // configurable : true,
  3066. // enumerable : true
  3067. // })
  3068. // return propValue;
  3069. // }
  3070. , configurable : true
  3071. , enumerable : true
  3072. }
  3073. }
  3074. function acquirelocalinstances(selected){
  3075. // utils.assign is used to cleanup duplicates...
  3076. var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
  3077. return chessinstances
  3078. }
  3079. function findlocalinstances(chessinstances, instanceoptions){
  3080. // We can expect a .elxr at each level.
  3081. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../..' /* instanceNames */].
  3082. earlyreduce( ( value, p, i, a )=>{
  3083. var localinstancesPath = `${instanceroot}/${p}.elxr`;
  3084. if(existsSync( localinstancesPath )) {
  3085. try {
  3086. var chessinstances = acquirelocalinstances( { localinstancesPath } )
  3087. return Object.keys(chessinstances).earlyreduce( ( value, instanceName) => {
  3088. return Object.keys(chessinstances[instanceName]).earlyreduce( (value, instanceType) => {
  3089. if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize( instanceroot) ) {
  3090. instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType])
  3091. return {
  3092. value : chessinstances[instanceName][instanceType]
  3093. , done : true
  3094. };
  3095. }
  3096. })
  3097. })
  3098. }
  3099. catch(e){
  3100. return { }
  3101. }
  3102. }
  3103. else return { }
  3104. }
  3105. )
  3106. }
  3107. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  3108. var selectedinstance = { root : process.env.wd };
  3109. var chessinstances = { current_run : {} };
  3110. var promptkeys = {
  3111. cmd : processedArgs._[0] || 'pull'
  3112. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  3113. // 'instanceName' : true
  3114. // , 'node_env' : true
  3115. // , username : ''
  3116. // , runchoice : 'c'
  3117. }
  3118. // promptkeys.runchoice = promptkeys.cmd ? 'c' : undefined
  3119. function createLocalChessInstance( cfg ){
  3120. // return createInstance(cfg)
  3121. reconfirm = getReconfirmAll()
  3122. var inst = {};
  3123. var __new = Object.assign({}, __default, cfg)
  3124. inst[cfg.node_env] = __new; return inst;
  3125. }
  3126. var choices = {
  3127. 'instanceName' : []
  3128. , 'reposerver' : []
  3129. , 'instanceType' : []
  3130. , username : ['guest', 'chessdemo', 'demo']
  3131. }
  3132. var getInteractionPoints = function(detectedinstanceoptions, possiblePrompts, promptsfilter){
  3133. var instances = []
  3134. var reposervers = [];
  3135. var instanceNames = []
  3136. var instanceTypes = ['development', 'production'];
  3137. Object.keys( chessinstances).forEach(instanceName => {
  3138. if(instanceName === 'current_run') return;
  3139. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  3140. var instance = chessinstances[instanceName][node_env];
  3141. reposervers = reposervers.concat(instance.reposervers)
  3142. if(instance.reposerver) reposervers.push(instance.reposerver)
  3143. instances.push(instance)
  3144. instanceTypes.push(instance.node_env)
  3145. instanceNames.push(instance.instanceName)
  3146. })
  3147. })
  3148. instances = instances.concat(detectedinstanceoptions)
  3149. if(selectedinstance['instanceName']) instanceNames.push(selectedinstance['instanceName'])
  3150. if(possiblePrompts['instanceName']) instanceNames.push(possiblePrompts['instanceName'])
  3151. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers'])
  3152. choices['instanceName'] = Array.from( new Set(instanceNames.concat(choices['instanceName'])) )
  3153. choices['reposerver'] = Array.from( new Set(reposervers.concat(choices['reposerver'])) )
  3154. choices['instanceType'] = Array.from( new Set(instanceTypes.concat(choices['instanceType'])) )
  3155. return __interactive_prompts(selectedinstance, choices, promptsfilter)
  3156. }
  3157. var detection_state = {
  3158. localInstanceDetected : false
  3159. }
  3160. const https = require('https')
  3161. const http = require('http');
  3162. const { resolve } = require('path');
  3163. const RESTAPI = (function(){
  3164. // Singleton
  3165. function RESTAPI(){}
  3166. // RESTAPI.create = RESTAPI; // Returns the one singe instance which is the class itself
  3167. // const options = {
  3168. // hostname: 'whatever.com',
  3169. // port: 443,
  3170. // path: '/todos',
  3171. // method: 'POST',
  3172. // headers: {
  3173. // 'Content-Type': 'application/json',
  3174. // 'Content-Length': data.length
  3175. // }
  3176. // }
  3177. RESTAPI.method = function(options, resolve, reject){
  3178. var __method = function() {
  3179. options.headers = options.headers || { 'Content-Type': 'application/json' }
  3180. if(options.payload) {
  3181. const data = new TextEncoder().encode( JSON.stringify(options.payload) )
  3182. options.headers = options.headers || {
  3183. 'Content-Type': 'application/json',
  3184. 'Content-Length': data.length
  3185. }
  3186. }
  3187. if(!options.authenticatepost) options.headers.Authorization = `token ${usertokens[options.username]}`
  3188. var acquirer = getHTTPorS(options)
  3189. const req = acquirer.request(options, res => {
  3190. if (res.statusCode < 200 || res.statusCode >= 300) {
  3191. return reject(new Error('statusCode=' + res.statusCode));
  3192. }
  3193. var body = [];
  3194. // res.setEncoding('utf8');
  3195. res.on('data', function(chunk) {
  3196. body.push(chunk);
  3197. });
  3198. res.on('end', function() {
  3199. try {
  3200. body = JSON.parse(Buffer.concat(body).toString());
  3201. } catch(e) {
  3202. reject(e);
  3203. }
  3204. resolve(body);
  3205. });
  3206. });
  3207. req.on('error', error => {
  3208. console.error(error)
  3209. reject(error)
  3210. })
  3211. if(options.payload) req.write(data)
  3212. req.end()
  3213. }
  3214. if(!options.authenticatepost && !usertokens[options.username]) {
  3215. RESTAPI.authenticate(options, function(tokenresp){
  3216. usertokens[options.username] = tokenresp.sha1
  3217. __method(options, resolve, reject)
  3218. },
  3219. function(err){ throw err}
  3220. )
  3221. }
  3222. else __method(options, resolve, reject)
  3223. }
  3224. RESTAPI.post = RESTAPI.method
  3225. var usertokens = {}
  3226. RESTAPI.authenticate = function(options, resolve, reject){
  3227. options.headers = options.headers || { 'Content-Type': 'application/json' }
  3228. if(!usertokens[options.username]) {
  3229. // Authenticate and acquire token.
  3230. // https://git.bbh/api/v1/users/<username>/tokens
  3231. // curl -XPOST -H "Content-Type: application/json" -k -d '{"name":"demo"}' -u demo:demo123 http://git.bbh/api/v1/users/demo/tokens
  3232. var _options = Object.assign({}, options)
  3233. // _options.username = 'demo'
  3234. // _options.password = 'demo123'
  3235. _options.method = 'POST'
  3236. _options.headers.Authorization = `Basic ${Buffer.from(`${_options.username}:${_options.password}`).toString('base64')}`
  3237. _options.path = `/api/v1/users/${_options.username}/tokens`
  3238. _options.authenticatepost = true
  3239. var postoptions = { name : _options.username }
  3240. delete _options.username
  3241. delete _options.password
  3242. _options.payload = postoptions
  3243. RESTAPI.post( _options, function(tokenresp){
  3244. // tokenresp = JSON.parse(tokenresp)
  3245. usertokens[options.username] = tokenresp.sha1
  3246. resolve(tokenresp)
  3247. },
  3248. function(err){ reject(err) }
  3249. )
  3250. }
  3251. else resolve(tokenresp.sha1)
  3252. }
  3253. RESTAPI.get = RESTAPI.post = RESTAPI.method
  3254. return RESTAPI
  3255. })();
  3256. var getHTTPorS = function(options){ return options.protocol.startsWith('https') ? https : http; }
  3257. const GITEA = (function(){
  3258. function GITEA(){}
  3259. GITEA.repository = {
  3260. fork( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  3261. // forkoptions = { owner : httpoptions.username, repo : {{reoptoFork}} }
  3262. // giteaoptions = {
  3263. // organization string
  3264. // --- organization name, if forking into an organization
  3265. // }
  3266. // http://try.gitea.io/api/v1/repos/{owner}/{repo}/forks
  3267. httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}/forks`
  3268. httpoptions.method = 'POST'
  3269. httpoptions.payload = giteaoptions;
  3270. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  3271. }
  3272. , updateattributes( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  3273. httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}`
  3274. httpoptions.method = 'PATCH'
  3275. httpoptions.payload = giteaoptions;
  3276. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  3277. }
  3278. }
  3279. GITEA.user = {
  3280. getuser( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  3281. // ​/users​/{username} // Get a user
  3282. httpoptions.path = `/api/v1/users/${httpoptions.username}`
  3283. httpoptions.method = 'GET'
  3284. return RESTAPI.get(httpoptions, giteaoptions, resolve || function(){}, reject || function(){} )
  3285. }
  3286. }
  3287. return GITEA
  3288. })();
  3289. // Wrapper for Git shell operations. Some meta operations will map to a bunch of GIT commands.
  3290. const GIT = (function(){
  3291. function GIT(){}
  3292. Object.assign(GIT, {
  3293. 'switch user'(username){
  3294. var server = new URL(selectedinstance.reposerver);
  3295. return GITEA.user.getuser({ hostname : server.host, protocol : server.protocol
  3296. , username : selectedinstance.username, password : selectedinstance.password
  3297. }).then(()=>{
  3298. return nodeShellExec('git', ['config', '--replace-all', 'user.name', username],
  3299. {
  3300. inherit: true, shell: true,
  3301. env: process.env
  3302. , cwd: instanceroot + '/' + repo
  3303. , runas: processedArgs.runas
  3304. , title: `'git', ${['config', '--replace-all', 'user.name', username].join(' ')}`
  3305. })
  3306. }
  3307. )
  3308. .catch(e => {
  3309. console.error(e + 'Could not switch. Probably no such user.')
  3310. })
  3311. }
  3312. })
  3313. return GIT
  3314. })();
  3315. function createInstanceData(target, source) {
  3316. var sourceinstance = source || target;
  3317. console.dir(sourceinstance)
  3318. var args = {
  3319. remotebase : sourceinstance.reposerver + '/chess/'
  3320. , sourcerepo : sourceinstance.repo || 'chess-data'
  3321. , targetrepo : `${target.instanceName}-data-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  3322. }
  3323. if(sourceinstance.local) {
  3324. var options = {
  3325. inherit: true, shell: true,
  3326. env: process.env
  3327. , cwd : instanceroot
  3328. , runas: processedArgs.runas
  3329. }
  3330. var cmdseq = [
  3331. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  3332. ]
  3333. return any(cmdseq.map(getshelltask)).then(() => { return true })
  3334. }
  3335. else {
  3336. // http://try.gitea.io/api/v1/org/{org}/repos
  3337. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  3338. throw 'createInstanceData is possible only within the same repository server.'
  3339. }
  3340. var server = new URL(target.reposerver);
  3341. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  3342. , username : target.username, password : target.password
  3343. }
  3344. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  3345. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  3346. return GITEA.repository.updateattributes( {
  3347. hostname : server.host, protocol : server.protocol
  3348. , username : target.username, password : target.password
  3349. }
  3350. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  3351. , { name : `${args.targetrepo}`}
  3352. )
  3353. }
  3354. )
  3355. }
  3356. // GITEA.repository.updateattributes( {
  3357. // hostname : server.host, protocol : server.protocol
  3358. // , username : selectedinstance.username, password : selectedinstance.password
  3359. // }
  3360. // , { repo : `chess-config`, owner : selectedinstance.username }
  3361. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  3362. // )
  3363. // return selectedinstance
  3364. }
  3365. function createInstance(target, source) {
  3366. var sourceinstance = source || target;
  3367. console.dir(sourceinstance)
  3368. var args = {
  3369. remotebase : sourceinstance.reposerver + '/chess/'
  3370. , sourcerepo : sourceinstance.repo || 'chess-config'
  3371. , targetrepo : `${target.instanceName}-config-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  3372. }
  3373. if(sourceinstance.local) {
  3374. var options = {
  3375. inherit: true, shell: true,
  3376. env: process.env
  3377. , cwd : instanceroot
  3378. , runas: processedArgs.runas
  3379. }
  3380. var cmdseq = [
  3381. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  3382. ]
  3383. return any(cmdseq.map(getshelltask)).then(() => { return true })
  3384. }
  3385. else {
  3386. // http://try.gitea.io/api/v1/org/{org}/repos
  3387. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  3388. throw 'createInstance is possible only within the same repository server.'
  3389. }
  3390. var server = new URL(target.reposerver);
  3391. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  3392. , username : target.username, password : target.password
  3393. }
  3394. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  3395. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  3396. return GITEA.repository.updateattributes( {
  3397. hostname : server.host, protocol : server.protocol
  3398. , username : target.username, password : target.password
  3399. }
  3400. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  3401. , { name : `${args.targetrepo}`}
  3402. )
  3403. }
  3404. )
  3405. }
  3406. // GITEA.repository.updateattributes( {
  3407. // hostname : server.host, protocol : server.protocol
  3408. // , username : selectedinstance.username, password : selectedinstance.password
  3409. // }
  3410. // , { repo : `chess-config`, owner : selectedinstance.username }
  3411. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  3412. // )
  3413. // return selectedinstance
  3414. }
  3415. var skipprerequisites = false;
  3416. function initinstances(selected_overrides) {
  3417. var root = selected_overrides.root // We should always have this coz we are running at some place which is fixed by detectLocalInstances.
  3418. var instanceName = selected_overrides.instanceName
  3419. || clioverrides.instanceName
  3420. // || processedArgs._[1]
  3421. || chessinstances.current_run.instanceName
  3422. var node_env = selected_overrides.node_env
  3423. || clioverrides.node_env
  3424. // || processedArgs.node_env
  3425. || chessinstances.current_run.node_env
  3426. var reposerver = selected_overrides.reposerver
  3427. || clioverrides.reposerver
  3428. // || processedArgs.node_env
  3429. || chessinstances.current_run.reposerver
  3430. if(!instanceName) {
  3431. promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  3432. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  3433. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  3434. }
  3435. if(!node_env) {
  3436. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  3437. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  3438. }
  3439. if(!reposerver) {
  3440. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  3441. }
  3442. chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
  3443. instanceName, node_env, root : selected_overrides.root, reposerver : selected_overrides.reposerver /* promptkeys['reposerver'] */ } );
  3444. chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root }
  3445. if(path.normalize(selected_overrides.root) !== path.normalize(chessinstances[instanceName][node_env].root)) {
  3446. 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
  3447. }
  3448. // Override sequence.
  3449. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  3450. // PB : TODO -- Undefined keys are overriding and deleting values. We should not allow that.
  3451. // This is ordinary utils.assign behavior. The key should not exist as undefined in the override.
  3452. if(selected_overrides.node_env === undefined) delete selected_overrides.node_env
  3453. selectedinstance = utils.assign(
  3454. chessinstances[instanceName][node_env]
  3455. , clioverrides
  3456. , selected_overrides
  3457. // , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
  3458. );
  3459. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  3460. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  3461. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  3462. // // Brand New.
  3463. // selectedinstance = Object.assign( __default, selectedinstance )
  3464. // }
  3465. if(!selectedinstance.repos[0].repo) {
  3466. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  3467. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  3468. }
  3469. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  3470. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  3471. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  3472. }
  3473. // Config from server always override merges into selection except for the current selection.
  3474. // PB : TODO -- utils.assign Array merges are non-distinct...
  3475. chessinstances[instanceName][node_env] = selectedinstance;
  3476. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  3477. cacheWriteInstanceConfig(chessinstances)
  3478. // PB : TODO -- We should probably write the new server config also...
  3479. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  3480. return chessinstances
  3481. }
  3482. var skipprereqs = {}
  3483. var maintask = () => {
  3484. // Default cmd to run !
  3485. processedArgs._[0] === processedArgs._[0] || 'pull';
  3486. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  3487. if(!noprerequisites[processedArgs._[0]]
  3488. && !skipprereqs[processedArgs._[0]]
  3489. ) {
  3490. return prerequisites.git.verifyAndInstall().then(()=>{
  3491. var e = { message : 'verifyAndInstall', success : true}
  3492. var inittasks = []
  3493. var commantask = () => { preworkerconfig(); return elxrworker(true) }
  3494. if(!detection_state.localInstanceDetected) {
  3495. var t1 = ()=>{ return createInstance(selectedinstance) };
  3496. t1.statuslog = statuslog
  3497. var specifictask = shell_verse.getNonElevatedTask(t1)
  3498. }
  3499. else {
  3500. var t2 = ()=>{ return acquireConfig(selectedinstance) };
  3501. t2.statuslog = statuslog
  3502. var specifictask = shell_verse.getNonElevatedTask(t2)
  3503. }
  3504. inittasks.push( specifictask().catch((err) => {
  3505. e = err;
  3506. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  3507. console.error(err)
  3508. }).then( commantask )
  3509. // .finally(()=>{
  3510. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  3511. // if(!e.success) fs.writeFileSync('run.done', 'error');
  3512. // // return process.exit()
  3513. // }))
  3514. )
  3515. return any(inittasks)
  3516. })
  3517. }
  3518. else {
  3519. console.log('cmd has no preqs or has been configured to skip preqs')
  3520. preworkerconfig()
  3521. return elxrworker()
  3522. }
  3523. }
  3524. function generateDependencies(){
  3525. // PB : TODO -- Keep only the last n runs...
  3526. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  3527. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
  3528. fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
  3529. // PB : TODO include and build from files... using rollup..
  3530. var downloadbatch =
  3531. `::**************************************************************************
  3532. :Download_ <url> <File>
  3533. Powershell.exe ^
  3534. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  3535. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  3536. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  3537. exit /b
  3538. ::**************************************************************************`
  3539. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch)
  3540. var windowselevate =
  3541. `
  3542. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  3543. <script language="vbscript">
  3544. document.title = "elxr control panel"
  3545. self.ResizeTo 200,600
  3546. Sub Window_Onload
  3547. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  3548. End Sub
  3549. Set objShell = CreateObject("WScript.Shell")
  3550. Set objENV = objShell.Environment("Process")
  3551. dim NODE_ENV
  3552. NODE_ENV = objENV("NODE_ENV")
  3553. </script>
  3554. <script language="javascript">
  3555. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  3556. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  3557. // alert(windowselevate.commandLine)
  3558. var args = windowselevate.commandLine.split('"').slice(3);
  3559. // alert(args)
  3560. var processedArgs = { _ : [] }
  3561. var namedArgs = [];
  3562. namedArgs.push('--wd=' + objENV('wd'))
  3563. // alert(namedArgs)
  3564. for(var item in args){
  3565. if(args[item].charAt(0) === '-'){
  3566. namedArgs.push(args[item])
  3567. var split = args[item].split('=');
  3568. processedArgs[split[0].slice(2)] = split[1] || true;
  3569. }
  3570. else processedArgs._.push(args[item]);
  3571. }
  3572. // args = args.forEach(function(item){ })
  3573. // alert('processedArgs._ : ' + processedArgs._);
  3574. // alert(processedArgs.runas);
  3575. // alert(objENV('wd'))
  3576. // PB : TODO -- Convert all the cli args back to string.
  3577. // __filename will sure we are launhed using the same entry point.
  3578. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' ${__filename.replace(/\\/g, '\\\\')} ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  3579. // alert(cargs)
  3580. var shell = new ActiveXObject('shell.application');
  3581. // alert('launching node privilged. ' + processedArgs['nodepath'])
  3582. // shell.ShellExecute('where', 'node', '', '', 10);
  3583. // shell.ShellExecute('cmd.exe', '/k notepad.exe', '', 'runas', 1);
  3584. // shell.ShellExecute('cmd.exe ', '/k node "' + cargs + '"', '', 'runas', 1);
  3585. shell.ShellExecute('node', cargs, '', 'runas', 1);
  3586. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  3587. var fso = new ActiveXObject('Scripting.FileSystemObject');
  3588. window.onload = function() {
  3589. document.body.style.backgroundColor = 'black';
  3590. document.body.style.fontFamily = 'arial';
  3591. var log = document.createElement('div');
  3592. log.innerHTML='Please Wait';
  3593. function l(msg){ log.innerHTML+= msg; };
  3594. log.style.color = 'blue';
  3595. log.style.width = '95%';
  3596. log.id = 'log';
  3597. document.body.appendChild(log);
  3598. l('<Br/>Current config : ')
  3599. l('<Br/>NODE_ENV = ' + NODE_ENV)
  3600. l('<Br/>cmd = ' + processedArgs._[0])
  3601. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  3602. l('<Br/><Br/>')
  3603. var timer = function(){
  3604. l('.');
  3605. if(fso.FileExists("run.done")) close();
  3606. else window.setTimeout(timer, 1000);
  3607. };
  3608. window.setTimeout(timer, 3000);
  3609. };
  3610. </script>
  3611. </html>
  3612. `
  3613. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate)
  3614. }
  3615. var startElxr = function() {
  3616. const retaincount = 2
  3617. var min = runtimestamp;
  3618. var collect = []
  3619. if(reconfirmcmds[processedArgs.label || processedArgs._[0]]) {
  3620. reconfirm = getReconfirmAll()
  3621. }
  3622. return detectLocalInstances().then((detectedinstanceoptions)=>{
  3623. detectedinstanceoptions.splice(0,0, __default)
  3624. var cmdinstance = cmds[clioverrides.cmd]
  3625. var cmdprompts = cmdinstance.getPossiblePrompts()
  3626. selectedinstance.node_env ? selectedinstance.node_env : selectedinstance.node_env = clioverrides.node_env
  3627. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  3628. selectedinstance = utils.assign( ...detectedinstanceoptions.slice(-2), promptkeys )
  3629. // promptkeys = utils.assign(promptkeys, clioverrides)
  3630. if(cmdprompts.instanceName) {
  3631. // not an instanceless cmd.
  3632. console.dir(selectedinstance)
  3633. try {
  3634. chessinstances = acquirelocalinstances(selectedinstance);
  3635. findlocalinstances(chessinstances, detectedinstanceoptions)
  3636. initinstances(selectedinstance) // use the local instances for defaults if at all possible.
  3637. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  3638. var inst = initinstances(selectedinstance)
  3639. detection_state.localInstanceDetected = true;
  3640. return inst;
  3641. })
  3642. }
  3643. catch (e) {
  3644. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  3645. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  3646. return initinstances(selectedinstance)
  3647. })
  3648. // if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  3649. // // Weve not been told what to do.
  3650. // todo = todo.then(() => { return acquireChoices(selectedinstance) })
  3651. // }
  3652. todo = todo.then(() => {
  3653. try {
  3654. chessinstances = acquirelocalinstances(selectedinstance)
  3655. findlocalinstances(chessinstances, detectedinstanceoptions)
  3656. detectedinstanceoptions.splice(0,0, __default)
  3657. initinstances(selectedinstance)
  3658. detection_state.localInstanceDetected = true;
  3659. }
  3660. catch (e) {
  3661. // console.error(e)
  3662. console.log('No local instances config found in current root = ' + selectedinstance.root);
  3663. console.log('A config will be createed with the instance and environment chosen...')
  3664. // return (async ()=>{return await __default.reposerver})().then(()=>{
  3665. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  3666. // return selectedinstance = Object.assign(__default, selectedinstance);
  3667. // })
  3668. detection_state.localInstanceDetected = false;
  3669. return selectedinstance
  3670. }
  3671. })
  3672. }
  3673. return todo
  3674. }
  3675. else return Promise.resolve(true)
  3676. })
  3677. .then(()=>{
  3678. generateDependencies();
  3679. if(noprerequisites[processedArgs._[0]]
  3680. || skipprereqs[processedArgs._[0]]
  3681. ) {
  3682. return elxrworker()
  3683. }
  3684. var neTask = ()=>{
  3685. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`)
  3686. // collect garbage
  3687. return dirs( (dir)=>{
  3688. var matches = /run-(.*)/gm.exec(dir.name)
  3689. if(matches) {
  3690. if(+(matches[1]) < min) {
  3691. min = matches[1]
  3692. collect.splice( 0, 0, matches[1] )
  3693. }
  3694. else collect.push(matches[1])
  3695. }
  3696. }, `${selectedinstance.root}/.elxr` )
  3697. .then(()=>{
  3698. // delete garbage
  3699. if(collect.length > retaincount) {
  3700. var asyncs = [];
  3701. while((collect.length - asyncs.length) > retaincount) {
  3702. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  3703. }
  3704. return Promise.all(asyncs)
  3705. }
  3706. else return true
  3707. })
  3708. }
  3709. neTask.statuslog = statuslog
  3710. shell_verse.getNonElevatedTask( neTask )()
  3711. var commonTask = ()=>{
  3712. verifyAndInstallPrerequisites.statuslog = statuslog
  3713. if((!skipprerequisites || processedArgs.forceprereqs)) mainTasks.push(verifyAndInstallPrerequisites);
  3714. mainTasks.push(maintask)
  3715. return any(mainTasks);
  3716. }
  3717. return commonTask()
  3718. })
  3719. }
  3720. // PB : TODO -- In windows if we are run from an elevated shell we never move forward and simply exits !?.
  3721. // -- Currently workaround in windows is to always run from a non-elevated shell.
  3722. shell_verse.acquireElevationState().then((elevationstate) => {
  3723. return detectInstanceRoot.then(()=>{
  3724. var cmdobj = cmds[clioverrides.cmd]
  3725. return Promise.all((cmdobj.requires || []).map( (r) => utils.promisify(null, r) ) ).then(()=>{
  3726. if(cmdobj.independentcmd) {
  3727. if(cmdobj.requiresElevation) {
  3728. return cmdobj.cmdFn()
  3729. }
  3730. else return cmdobj.cmdFn()
  3731. }
  3732. else return startElxr()
  3733. })
  3734. .catch(e => {
  3735. if(typeof e === 'symbol') console.log('error : ' + 'symbol')
  3736. else console.log('error : ' + e)
  3737. })
  3738. })
  3739. })
  3740. // .then( () => {
  3741. // console.log(process._getActiveHandles());
  3742. // console.log(process._getActiveRequests());
  3743. // })
  3744. // detect if alread installed -> Take no action.
  3745. // download if no installer avalable -> next()
  3746. // install
  3747. function chackandinstall(items) {
  3748. var tasks = []
  3749. items.forEach(item => {
  3750. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  3751. })
  3752. return Promise.all(tasks).then(existances => {
  3753. existances.forEach((exists, i) => {
  3754. if (!exists) {
  3755. return downloadandinstall([items[i]])
  3756. }
  3757. })
  3758. })
  3759. }
  3760. function downloadandinstall(items) {
  3761. var tasks = []
  3762. items.forEach(item => {
  3763. tasks.push(getTaskDownload(item))
  3764. })
  3765. return Promise.all(tasks)
  3766. }
  3767. // Sample instances config.
  3768. // var instances = {
  3769. // "elixir": {
  3770. // "production": {
  3771. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  3772. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  3773. // , "exludeMergeRepos": {
  3774. // "elixir-config-development": true, "elixir-config-test": true
  3775. // , "elixir-config-production": true, "elixir-data": true
  3776. // }
  3777. // , "instanceName": "elixir", "node_env": "production"
  3778. // }
  3779. // },
  3780. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  3781. // }
  3782. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...