Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

index.js 171KB

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