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

пре 2 година
пре 2 година
пре 2 година
пре 1 година
пре 2 година
пре 2 година
пре 3 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 2 година
пре 2 година
пре 3 година
пре 4 година
пре 1 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 1 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 2 година
пре 1 година
пре 2 година
пре 2 година
пре 2 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 2 година
пре 2 година
пре 1 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 2 година
пре 1 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 2 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 1 година
пре 3 година
пре 1 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 1 година
пре 3 година
пре 2 година
пре 1 година
пре 2 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 3 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 3 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 1 година
пре 3 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 6 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 2 година
пре 1 година
пре 2 година
пре 3 година
пре 1 година
пре 3 година
пре 3 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 3 година
пре 1 година
пре 2 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 3 година
пре 1 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 1 година
пре 1 година
пре 3 година
пре 1 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 3 година
пре 1 година
пре 3 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 1 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 2 година
пре 1 година
пре 3 година
пре 2 година
пре 3 година
пре 2 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
пре 3 година
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510
  1. 
  2. // {{!-- https://corporatefinanceinstitute.com/resources/knowledge/accounting/general-ledger-gl/ --}}
  3. "use strict";
  4. // console.log([ 'If this is colorized we have color output...' ])
  5. // console.dir(process.env)
  6. var __g = require('global-this');
  7. var ENV = Object.assign({}, process.env); // Shallow clone so we can set values and reuse for reshelling spawns.
  8. __g.env = ENV
  9. ENV.NODE_ENV = (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || 'development'
  10. const fs = require('fs')
  11. var path = require('path');
  12. var utils = require('bbhverse');
  13. var any = utils.any;
  14. var Tasq = utils.Tasq
  15. var statuslog = utils.Traq
  16. var Traq = utils.Traq
  17. // console.error('EEEEEEEEEEEEEEEEEEEE')
  18. var util = require('util')
  19. var ENV = Object.assign({}, process.env); // Shallow clone so we can set values and reuse for reshelling spawns.
  20. const cliargs = utils.cliargs;
  21. const processedArgs = cliargs(process.argv.slice(2));
  22. const __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b'
  23. const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  24. const runtimestamp = processedArgs.runtimestamp ? (new Date(processedArgs.runtimestamp)).getTime() : (new Date()).getTime();
  25. function getVersion() { return BUILD_VERSION; }
  26. // 'use strict';
  27. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  28. // PB : TODO --
  29. // runas bypass non elevated tasks when we request privelege
  30. // runas message is always error needs to be fixed.
  31. // runas wait needs to be parallelized.
  32. // suppress elevation check error messages
  33. // support runas lauched directly from shell.
  34. // pass in environment in hta to shellexecute.
  35. const https = require('https')
  36. const http = require('http');
  37. const { Console } = require('console');
  38. const { env } = require('process');
  39. const RESTAPI = (function(){
  40. // Singleton
  41. function RESTAPI(){}
  42. // RESTAPI.create = RESTAPI; // Returns the one singe instance which is the class itself
  43. // const httpsoptions = {
  44. // hostname: 'whatever.com',
  45. // port: 443,
  46. // path: '/todos',
  47. // method: 'POST',
  48. // headers: {
  49. // 'Content-Type': 'application/json',
  50. // 'Content-Length': data.length
  51. // }
  52. // }
  53. RESTAPI.method = function(options, resolve, reject){
  54. options.headers = options.headers || { 'Content-Type': 'application/json' }
  55. const data = options.payload ? new TextEncoder().encode( JSON.stringify(options.payload) ) : null
  56. options.headers = options.payload ? (options.headers || {
  57. 'Content-Type': 'application/json',
  58. 'Content-Length': data.length
  59. }) : (options.headers || {})
  60. !options.headers.Authorization && usertokens[options.username] ? (()=>{
  61. options.headers.Authorization = `token ${usertokens[options.username]}`
  62. delete options.username
  63. onauthenticated()
  64. })() : (()=>{
  65. if(!usertokens[options.username] && !options.isAuthCall) {
  66. RESTAPI.authenticate( utils.assign( {isAuthCall : true}, options ) , onauthenticated, function(err){
  67. // PB : TODO -- Retry without auth...
  68. console.error('Auth failed or not accessible')
  69. reject(err)
  70. })
  71. }
  72. else onauthenticated()
  73. })()
  74. function onauthenticated(){
  75. var acquirer = getHTTPorS(options)
  76. const req = acquirer.request(options, res => {
  77. if (res.statusCode < 200 || res.statusCode >= 300) {
  78. // new Error('statusCode=' + res.statusCode)
  79. return reject('statusCode = ' + res.statusCode);
  80. }
  81. var body = [];
  82. // res.setEncoding('utf8');
  83. res.on('data', (chunk)=>{ body.push(chunk); });
  84. res.on('end', ()=>{
  85. try {
  86. if(res.headers['content-type'] && res.headers['content-type'].split(';').find( (i)=> i.trim() === 'application/json' )) body = JSON.parse(Buffer.concat(body).toString());
  87. else body = Buffer.concat(body).toString();
  88. } catch(e) { return reject(e); }
  89. resolve(body);
  90. });
  91. });
  92. req.on('error', error => { reject(error) })
  93. if(options.payload) req.write(data)
  94. req.end()
  95. }
  96. }
  97. var usertokens = {}
  98. RESTAPI.authenticate = function(options, resolve, reject){
  99. options.headers = options.headers || { 'Content-Type': 'application/json' }
  100. if(!usertokens[options.username]) {
  101. // Authenticate and acquire token.
  102. // https://git.bbh/api/v1/users/<username>/tokens
  103. // curl -XPOST -H "Content-Type: application/json" -k -d '{"name":"demo"}' -u demo:demo123 http://git.bbh/api/v1/users/demo/tokens
  104. var _options = Object.assign({}, options)
  105. // _options.username = 'demo'
  106. // _options.password = 'demo123'
  107. _options.method = 'POST'
  108. _options.headers.Authorization = `Basic ${Buffer.from(`${_options.username}:${_options.password}`).toString('base64')}`
  109. _options.path = `/api/v1/users/${_options.username}/tokens`
  110. var postoptions = { name : _options.username }
  111. delete _options.username
  112. delete _options.password
  113. _options.payload = postoptions
  114. RESTAPI.post( _options, function(tokenresp){
  115. // tokenresp = JSON.parse(tokenresp)
  116. usertokens[options.username] = tokenresp.sha1
  117. resolve(tokenresp)
  118. },
  119. function(err){ reject(err) }
  120. )
  121. }
  122. else resolve(tokenresp.sha1)
  123. }
  124. RESTAPI.put = RESTAPI.get = RESTAPI.post = RESTAPI.method
  125. return RESTAPI
  126. })();
  127. var getHTTPorS = function(options){ return options.protocol.startsWith('https') ? https : http; }
  128. const GITEA = (function(){
  129. function GITEA(){}
  130. GITEA.APIROOT = '/api/v1'
  131. GITEA.repository = {
  132. fork( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  133. // forkoptions = { owner : httpoptions.username, repo : {{reoptoFork}} }
  134. // giteaoptions = {
  135. // organization string
  136. // --- organization name, if forking into an organization
  137. // }
  138. // http://try.gitea.io/api/v1/repos/{owner}/{repo}/forks
  139. httpoptions.path = `${GITEA.APIROOT}/repos/${cmdoptions.owner}/${cmdoptions.repo}/forks`
  140. httpoptions.method = 'POST'
  141. httpoptions.payload = giteaoptions;
  142. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  143. }
  144. , updateattributes( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  145. httpoptions.path = `${GITEA.APIROOT}/repos/${cmdoptions.owner}/${cmdoptions.repo}`
  146. httpoptions.method = 'PATCH'
  147. httpoptions.payload = giteaoptions;
  148. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  149. }
  150. , exists( httpoptions, repo, owner ) {
  151. // ​/users​/{username} // Get a user
  152. httpoptions.path = `${GITEA.APIROOT}/repos/${owner}/${repo}`
  153. httpoptions.method = 'GET'
  154. return new Promise( (resolve, reject) => {
  155. RESTAPI.get(httpoptions, function(o){
  156. if(o.id) return resolve(true)
  157. return resolve(false) }, reject || function(){ return false } )
  158. })
  159. }
  160. , addcollaborator( httpoptions, repodef, owner, collaborator, permission ) {
  161. permission = permission || 'Read'
  162. httpoptions.payload = { permission }
  163. httpoptions.path = `${GITEA.APIROOT}/repos/${owner}/${repodef.repo}/collaborators/${collaborator}`
  164. httpoptions.method = 'PUT'
  165. return new Promise( (resolve, reject) => {
  166. RESTAPI.put(httpoptions, function(o){
  167. //
  168. if(o === "") return resolve(true)
  169. return resolve(false) }, reject || function(){ return false } )
  170. })
  171. }
  172. }
  173. GITEA.user = {
  174. getuser( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  175. // ​/users​/{username} // Get a user
  176. httpoptions.path = `${GITEA.APIROOT}/users/${httpoptions.username}`
  177. httpoptions.method = 'GET'
  178. return RESTAPI.get(httpoptions, giteaoptions, resolve || function(){}, reject || function(){} )
  179. }
  180. }
  181. return GITEA
  182. })();
  183. // Wrapper for Git shell operations. Some meta operations will map to a bunch of GIT commands.
  184. const GIT = (function(){
  185. function GIT(){}
  186. Object.assign(GIT, {
  187. 'switch user'(username){
  188. var httpoptions = new URL(selectedinstance.reposerver);
  189. httpoptions.username = selectedinstance.username
  190. httpoptions.password = selectedinstance.password
  191. return GITEA.user.getuser(httpoptions).then(()=>{
  192. return nodeShellExec('git', ['config', '--replace-all', 'user.name', username],
  193. {
  194. inherit: true, shell: true,
  195. env: ENV
  196. , cwd: instanceroot + '/' + repo
  197. , runas: processedArgs.runas
  198. , title: `'git', ${['config', '--replace-all', 'user.name', username].join(' ')}`
  199. })
  200. }
  201. )
  202. .catch(e => {
  203. console.error(e + 'Could not switch. Probably no such user.')
  204. })
  205. }
  206. })
  207. return GIT
  208. })();
  209. // PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
  210. (function () {
  211. "use strict";
  212. if (!Array.prototype.earlyreduce) {
  213. Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
  214. var iterable = this;
  215. var donecallback = donecallback || (a=>a)
  216. var result = { value : initialValue === undefined ? iterable[0] : initialValue };
  217. initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
  218. // function *earlyReduceGenerator(acc, v, i, a) {
  219. for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
  220. var element = iterable[i]
  221. result = eachcallback(result, element, i, iterable)
  222. if(result.done) return donecallback(result)
  223. }
  224. // }
  225. return donecallback(result)
  226. }
  227. }
  228. }());
  229. function isWin(){ return /^win/.test(process.platform) }
  230. if(isWin()) {
  231. var win_verse = require('./win_verse')
  232. var shell_verse = win_verse;
  233. }
  234. else {
  235. var lin_verse = require('./lin_verse')
  236. var shell_verse = lin_verse;
  237. }
  238. // PB : TODO -- In windows if we are run from an elevated shell we never move forward and simply exits !?.
  239. // -- Currently workaround in windows is to always run from a non-elevated shell.
  240. shell_verse.acquireElevationState().then((isElevated) => {
  241. // PB : TODO -- Implement queues using streams. Specially form bundling all elevated tasks as a single out of proc run with post elevated queue run postponed until the elevated stream and its dependencies are completed....
  242. const { existsSync } = require('fs');
  243. const existslink = function(name, cb){
  244. fs.lstat(name, (error, stats) => {
  245. if (error) {
  246. console.log(error);
  247. cb(error)
  248. }
  249. else {
  250. console.log("Stats object for: example_directory.txt");
  251. console.log(stats);
  252. // Using methods of the Stats object
  253. console.log("Path is file:", stats.isFile());
  254. console.log("Path is directory:", stats.isDirectory());
  255. cb(null, true)
  256. }
  257. });
  258. }
  259. const existsFolderSync = existsSync;
  260. var hasElxr = function(path, options, cb) {
  261. // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
  262. options = options || {};
  263. var tasks = [
  264. '/elxr' // Is there a subfolder named elxr
  265. , '/elxr/.git' // which is also a git repository
  266. // , '/elxr/.elxr' // and has .elxr subfolder we now store this in the instanceroot.
  267. , '/elxr/' + __ALIAS__STAMP__ // Which has our stamp.
  268. ]
  269. if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
  270. var value = existsFolderSync(path + tpath);
  271. return { value, done : acc && !value };
  272. }).value }
  273. if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
  274. var value = existsFolderSync(path + tpath);
  275. return { value, done : acc && !value };
  276. }).value );
  277. return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
  278. var value = existsFolderSync(path + tpath);
  279. return { value, done : acc && !value };
  280. }).value);
  281. }
  282. var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); }
  283. 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
  284. var root = process.cwd() // Root need not be the launchdir...
  285. // wd is our own environment variable probably corresponding to the root but need not be the same.
  286. // console.log(processedArgs.root)
  287. // console.log('PWD :' + ENV.PWD)
  288. // console.log('cwd : ' + process.cwd())
  289. // console.log('launchscriptdir : ' + path.normalize(__dirname))
  290. if(!processedArgs.root){
  291. if(!process.env.wd){
  292. console.log('discovery')
  293. // Script may exists in the same location where we were launched(PWD) but that doesn't mean we r running from elxr.
  294. // script could have been copied tosome random location and run from there.
  295. // check elxr is preinstalled in same location. If so we need to chdir to parent. Else promt for confirmation of root.
  296. var launchdir = /*process.env.PWD ||*/ process.cwd() // mingw + node --inspect-brk behaves differently has a PWD that windows commands cannot recognize /d instead of D:\ and process.chdir fails..
  297. var parentdir = path.dirname( launchdir )
  298. var parentFolderHasElxr = hasElxrSync(parentdir)
  299. var launchFolderHasElxr = hasElxrSync(launchdir)
  300. if( parentFolderHasElxr && (path.normalize(parentdir + '/elxr') === thisscriptdir)) {
  301. // We were run from the proper root with elxr cli in the subfolder.
  302. // PB : TODO -- Cleanup this should no longer be needed... selectedinstance is properly initialized...
  303. // instanceroot = root = selectedinstance.root;
  304. // instanceoptions.splice( 0, 0, detected = { root })
  305. // instanceoptions.splice( 0, 0, detectfromroot(root))
  306. root = ENV.wd = parentdir; // Default to the parent.
  307. }
  308. else {
  309. if( path.normalize(parentdir + '/elxr') === thisscriptdir ) {
  310. // launchFolderHasElxr is false -- and yet thiscriptdir is still proper.
  311. // PB : TODO -- Maybe a warning / abort if for some reason thisscriptdir should not be used...
  312. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.')
  313. // instanceoptions.splice( 0, 0, detected = { root })
  314. // instanceoptions.splice( 0, 0, detectfromroot(root))
  315. root = ENV.wd = parentdir; // Default to the parent.
  316. }
  317. else if (launchdir === thisscriptdir) {
  318. // Same directory doesn't mean we are being run from elxr sub directory. It could be a dislocated standalone elxr script.
  319. // PB : TODO -- In case elxr is not full elxr we need to locate it and relaunch to switch to the full version...
  320. // if(!parentFolderHasElxr) console.error('Invalid run location in subfolder that looks like elxr. We should probably abort.')
  321. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  322. // Confirmed we were run from an Unbuilt ( meaning non standalone ) elxr therefore we are in the elxr sub directory.
  323. root = ENV.wd = parentdir; // Default to the parent.
  324. // instanceroot = root = path.normalize(selectedinstance.root + '/..');
  325. // instanceoptions.splice( 0, 0, detected = { root });
  326. // instanceoptions.splice( 0, 0, detectfromroot(root));
  327. }
  328. else {
  329. // In standalone build script we may or not be in the same location.
  330. if(!parentFolderHasElxr) {
  331. // We could have been run from the elxr subfolder. However we cant say for sure.
  332. // Most likely that the built version isn't the full elxr. We assume elxr doesnt exist and create an new elxr under..
  333. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.')
  334. root = ENV.wd = launchdir;
  335. }
  336. else {
  337. // Built version was run from the full elxr subfolder
  338. root = ENV.wd = parentdir; // Default to the parent.
  339. // instanceoptions.splice( 0, 0, detected = { root })
  340. // instanceoptions.splice( 0, 0, detectfromroot(root))
  341. // Assume current selectedinstance.root is a new instance and create.
  342. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  343. // if(clioverrides.instanceName) {
  344. // if(clioverrides.node_env) {
  345. // instanceroot = root = path.normalize(selectedinstance.root + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  346. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  347. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  348. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  349. // // eg : floder name can be elixir01 but instance name is elixr
  350. // }
  351. // else {
  352. // instanceroot = root = path.normalize(selectedinstance.root + '/' + clioverrides.instanceName + '/' + 'development')
  353. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  354. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  355. // }
  356. // }
  357. // else {
  358. // instanceroot = root = selectedinstance.root;
  359. // if(clioverrides.node_env) {
  360. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  361. // instanceoptions.splice( 0, 0, detectfromroot(root))
  362. // }
  363. // else {
  364. // // Nothing was specified... We only have one option from root.
  365. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  366. // }
  367. // }
  368. }
  369. }
  370. }
  371. else if(launchFolderHasElxr) {
  372. root = ENV.wd = launchdir;
  373. // instanceoptions.splice( 0, 0, detected = { root })
  374. // instanceoptions.splice( 0, 0, detectfromroot(root))
  375. }
  376. else {
  377. // Ambiguous but assume script is standalone in the instanceroot.
  378. root = ENV.wd = launchdir;
  379. // must be a new install in the selectedinstance.root with script invoked from some random location.
  380. }
  381. }
  382. }
  383. else root = ENV.wd = process.env.wd
  384. }
  385. else {
  386. if(process.env.wd && process.env.wd !== processedArgs.root) throw 'wd and root must match.'
  387. root = ENV.wd = process.env.wd = processedArgs.root
  388. }
  389. var instanceroot = root
  390. ENV.PWD = ENV.wd
  391. ENV.NODE_ENV = processedArgs.node_env || (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || 'development'
  392. console.log('----------------------------------------------------------------')
  393. console.log('version : ' + getVersion());
  394. console.log('process.env.wd : ' + process.env.wd)
  395. console.log('processedArgs.root : ' + processedArgs.root)
  396. console.log('----------------------------------------------------------------')
  397. console.log('wd :' + ENV.wd)
  398. process.chdir(ENV.wd) // Ensure cwd is the actual working dir.
  399. console.log('PWD :' + ENV.PWD)
  400. console.log('cwd : ' + process.cwd())
  401. console.log(`thisscriptdir = ${thisscriptdir}`)
  402. console.log('----------------------------------------------------------------')
  403. var cli = require('./cliverse')
  404. // throw 'initbreak'
  405. // We no longer use this Folder name may be different from instanceName
  406. // var detectfromroot = function(root){
  407. // return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(root) ) }
  408. // }
  409. // independent elxr cli operations
  410. var noprerequisites = {
  411. add : true, 'set-url' : true, 'repo-relocate' : true
  412. , remote : true, 'c' : true, 'h' : true
  413. , httpget : true, getuser : true
  414. , 'switch user' : true
  415. , 'switch' : true
  416. // , 'undefined' : true
  417. }
  418. var __default = {
  419. // Common baseline repos for all chess chessinstances.
  420. repos : [
  421. { repo : 'ember-masonry-grid' /*, branch : master*/ } // Default need not be specified.
  422. , { repo : 'bbhverse' }
  423. , { repo : 'clientverse' }
  424. , { repo : 'serververse' }
  425. , { repo : 'elxr' }
  426. , { repo : 'ember-searchable-select' }
  427. , { repo : 'loopback-component-jsonapi' }
  428. , { repo : 'loopback-jsonapi-model-serializer' }
  429. , { repo : 'loopback-connector-mysql' }
  430. , { repo : 'loopback-connector-ds' }
  431. , { repo : 'ember-service-worker' }
  432. , { repo : 'ember-service-worker-asset-cache' }
  433. , { repo : 'ember-service-worker-cache-fallback' }
  434. , { repo : 'ember-service-worker-index' }
  435. , { repo : 'ember-sw-client-route' }
  436. , { repo : 'global-this' }
  437. ]
  438. // Requires elevation only in windows
  439. , elevated : [ { repo : 'chess-server-lib', requiresElevation : true } ]
  440. , exludeMergeRepos : { }
  441. }; // PB : TODO -- Use initialized instance instead of __default everywhere.
  442. var cmds = {
  443. remote : {
  444. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  445. , { cmd : processedArgs._.slice(0, 2).join(' '), runchoice : 'c' }) }
  446. , noprerequisites : true
  447. , independentcmd : true
  448. }
  449. , start : {
  450. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  451. , { cmd : 'start', runchoice : 'c'
  452. , node_env : ENV.NODE_ENV, root : ENV.wd, instanceType : ENV.NODE_ENV
  453. })}
  454. }
  455. , 'remote refresh' : {
  456. // return a interpreted set of arguments for this cmd run context.
  457. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  458. , { cmd : 'remote refresh', runchoice : 'c' }) }
  459. , noprerequisites : true
  460. , independentcmd : true
  461. // , requires : [ generateDependencies ]
  462. , toArgs : function( o ){
  463. return o
  464. }
  465. }
  466. , 'remote set-url' : {
  467. // return a interpreted set of arguments for this cmd run context.
  468. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  469. , { cmd : 'remote set-url', runchoice : 'c' }) }
  470. , noprerequisites : true
  471. , independentcmd : true
  472. // , requires : [ generateDependencies ]
  473. }
  474. , 'remote add' : {
  475. // return a interpreted set of arguments for this cmd run context.
  476. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  477. , { cmd : 'remote add', runchoice : 'c' }) }
  478. , noprerequisites : true
  479. , independentcmd : true
  480. // , requires : [ generateDependencies ]
  481. }
  482. , 'remote remove' : {
  483. // return a interpreted set of arguments for this cmd run context.
  484. interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  485. , { cmd : 'remote remove', runchoice : 'c' }) }
  486. , noprerequisites : true
  487. , independentcmd : true
  488. }
  489. , 'addcollaborator' : {
  490. // Usage :
  491. // elxr addcollaborator instancename developer
  492. cmdFn : function(args){
  493. var __each = function(args){
  494. var collaborator = args.collaborator;
  495. if(!collaborator) {console.error('Error : collaborator required'); throw 'Error : collaborator required' }
  496. var repo = args.repo
  497. var remotename = 'chess'
  498. var repodef = selectedinstance.reposindexed[repo];
  499. if(!repodef) return
  500. var remotenames = (selectedinstance.selectedremotes || []).concat( selectedinstance.permanentremotes )
  501. var remotes = selectedinstance.reposerverinstances[selectedinstance.reposerver].remotes
  502. // console.log('-----------------------------------------------------')
  503. // console.log(repo)
  504. // // console.dir(remotes)
  505. // console.log('-----------------------------------------------------')
  506. // PB : TODO -- pick up remote definitions per repository...
  507. var reposmanfiest = utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  508. , {}, selectedinstance, loadmanifest( selectedinstance.root + '/' + repo
  509. , { utils, username : selectedinstance.username, instanceName : selectedinstance.instanceName
  510. , node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver }
  511. ))
  512. if( !reposmanfiest.error ) {
  513. var reporemotenames = remotenames.concat(reposmanfiest.selectedremotes || []).concat( reposmanfiest.permanentremotes || [] )
  514. var reporemotes = utils.assign(remotes, reposmanfiest.reposerverinstances[selectedinstance.reposerver].remotes)
  515. }
  516. else {
  517. var reporemotenames = remotenames
  518. var reporemotes = remotes
  519. }
  520. var remote = reporemotes[remotename]
  521. var reposerver = repodef.server || remote.server || selectedinstance.reposerver
  522. // selectedinstance.reposerverinstances[reposerver]
  523. var auth = repodef.username ? repodef : remote.username ? remote : selectedinstance.reposerverinstances[reposerver].username ? reposerver : selectedinstance;
  524. var httpoptions = new URL(reposerver);
  525. httpoptions = {
  526. hostname: httpoptions.hostname
  527. , protocol : httpoptions.protocol
  528. }
  529. httpoptions.username = auth.username // PB : TODO -- Handle remotes with different username. Also cache git credentials either globally or per repo...
  530. // PB : TODO -- handle credentials properly. cant mix and match passwords..
  531. httpoptions.password = (auth.password || selectedinstance.password || '') // PB : NOTE URL has some kind of a setter for password which converts to string "undefined" as password which is undesirable.. so we pre resolve and send.
  532. // console.log(___args)
  533. // PB : TODO -- Check valid collaborator before adding...
  534. return GITEA.repository.addcollaborator(httpoptions, repodef, remote.owner, collaborator).then( v => {
  535. if(v === true) {
  536. console.log('-----------------------------------------------------')
  537. console.log('addcollaborator successful for ' + repo + ' ' + collaborator)
  538. console.log('-----------------------------------------------------')
  539. }
  540. } )
  541. }
  542. var promises = []
  543. var repos = Object.keys(selectedinstance.reposindexed)
  544. repos.forEach(repo => { promises.push(__each({ repo, collaborator : args._[2]})) }) // PB : TODO -- Move to toArgs.
  545. return Promise.all(promises).then(pr => { console.log('addcollaborator done') })
  546. }
  547. }
  548. , 'isurlaccessible' : {
  549. noprerequisites : true
  550. , independentcmd : true
  551. , toArgs : function( o ){
  552. return { url : o._[1] }
  553. }
  554. }
  555. , resetgitconfig : {
  556. // return a interpreted set of arguments for this comd run context.
  557. // cmdFn : resetgitconfig,
  558. interpret() { return { cmd : 'resetgitconfig' } }
  559. , noprerequisites : true
  560. , independentcmd : true
  561. }
  562. , reinit : {
  563. // return a interpreted set of arguments for this comd run context.
  564. // cmdFn : reinit
  565. // ,
  566. interpret() { return { cmd : 'reinit' } }
  567. , noprerequisites : true
  568. , independentcmd : true
  569. , requiresElevation : true
  570. // , requires : [ generateDependencies ]
  571. }
  572. , init : {
  573. // return a interpreted set of arguments for this comd run context.
  574. // cmdFn : init
  575. // ,
  576. interpret() { return { cmd : 'init' } }
  577. , noprerequisites : true
  578. , independentcmd : true
  579. , requiresElevation : true
  580. // , requires : [ generateDependencies ]
  581. }
  582. , switch : {
  583. interpret() {
  584. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2]
  585. , reposerver : __default.reposerver // .?.?.?
  586. }
  587. }
  588. , getPossiblePrompts(){ return { username : true, reposerver : 'http://git.bbh' } } // Requires only one argument...
  589. }
  590. , 'switch user' : {
  591. interpret() {
  592. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2] }
  593. }
  594. , getPossiblePrompts(){ return { username : true } } // Requires only one argument...
  595. }
  596. // Flat linear structure. Every subcommand should have a top level 'label'
  597. , 'users' : {
  598. // default to the users list
  599. subcommands : { list : {} }
  600. , cmdFn : ()=>getCredentials() // default
  601. , cmd : 'users'
  602. , noprerequisites : true
  603. }
  604. , 'users list' : {
  605. cmdFn : ()=>getCredentials()
  606. , cmd : 'users list'
  607. , noprerequisites : true
  608. }
  609. , 'get-upstream' :{
  610. // cmdFn : op['get-upstream'] // default
  611. // ,
  612. cmd : 'get-upstream'
  613. , noprerequisites : true
  614. , independentcmd : true
  615. , interpret() { return { cmd : 'get-upstream' } }
  616. }
  617. , 'g' : {
  618. cmd : 'g'
  619. , noprerequisites : true
  620. }
  621. , 'link' : {
  622. 'cmd' : 'link'
  623. // , cmdFn : function( sourecpath, filename, dir ){
  624. // var afterTargetPath = (dir)=>{
  625. // console.dir(dir);
  626. // // var tasks = [
  627. // // () => {
  628. // // // Use junctions to avoid npm package issues
  629. // // var p = nodeShellExec('mklink', ['/J', filename, sourecpath], {
  630. // // inherit: true, shell: true
  631. // // , cwd : dir || instanceroot
  632. // // , env: ENV
  633. // // }).catch((e) => { console.error(e) })
  634. // // return p;
  635. // // }
  636. // // ];
  637. // }
  638. // // console.dir(ENV)
  639. // if(!dir) getCurrentFolder().then(afterTargetPath);
  640. // else afterTargetPath(dir)
  641. // }
  642. , cmdFn : function( cmdopts ){
  643. // sourecpathandfile should include name of file name
  644. targetfilename = cmdopts.targetfilename || processedArgs._[1]
  645. // console.log(processedArgs)
  646. if(!targetfilename) return Promise.reject('error no file provided for linking')
  647. targetdir = cmdopts.targetdir || ENV.wd
  648. sourecpathandfile = cmdopts.sourecpathandfile || path.normalize(`../../node_modules/chess-server-lib/common/models/${targetfilename}`)
  649. var tasks = [
  650. () => {
  651. // Use junctions to avoid npm package issues
  652. var p = nodeShellExec('mklink', [path.normalize(`${targetdir + '/' + targetfilename}`), sourecpathandfile], {
  653. inherit: true, shell: true
  654. , cwd : targetdir
  655. , env: ENV
  656. }).catch((e) => { console.error(e) })
  657. return p;
  658. }
  659. ];
  660. var etask = ()=>{
  661. return any(tasks).then(() => {
  662. fs.writeFileSync('run.done', 'success')
  663. }).catch(() => {
  664. fs.writeFileSync('run.done', 'error')
  665. })
  666. }
  667. etask.statuslog = statuslog
  668. etask.selectedinstance = selectedinstance
  669. etask.processedArgs = processedArgs
  670. etask.runtimestamp = runtimestamp
  671. etask.ENV = ENV
  672. return shell_verse.runElevated(etask)
  673. }
  674. , noprerequisites : true
  675. , privileged : true
  676. }
  677. }
  678. function interpret() {
  679. var interpreted = this
  680. // Non custom command has universal positiona args.
  681. processedArgs._[1] ? interpreted.instanceName = processedArgs._[1] : null;
  682. interpreted.runchoice = interpreted.cmd ? 'c' : null
  683. // interpreted.runchoice = processedArgs._[0] || selectedinstance.runchoice;
  684. // return clioverrides
  685. // cmds[cmd] = {
  686. // interpret() {
  687. // return Object.assign(clioverrides, { cmd, runchoice : 'c' })
  688. // }
  689. // , getPossiblePrompts(){ return { cmd, username : true, password : true,
  690. // instanceName : true, instanceType : true, reposerver : true } }
  691. // }
  692. // ... PB : TODO -- use cmd.toArgs
  693. // interpreted.cmd = this.cmd
  694. return interpreted
  695. }
  696. var interpretrun = function(){
  697. var cmd = processedArgs._[0];
  698. return cmds[cmd] && cmds[cmd].interpret ? cmds[cmd].interpret() : (function(){
  699. return cmds[cmd] = utils.assign(cmds[cmd] || {}, interpret.call({ cmd, toArgs : function( o ){
  700. // PB : TODO -- need to call this before selectedinstance is built. The instanceName is dependent on the specific cmd.
  701. return o } }))
  702. })()
  703. }
  704. var chessinstances = { current_run : {} };
  705. var clioverrides = interpretrun()
  706. clioverrides = utils.assign( { cmd : processedArgs._[0], node_env : ENV.NODE_ENV, root : ENV.wd, instanceType : ENV.NODE_ENV }
  707. , clioverrides, cmds[clioverrides.cmd].toArgs(processedArgs), { root : ENV.wd } )
  708. function acquirelocalinstances(selected){
  709. // utils.assign is used to cleanup duplicates... assuming it is probably not clean.
  710. // PB : TODO -- if require fails decipher instanceName from findlocalinstances using the root...
  711. try { var existinglocalinstances = require(path.normalize(selected.root + '/chessinstances.js'))}
  712. catch(e){
  713. console.warn( 'Local instances not found.' ) // This is not an error. A new fresh instance is probably being setup.
  714. var existinglocalinstances = { current_run : {}, error : true }
  715. }
  716. chessinstances = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }, existinglocalinstances);
  717. // console.dir(chessinstances)
  718. return chessinstances
  719. }
  720. function findlocalinstances(chessinstances, instanceoptions){
  721. // We can expect a .elxr at each level in folder and 2 levels up. higher up we will find a shared instance chessinstances.js
  722. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../../' /* instanceNames */].
  723. earlyreduce( ( reduced, p, i, a )=>{
  724. var localinstancesPath = `${instanceroot}/${p}.elxr`;
  725. if(existsSync( localinstancesPath )) {
  726. try {
  727. acquirelocalinstances( { root : `${instanceroot}/${p}` } )
  728. if(chessinstances.error) {
  729. delete chessinstances.error; delete chessinstances.e
  730. return {}
  731. }
  732. return Object.keys(chessinstances).earlyreduce( ( reduced, instanceName) => {
  733. return Object.keys(chessinstances[instanceName]).earlyreduce( (reduced, instanceType) => {
  734. // Scan to find a matching instanceroot
  735. if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize( instanceroot) ) {
  736. instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType])
  737. return {
  738. value : chessinstances[instanceName][instanceType]
  739. , done : true
  740. };
  741. }
  742. })
  743. })
  744. }
  745. catch(e){
  746. return { }
  747. }
  748. }
  749. else return { }
  750. }
  751. )
  752. }
  753. // PB : TODO -- Move this to utils assign... as an array merge option.
  754. var mergeObjByKey = function(arrOfObjs, keyName) {
  755. var keyedDistinct = {}
  756. var distinctArrOfObjs = []
  757. arrOfObjs.forEach( o => {
  758. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o)
  759. })
  760. Object.keys(keyedDistinct).forEach(key => {
  761. distinctArrOfObjs.push( utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  762. , ...keyedDistinct[key] ) ) // PB : TODO -- Shallow use utils.assign
  763. })
  764. return distinctArrOfObjs;
  765. }
  766. var cacheWriteInstanceConfig = function(chessinstances, instanceroot, selectedinstance){
  767. if(selectedinstance) {
  768. var instanceName = selectedinstance.instanceName ;
  769. var node_env = selectedinstance.node_env;
  770. // PB : TODO -- handle current_run switch...
  771. // console.dir(chessinstances)
  772. // PB : TODO -- We should be able to do simply merge at a higher level using assign
  773. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos || [], 'repo') ;
  774. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated || [], 'repo') ;
  775. }
  776. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  777. }
  778. var loadmanifest = function( mpath, moverrides ){
  779. try {
  780. // PB : TODO -- pick up remote definitions per repository...
  781. return utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  782. , {}, require(path.normalize( mpath + '/repo-manifest'))( null, moverrides ))
  783. }
  784. catch(e){
  785. // console.warn(e);
  786. return utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }, { error : true, e }, moverrides)
  787. }
  788. }
  789. var getReconfirmAll = ()=>{return { instanceName : true, instanceType : true, reposerver : true, username : true, password : true } }
  790. if(clioverrides.reconfirm) {
  791. var reconfirm = getReconfirmAll()
  792. }
  793. else { var reconfirm = {}; }
  794. var shouldPrompt = function(k, possiblePrompts, target){
  795. return ((possiblePrompts[k] !== undefined && possiblePrompts[k] !== null) && target[k] !== possiblePrompts[k]
  796. || (possiblePrompts[k] === undefined || possiblePrompts[k] === null) && (target[k] === undefined || target[k] === null)
  797. || reconfirm[k])
  798. }
  799. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  800. return {
  801. get (){
  802. return any( promptable.dependencies || [] ).then(()=>{
  803. return cli.prompt( promptable.choices, promptable.label, promptable.defaultchoice, promptable.selectedchoice ).then(propValue => {
  804. var asyncprop = Promise.resolve(propValue)
  805. if(promptable.interpret){
  806. asyncprop = promptable.interpret(propValue)
  807. }
  808. return asyncprop.then(
  809. ()=>{
  810. Object.defineProperty(this, propName, {
  811. value: propValue,
  812. writable: true,
  813. configurable : true,
  814. enumerable : true
  815. });
  816. return propValue
  817. }
  818. )
  819. })
  820. } )
  821. }
  822. // , set (propValue){
  823. // Object.defineProperty(this, propName, {
  824. // value: propValue,
  825. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  826. // configurable : true,
  827. // enumerable : true
  828. // })
  829. // return propValue;
  830. // }
  831. , configurable : true
  832. , enumerable : true
  833. }
  834. }
  835. var getBoundEachPrompt = function(target, possiblePrompts, promptables, choices, promptsfilter) {
  836. return function(prompts, k, i, a){
  837. // Reducer for all prompts on targets.
  838. // No local instances config found. We use a default initialized instance available in selectedinstance
  839. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  840. // PB : TODO -- selectedinstance === __default check to prompt everything...
  841. if( shouldPrompt(k, possiblePrompts, target) ) {
  842. delete reconfirm[k];
  843. // console.log(k)
  844. // console.dir(possiblePrompts); //console.dir(target)
  845. prompts.push(async ()=>{
  846. // PB : NOTE -- Important in async cases when this {{target}} needs to be in the same state as when it was invoked.
  847. // We need to take a snapshot... Shallow.. !! If required deep should be used based on use case.
  848. // var asyncthis = Object.assign(this);
  849. // By default Latest altered state is provided which is an implicit reference directly.
  850. console.log('----------------------------------------------------')
  851. console.log(k)
  852. console.dir(choices[k])
  853. if(!promptables[k]) promptables[k] = {}
  854. promptables[k].choices = choices[k]
  855. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  856. return await target[k]
  857. })
  858. }
  859. delete possiblePrompts[k] // PB : TODO We should keep this around instead of deleting so we can do a second pass if required.
  860. return prompts
  861. }
  862. }
  863. // unbound. Bind before using.
  864. var unbound_interactionpoints = function(selectedinstance){
  865. var self = this;
  866. var _interactionpoints = {
  867. get runchoice() {
  868. return {
  869. label :
  870. `Choose an option :
  871. d) Install the default chess instance.
  872. => elxr i chess node_env=development --default
  873. n) Create your custom new instance interactively
  874. => elxr i {{instanceName}} node_env={{environment}}
  875. i) Choose an instance and environment to install
  876. => elxr i {{instanceName}} node_env={{environment}}
  877. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  878. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  879. h) Help
  880. q) Quit
  881. : `
  882. , choices : []
  883. , defaultchoice : 'c'
  884. , selectedchoice : self.target.runchoice
  885. , interpret : function(choice){
  886. var interpret_map = {
  887. d : function(){
  888. processedArgs._[0] = 'i'
  889. self.target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  890. self.target.node_env = processedArgs.node_env = (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  891. self.target.reposerver = 'https://git.bbh.org.in' // PB : TODO -- Read from global defaults...
  892. }
  893. , n : function() { processedArgs._[0] = 'i' }
  894. , i : function() {
  895. processedArgs._[0] = 'i'
  896. // processedArgs._[1] = self.target.instanceName || processedArgs._[1] || 'chess';
  897. }
  898. , c : async function() {
  899. // self here will always be the self.target.
  900. Object.defineProperty(self, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  901. label : `Enter cmd :
  902. p) pull
  903. Default <= p
  904. : `
  905. , defaultchoice : 'pull'
  906. }
  907. ));
  908. var cmd = await self.target['cmd'];
  909. if (!cmd || cmd === 'p') { self.target['cmd'] = processedArgs._[0] = 'pull' }
  910. else self.target['cmd'] = processedArgs._[0] = cmd
  911. return cmd;
  912. }
  913. , h : function() { console.log(elxr.help()); process.exit() } // PB : TODO -- Why do we need log.
  914. , q : function() { process.exit() }
  915. }
  916. if(Promise.resolve(choice) === choice){
  917. return choice.then( resolvedchoice => {
  918. return (interpret_map[choice] || interpret_map['c']).call(self.target)
  919. })
  920. }
  921. else return Promise.resolve( (interpret_map[choice] || interpret_map['c']).call(self.target) )
  922. // var __interpreter = interpret_map[choice] || interpret_map['c']
  923. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  924. // if(interpret_map[choice]) __interpreter = interpret_map[choice];
  925. // return __interpreter.call(self.target)
  926. }
  927. }
  928. }
  929. , get instanceName() {
  930. return { label : `Enter Instance Name ( <= ${self.target.instanceName || 'chess'} ) : `
  931. , choices : self.choices['instanceName'], defaultchoice : 'chess'
  932. , selectedchoice : self.target.instanceName
  933. }
  934. }
  935. , get instanceType() {
  936. return { label : `Enter Instance Type ( <= ${self.target.instanceType || 'development'} ) : `
  937. , choices : self.choices['instanceType'], defaultchoice : 'development'
  938. , selectedchoice : self.target.instanceType || 'development'
  939. }
  940. }
  941. , get reposerver() {
  942. return { label : `Enter Repo Server Base Url ( <= ${self.target.reposerver || 'https://git.bbh.org.in'} ) : `
  943. , get choices() {
  944. // self.choices['reposerver'].forEach( rs => {
  945. // var __rs = new URL(rs);
  946. // __rs.hostname = __rs.host;
  947. // __rs.path = '/'
  948. // __rs.method = 'GET'
  949. // RESTAPI.get(__rs, function(data){ rs.accessibility = 'accessible' }
  950. // , function(error){ rs.accessibility = 'unaccessible' } )
  951. // })
  952. return self.choices['reposerver']
  953. }
  954. , set choices(cs) {
  955. return self.choices['reposerver'].concat([selectedinstance.reposerver]).concat(cs)
  956. }
  957. , defaultchoice : selectedinstance.reposerver || 'https://git.bbh.org.in'
  958. , selectedchoice : self.target.reposerver
  959. }
  960. }
  961. // , 'upstream-remote' : { label : `Enter Remote Name ( <= ${self.target['upstream-remote'] || 'chess'} ) : `
  962. // , get choices() {
  963. // var reposerver = self.target['reposerver']
  964. // var remotes = []
  965. // var trs = self.target.reposervers || []
  966. // trs.forEach(rs => {
  967. // if(rs.server === reposerver){
  968. // remotes.push(remote)
  969. // // PB : TODO -- Sort and display highest priority self.target.remotes.sort( )
  970. // }
  971. // })
  972. // return remotes
  973. // }
  974. // , set choices(addlchoices){
  975. // var reposerver = self.target['reposerver']
  976. // var remotes = []
  977. // var trs = self.target.reposervers || []
  978. // trs.forEach(rs => {
  979. // if(rs.server === reposerver){
  980. // remotes.push(remote)
  981. // // PB : TODO -- Sort and display highest priority self.target.remotes.sort( )
  982. // }
  983. // })
  984. // return remotes.concat(addlchoices)
  985. // }
  986. // , defaultchoice : 'userfork'
  987. // , selectedchoice : self.target['upstream-remote'] || 'userfork'
  988. // // Just using getters resolves dependencies..., dependencies : [ ()=>{ return self.target['reposerver'] } ]
  989. // }
  990. // , 'remote-type' : { label : `Enter Remote Type ( <= ${self.target['remote-type'] || 'public'} ) : `
  991. // , get choices() {
  992. // return ['external', 'public', 'private', 'github', 'unc']
  993. // }
  994. // , set choices(addlchoices){
  995. // var reposerver = self.target['reposerver']
  996. // var remotes = []
  997. // var trs = self.target.reposervers || []
  998. // trs.forEach(rs => {
  999. // if(rs.server === reposerver){
  1000. // remotes.push(remote)
  1001. // // PB : TODO -- Sort and display highest priority self.target.remotes.sort( )
  1002. // }
  1003. // })
  1004. // return ['external', 'public', 'private', 'github', 'unc'].concat(addlchoices)
  1005. // }
  1006. // , defaultchoice : 'public'
  1007. // , selectedchoice : self.target['remote-type'] || 'public'
  1008. // // Just using getters resolves dependencies..., dependencies : [ ()=>{ return self.target['reposerver'] } ]
  1009. // }
  1010. // , 'selectedremotes' : { label : `Chose Remote Names ( <= ${self.target['selectedremotes'] || 'chess'} ) : `
  1011. // , get choices() {
  1012. // var reposerver = self.target['reposerver'] // PB : TODO -- We need options to work with multiple selected reposervers at the same time..
  1013. // var remotenames = []
  1014. // Object.entries(self.target.remotes || []).forEach( ([rname, r]) => {
  1015. // if(r.server === reposerver && r.accessibility.find( self.target[ 'remote-type' ] )){
  1016. // remotes.push(rname)
  1017. // // PB : TODO -- Sort and display highest priority self.target.remotes.sort( )
  1018. // }
  1019. // })
  1020. // // PB : TODO -- Need to generate all possible permuted choices nP( 1 -> n )
  1021. // // Currenty handles all combinations without any priority order.
  1022. // var _remotechoices = [] // Array of arrays of choices.
  1023. // remotenames.forEach( r => {
  1024. // var __rcs = []
  1025. // _remotechoices.forEach(rc => {
  1026. // __rcs.push( rc.concat(r) )
  1027. // })
  1028. // Array.prototype.push.apply( _remotechoices, __rcs)
  1029. // _remotechoices.push(r)
  1030. // })
  1031. // return _remotechoices
  1032. // }
  1033. // , defaultchoice : ['userfork', 'chess'] // userfork and chess should imlicitly point to userfork-external and chess-external when external connectivity is dtetected.
  1034. // , selectedchoice : self.target['selectedremotes'] || ['userfork-external', 'chess-external']
  1035. // // , defaultchoice : { 'userfork-external' : self.target.remotes['userfork-external'] , 'chess-external' : self.target.remotes['chess-external'] }
  1036. // // , selectedchoice : self.target['selectedremotes'] || { 'userfork-external' : self.target.remotes['userfork-external'] , 'chess-external' : self.target.remotes['chess-external'] }
  1037. // // Info : Just using getters resolves dependencies..., dependencies : [ ()=>{ return self.target['reposerver'] } ]
  1038. // }
  1039. , get username() { return { label : `Enter User Id for ${self.target.reposerver} ( <= ${self.target.username || 'chess'} ) : `
  1040. , choices : self.choices['username'], defaultchoice : self.target.username || 'chess', selectedchoice : self.target.username } }
  1041. , get password() { return { label : `Enter Password for ${self.target.username} @ ${self.target.reposerver} ( <= ${self.target.password || ''} ) : `
  1042. , choices : self.choices['password'], defaultchoice : '***', selectedchoice : self.target.password } }
  1043. , get email() { return { label : `Enter Email for ${self.target.username} @ ${self.target.reposerver} ( <= ${self.target.email || ''} ) : `
  1044. , choices : self.choices['email'], defaultchoice : 'guest@bbh.org.in', selectedchoice : self.target.email } }
  1045. }
  1046. return _interactionpoints
  1047. }
  1048. var get_interactionpoints_template = function(){
  1049. return {
  1050. instanceName : { label : `Enter Instance Name ( <= ${this.target.instanceName || 'chess'} ) : `
  1051. , choices : this.choices['instanceName'], defaultchoice : 'chess'
  1052. , selectedchoice : this.target.instanceName
  1053. }
  1054. }
  1055. }
  1056. var pending = (function() {
  1057. // PB : TODO -- Override cli prefs and call with undefined selectedinstance only if there is no cli overide or selection.
  1058. acquirelocalinstances( { root : ENV.wd } )
  1059. function createLocalChessInstance( cfg ){
  1060. // return createInstance(cfg)
  1061. reconfirm = getReconfirmAll()
  1062. var inst = {};
  1063. var __new = Object.assign({}, __default, cfg)
  1064. inst[cfg.node_env] = __new; return inst;
  1065. }
  1066. if(chessinstances.error) {
  1067. delete chessinstances.error
  1068. // use installchoices only when we don't find chessinstances.
  1069. try { var installchoices = require(path.normalize(ENV.wd + '/installchoices.js'))
  1070. var instanceName = installchoices.instanceName;
  1071. var reposerver = installchoices.reposerver
  1072. var node_env = clioverrides.node_env || installchoices.node_env
  1073. var __instance = (chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
  1074. instanceName, node_env, root, reposerver /* promptkeys['reposerver'] */ } ))[node_env];
  1075. chessinstances['current_run'] = { instanceName, node_env, reposerver, root }
  1076. // if(path.normalize(selectedinstance.root) !== path.normalize(chessinstances[selectedinstance.instanceName][selectedinstance.node_env].root)) {
  1077. // throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selectedinstance.root
  1078. // }
  1079. // chessinstances[installchoices.instanceName] = chessinstances[installchoices.instanceName] || {}
  1080. // chessinstances[installchoices.instanceName][installchoices.node_env || clioverrides.node_env] = installchoices
  1081. __instance.username = installchoices.username = installchoices.gitUser
  1082. __instance.email = installchoices.email = installchoices.gitEmail
  1083. }
  1084. catch(e){
  1085. console.warn(e)
  1086. console.warn( 'Install choices not found. WIll prompt for choices' ) // This is not an error. A new fresh instance is probably being setup.
  1087. throw 'PROMPT FOR INSTLL CHOICES TO BE IMPLEMENTED'
  1088. // chessinstances[installchoices.instanceName] = chessinstances[installchoices.instanceName] || {}
  1089. // chessinstances[installchoices.instanceName][installchoices.node_env || clioverrides.node_env] = installchoices
  1090. }
  1091. }
  1092. // PB : chessinstances.js update if we are switching repo servers, username etc... Myabe always refresh on each run.
  1093. // root location for instance swithc ?? should not be allowd...
  1094. var instanceName = clioverrides.instanceName || chessinstances.current_run.instanceName
  1095. var instance = {}
  1096. function oninstanceName(instanceName) {
  1097. var instance_ = chessinstances[instanceName]
  1098. if(instance_) {
  1099. instance = instance_[clioverrides.node_env || chessinstances.current_run.node_env] || utils.assign(chessinstances['current_run'], clioverrides, { instanceName })
  1100. }
  1101. else instance = utils.assign(chessinstances['current_run'], clioverrides, { instanceName })
  1102. // PB : TODO We should promt like instanceName create a new one instad of undefined ??
  1103. return instance
  1104. }
  1105. if(!instanceName) {
  1106. var interactionpoints = (function() { return { instanceName : get_interactionpoints_template.bind({target : {}, choices : {}})()['instanceName'] } })()
  1107. var eachPrompt = getBoundEachPrompt(instance, utils.assign({}, interactionpoints), interactionpoints, {})
  1108. var pendingtasks = any( Object.keys(interactionpoints).reduce(eachPrompt, []) ).then(()=>{
  1109. return oninstanceName(instance.instanceName)
  1110. })
  1111. }
  1112. else {
  1113. var pendingtasks = Promise.resolve(oninstanceName(instanceName))
  1114. }
  1115. return pendingtasks.then((instance)=>{
  1116. // PB : TODO -- Embed defaults in the build instead of inlining here...
  1117. // PB : TODO -- All these values instanceName, node_env, username, reposervers should come from instace overridden by a finalized cliovrrides...
  1118. // Also attepmt to load preconfig specially for new chessinstances from ../chess-config/...
  1119. var __repo_manifest_elxr = loadmanifest( instance.root + '/elxr'
  1120. , { utils, username : instance.username /** ??? TODO */ , instanceName : instance.instanceName /** ??? TODO */
  1121. , node_env : clioverrides.node_env, reposerver : instance.reposerver /** ??? TODO */ } // options
  1122. )
  1123. if(__repo_manifest_elxr.error) console.log(__repo_manifest_elxr.e.message)
  1124. var instance_specific_config_manifest = loadmanifest( instance.root + `/${instance.instanceName}-config-${clioverrides.node_env}`
  1125. , { utils, username : instance.username /** ??? TODO */ , instanceName : instance.instanceName /** ??? TODO */
  1126. , node_env : clioverrides.node_env, reposerver : instance.reposerver /** ??? TODO */ } // options
  1127. )
  1128. if(instance_specific_config_manifest.error) console.log(instance_specific_config_manifest.e.message)
  1129. delete __repo_manifest_elxr.error
  1130. delete __repo_manifest_elxr.e
  1131. delete __repo_manifest_elxr.utils
  1132. delete instance_specific_config_manifest.error
  1133. delete instance_specific_config_manifest.e
  1134. delete instance_specific_config_manifest.utils
  1135. // selectedinstance is not complete until we load in the following order of priority...
  1136. // 1) inline defaults
  1137. // 2) elxr defaults & manifest
  1138. // 3) ../chess-config/... defaults TODO
  1139. // 4) local cached lastrun or cli selected instance from chessinstances
  1140. // 5) instance specific manifest from {{instanceName}}-config-{{node_env}} ( can work with stale or on demand currently pulled updated version )
  1141. // 5.5) runconfig ??? lastrun vs fixed runconfig for repetitive stuff. TODO -- runconfig overrides lastrun...
  1142. // 6) cli overrides from command promnt
  1143. // 7) promted selections and reconfirms.
  1144. var __pvt = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  1145. , __default, __repo_manifest_elxr, instance
  1146. , { root : ENV.wd, node_env : ENV.NODE_ENV
  1147. , get instanceName() {
  1148. // FInalize to prevent subsequent overrides...
  1149. return instance.instanceName
  1150. }
  1151. }
  1152. , instance_specific_config_manifest
  1153. , clioverrides
  1154. )
  1155. // console.dir(__pvt)
  1156. // Unmergable server overrides
  1157. Object.keys(instance_specific_config_manifest).forEach( key => {
  1158. __pvt[key] = instance_specific_config_manifest[key]
  1159. })
  1160. var __pub = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }, {}, __pvt
  1161. // Finalized immutables.
  1162. // We don't need pub to prevent immutability.
  1163. , { get root(){ return __pvt.root }
  1164. , get node_env(){ return __pvt.node_env }
  1165. , get instanceName() { return __pvt.instanceName }
  1166. , get reposindexed(){
  1167. // PB : TODO -- Implement -- One time gettor and then cached...
  1168. var indexed = {}
  1169. this.repos.forEach(r => { indexed[r.repo] = r })
  1170. this.elevated.forEach(r => { indexed[r.repo] = r })
  1171. Object.defineProperty(this, 'reposindexed', { value: indexed, writable: false });
  1172. return indexed;
  1173. }
  1174. , set root(val){
  1175. throw 'root changes not yet supported'
  1176. // if the root changes while we r invoked from somewhere else... we need to reload everything from that location...
  1177. if(__pvt.root === val){
  1178. return __pvt.root = val
  1179. }
  1180. else __pvt.root
  1181. }
  1182. }
  1183. )
  1184. chessinstances[__pub.instanceName] = chessinstances[__pub.instanceName] || {}
  1185. chessinstances[__pub.instanceName][__pub.instanceType] = __pub
  1186. // PB : TODO initinstances is now obselete relocated here
  1187. // Upgrade old formats..
  1188. if(__pub?.repos && !__pub?.repos[0]?.repo) {
  1189. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  1190. __pub.repos = __pub.repos.map(function(repo){ return { repo } })
  1191. }
  1192. if(__pub?.elevated && !__pub?.elevated[0]?.repo) {
  1193. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  1194. __pub.elevated = __pub.elevated.map(function(repo){ return { repo } })
  1195. }
  1196. // Config from server always override merges into selection except for the current selection.
  1197. // PB : TODO -- utils.assign Array merges are non-distinct...
  1198. // chessinstances[instanceName][node_env] = selectedinstance;
  1199. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  1200. // PB : TODO -- We should probably write the new server config also...
  1201. // PB : TODO -- Attempt first one that is available and online...
  1202. // PB : TODO -- system select may need a reconfirm...
  1203. if(!__pub.reposerver) reconfirm['reposerver'] = true
  1204. __pub.reposerver = __pub.reposerver || __pub.reposervers[0]
  1205. cacheWriteInstanceConfig(chessinstances, __pub.root, __pub )
  1206. Object.defineProperty(__g, 'selectedinstance', {
  1207. get(){ return __pub}
  1208. , set( inst ){
  1209. utils.assign(__pub, inst); return __pub
  1210. }
  1211. })
  1212. return __pub;
  1213. })
  1214. })()
  1215. return pending.then(( selectedinstance)=>{
  1216. var op = {
  1217. 'h': () => { console.log(elxr.help()); return '-h' }
  1218. , 'clean' : () => {
  1219. // delete all node_module folders and links.
  1220. var tasklist = [];
  1221. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot )
  1222. return Promise.all(tasklist)
  1223. }
  1224. // , 'undefined': () => { return acquireChoices( {} ); }
  1225. , 'isurlaccessible' : function(args){
  1226. // args.url... .. PB : TODO -- Extract from url
  1227. args = args || {}
  1228. var u = new URL(args.url || selectedinstance.reposerver)
  1229. console.log(u)
  1230. var httpoptions = { hostname : u.host || 'git.bbh.org.in', protocol : u.protocol || 'https'
  1231. , method : 'GET'
  1232. , username : args.username || selectedinstance.username || 'chess'
  1233. , password : selectedinstance.password || 'chess'
  1234. }
  1235. httpoptions.path = args.path || `/`
  1236. return new Promise(function( resolve, reject ){
  1237. RESTAPI.get(httpoptions, function(){
  1238. console.log('URL is accessible')
  1239. resolve(true)
  1240. }, function(){
  1241. console.error('URL is not accessible')
  1242. resolve(false)
  1243. })
  1244. })
  1245. }
  1246. , 'reset': () => {
  1247. // Reset NPM packages semver so major versions can be updated.
  1248. const fs = require('fs')
  1249. const wipeDependencies = (__package) => {
  1250. const file = fs.readFileSync(__package + '/package.json')
  1251. const content = JSON.parse(file)
  1252. for (var devDep in content.devDependencies) {
  1253. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  1254. content.devDependencies[devDep] = '*';
  1255. }
  1256. }
  1257. for (var dep in content.dependencies) {
  1258. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  1259. content.dependencies[dep] = '*';
  1260. }
  1261. }
  1262. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  1263. }
  1264. var repos = ['client'];
  1265. // repos = gitRepos;
  1266. repos.forEach(wipeDependencies)
  1267. // if (require.main === module) {
  1268. // } else {
  1269. // module.exports = wipeDependencies
  1270. // }
  1271. }
  1272. , 'upgrade': () => {
  1273. console.log('upgrade.......')
  1274. var tasks = [
  1275. () => {
  1276. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  1277. inherit: true, shell: true
  1278. , env: ENV
  1279. }).catch((e) => { console.error(e) })
  1280. p.position = 1;
  1281. console.log('One')
  1282. return p;
  1283. }
  1284. , () => {
  1285. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  1286. inherit: true, shell: true
  1287. , env: ENV
  1288. }).catch((e) => { console.error(e) })
  1289. p.position = 2;
  1290. console.log('Two')
  1291. return p;
  1292. }
  1293. , () => {
  1294. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  1295. inherit: true, shell: true
  1296. , env: ENV
  1297. }).catch((e) => { console.error(e) })
  1298. p.position = 3;
  1299. console.log('Three')
  1300. return p;
  1301. }
  1302. , () => {
  1303. var p = nodeShellExec('n', ['latest'], {
  1304. inherit: true, shell: true
  1305. , env: ENV
  1306. }).catch((e) => { console.error(e) })
  1307. p.position = 4;
  1308. console.log('Four')
  1309. return p;
  1310. }
  1311. ]
  1312. any(tasks)
  1313. console.log('.......done')
  1314. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  1315. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  1316. console.info('Uninstalling existing ember globally');
  1317. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  1318. stdio: ['pipe', process.stdout, process.stderr],
  1319. inherit: true,
  1320. shell: true,
  1321. cwd: path.dirname(__dirname),
  1322. env: ENV
  1323. })
  1324. step1.on('close', () => {
  1325. console.info('Installing ember globally');
  1326. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  1327. stdio: ['pipe', process.stdout, process.stderr],
  1328. inherit: true,
  1329. shell: true,
  1330. cwd: path.dirname(__dirname),
  1331. env: ENV
  1332. })
  1333. step2.on('close', () => {
  1334. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  1335. stdio: ['pipe', process.stdout, process.stderr],
  1336. inherit: true,
  1337. shell: true,
  1338. cwd: path.dirname(__dirname),
  1339. env: ENV
  1340. })
  1341. })
  1342. })
  1343. }
  1344. , 'push': () => {
  1345. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  1346. // init remote bare from local
  1347. // pushandinitremotebare
  1348. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  1349. // connect to repo server -- net use 172.16.0.27
  1350. // cd 172.16.0.27/repos/
  1351. // mkdir repo.git
  1352. // cd repo.git
  1353. // git init --bare
  1354. // cd localrepo
  1355. // git remote rename origin githubclone
  1356. // git remote add origin //172.16.0.27/repos/repo.git
  1357. // git push origin master
  1358. var repo = processedArgs._[1];
  1359. var remote = 'origin'
  1360. var sequentialTaskShellCommands = [];
  1361. if (!existsSync(`Z:/${repo}.git`)) {
  1362. sequentialTaskShellCommands = [
  1363. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  1364. // inherit : true, shell: true
  1365. // , env: ENV
  1366. // }]
  1367. ['pwd', { cwd: 'Z:', inherit: true }]
  1368. , ['mkdir', [`${repo}.git`], {
  1369. cwd: `Z:`
  1370. , inherit: true, shell: true
  1371. , env: ENV
  1372. }]
  1373. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  1374. , ['git', ['init', '--bare'], {
  1375. cwd: `Z:/${repo}.git`
  1376. , inherit: true, shell: true
  1377. , env: ENV
  1378. }]
  1379. // PB : TODO -- Do this conditionally only...
  1380. , ['git', ['remote', 'rename', remote, 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  1381. console.log(`Ignoring ${remote} rename error : ` + err); return true; //return true to continue.
  1382. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  1383. , ['git', ['remote', 'add', remote, `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  1384. // PB : TODO -- If threre is a gitbubclone origin
  1385. // Set the master to pull from the local repo.
  1386. ]
  1387. if (!existsSync(`Z:`)) {
  1388. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  1389. inherit: true, shell: true
  1390. , env: ENV
  1391. }])
  1392. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  1393. // throw 'done'
  1394. }
  1395. }
  1396. sequentialTaskShellCommands.push(['git', ['push', remote, 'master'], { cwd: `${instanceroot + '/' + repo}` }])
  1397. // console.dir(sequentialTaskShellCommands);
  1398. var tasks = [];
  1399. sequentialTaskShellCommands.forEach(shellcmd => {
  1400. // console.log(shellcmd)
  1401. tasks.push(() => {
  1402. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
  1403. return p;
  1404. })
  1405. })
  1406. any(tasks);
  1407. }
  1408. , 'is-git-repo': (dir) => {
  1409. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  1410. }
  1411. // git remote equivalents...
  1412. // git branch --set-upstream-to=elixir-unc/master master
  1413. // git push --set-upstream elixir-unc branch..
  1414. , 'remote': (args) => {
  1415. // Subcommands!
  1416. // PB : TODO -- we can now pass in hypehnated args...
  1417. if(!processedArgs.v) return false; // Only -v is supported presently..
  1418. var serial_perform = (repo) => {
  1419. var options = { cwd: instanceroot + '/' + repo }
  1420. return [
  1421. ['git', ['remote', '-v'], options]
  1422. ]
  1423. }
  1424. var x = (args) => {
  1425. var tasq = () => {
  1426. // console.log(args)
  1427. return nodeShellExec.apply(null, args).catch(e => {
  1428. // We continue on failure.
  1429. console.error(tasq.toString())
  1430. })
  1431. }
  1432. tasq.toString = function(){
  1433. return JSON.stringify(args)
  1434. }
  1435. return tasq;
  1436. }
  1437. var perform = (dir) => {
  1438. return any(serial_perform(dir.name).map(x))
  1439. }
  1440. dirs(perform)
  1441. }
  1442. , 'remote set-url': (args) => {
  1443. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  1444. var __args = {
  1445. remotename : args.remotename || processedArgs._[2]
  1446. , url : args.url || processedArgs._[3]
  1447. , branch : args.branch || processedArgs._[4] || 'master'
  1448. }
  1449. __args.upstream = args['upstream'] || processedArgs._[5] || `${__args.remotename}/${__args.branch}`
  1450. // pushable doesn't mean the remote doesn't support being pushed to.
  1451. // 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.
  1452. // PB : TODO -- change this to enablepushing.
  1453. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  1454. var pushable = processedArgs.pushable || (args.remote ? args.remote.pushable : false) || args.pushable;
  1455. var remotename = __args.remotename
  1456. var url = __args.url
  1457. var branch = __args.branch
  1458. var upstream = __args.upstream
  1459. console.log('remotename : ' + args.remotename)
  1460. var serial_perform_git_seturl = (reponame) => {
  1461. var options = { cwd: instanceroot + '/' + reponame }
  1462. // console.log(reponame)
  1463. var serialcmds = [
  1464. ['git', ['remote', 'set-url', remotename, url + '/' + reponame], { cwd: instanceroot + '/' + reponame }]
  1465. ]
  1466. if (!pushable) {
  1467. serialcmds.push(['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + reponame }])
  1468. }
  1469. var requiresElevation = selectedinstance.elevated.find( r => r.repo === reponame)
  1470. serialcmds.push(['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + reponame, requiresElevation }]) // requires elevation based on repo
  1471. serialcmds.push(['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }])
  1472. return serialcmds
  1473. }
  1474. var x = (xargs) => {
  1475. var tasq = () => {
  1476. // console.log(args)
  1477. var task = (onsuccess, onerror)=>{
  1478. return ()=>{
  1479. return nodeShellExec.apply(null, xargs).then( onsuccess ).catch(e => {
  1480. // We continue on failure.
  1481. // No such remote
  1482. if(e.messages[0].search('No such remote') > -1 ){
  1483. console.log(remotename + ' Remote doesnt exist will add.')
  1484. return op['remote add']( args )
  1485. }
  1486. console.error(util.inspect(e) + ' ' + tasq.toString())
  1487. })
  1488. }
  1489. }
  1490. if(xargs[2].requiresElevation){
  1491. if(!isElevated) {
  1492. var etask = task( ()=>{ return remotename } )
  1493. etask.statuslog = statuslog
  1494. etask.selectedinstance = selectedinstance
  1495. etask.processedArgs = processedArgs
  1496. etask.runtimestamp = runtimestamp
  1497. etask.ENV = ENV
  1498. return shell_verse.runElevated(etask)
  1499. }
  1500. }
  1501. return task(
  1502. () => { fs.writeFileSync('run.done', 'success')}
  1503. , () => { fs.writeFileSync('run.done', 'error') }
  1504. )()
  1505. }
  1506. tasq.toString = function(){ return JSON.stringify(args) }
  1507. return tasq;
  1508. }
  1509. var perform_git_seturl = (dir) => {
  1510. return op['is-git-repo'](dir).then((logEntry) => {
  1511. return any(serial_perform_git_seturl(dir.name).map(x))
  1512. }).catch((e) => {
  1513. console.log(e + ' Failed not recognized as a git repo : ' + dir.name)
  1514. })
  1515. }
  1516. if(args.dir) return perform_git_seturl(args.dir) // do this for a specific repo
  1517. else return dirs(perform_git_seturl) // Do for all
  1518. }
  1519. // , 'reset' : ()=>{
  1520. // PB : TODO -- Cant have 2 resets !! | There is an npm reset that should be bundled.
  1521. // // Reset the whole installation pertaining to this elxr folder.
  1522. // }
  1523. , 'remote exists': (args) => {
  1524. var __args = {
  1525. remotename : args.remotename|| processedArgs._[2]
  1526. , url : args.url || processedArgs._[3]
  1527. , branch : args.branch || processedArgs._[4]
  1528. }
  1529. var options = args.repo ? { cwd: instanceroot + '/' + args.repo } : {}
  1530. // PB : TODO -- We should evaluate a whole list of remotes passed in from args instead of just one.
  1531. var commands = [
  1532. // git remote -v| while read remote; do "${remote#origin/}" "$remote"; done
  1533. // ['git', ['remote', '-v', '| while read remote; do "${remote#origin/}" "$remote"; done'], utils.assign( {
  1534. [
  1535. // 'git', ['remote', '-v']
  1536. 'git', ['config', `remote.${__args.remotename}.url`]
  1537. , utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  1538. , {
  1539. benign : args.benign, ignorefailures : args.ignorefailures,
  1540. evaluateResult : function(err, result){
  1541. return [
  1542. +result.code === 0
  1543. , result
  1544. ]
  1545. }
  1546. } , options) ]
  1547. ]
  1548. var mapped = commands.map(getshelltask) //.map( p => p.catch(e => e)) // Handle errors later.
  1549. mapped.push( function(prevserialtaskresult) {
  1550. var pt = [false , null]
  1551. if(prevserialtaskresult.error) {
  1552. // Previous task has failed.
  1553. pt[1] = prevserialtaskresult.error[1]
  1554. }
  1555. else pt = prevserialtaskresult;
  1556. console.dir(prevserialtaskresult)
  1557. return getshelltask(['git', ['ls-remote', `${__args.url}`], utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  1558. , {
  1559. benign : args.benign, ignorefailures : args.ignorefailures,
  1560. evaluateResult : function(err, result){
  1561. if(+result.code !== 0) return [pt, [ false, result]]
  1562. // var hasfailed = /^fatal: .*/.test(result.messages.join(' '))
  1563. return [pt, [true, result] ]
  1564. }
  1565. } , options) ])().catch( e => {
  1566. console.error(e)
  1567. return [pt, [ false, null]]
  1568. })
  1569. })
  1570. return any(mapped, true, false, { accumulatedresults : [] }).then( allresolved => {
  1571. console.dir(allresolved)
  1572. !allresolved[0][0] && !allresolved[1][0] ? console.log('was not added as a remote and url is currently inaccessible.')
  1573. : allresolved[0][0] && allresolved[1][0] ? console.log('was added as a remote and url is accessible.')
  1574. : allresolved[0][0] && !allresolved[1][0] ? console.log('was added as a remote but url is currently inaccessible.')
  1575. : console.log('was not added as a remote but url is currently accessible.')
  1576. return !allresolved[0][0] && !allresolved[1][0] ? [0, 0]
  1577. : allresolved[0][0] && allresolved[1][0] ? [1, 1] // => was added as a remote and url is accessible.
  1578. : allresolved[0][0] && !allresolved[1][0] ? [1, 0] // => was added as a remote but url is currently inaccessible.
  1579. : [0, 1] // => was not added and remote and url is accessible.
  1580. }).catch(e => {
  1581. console.log(e)
  1582. return [0, 0]
  1583. })
  1584. }
  1585. , 'remote refresh' : (args) => {
  1586. var url = args._[2] || selectedinstance.reposerver
  1587. return op['isurlaccessible']({ url }).then(( baccess )=>{
  1588. if(!baccess) {
  1589. var reposerver = selectedinstance.reposerverinstances[url]
  1590. if(!reposerver.external) {
  1591. // Internal server not accessible ask to switch to external.
  1592. console.log('Internal server not accsssible. Will switch to external')
  1593. // console.dir(selectedinstance.reposerverinstances)
  1594. url = reposerver.externalreposervers[0]
  1595. }
  1596. else {
  1597. console.log('External server not accsssible. Will switch to interal')
  1598. // PB : TODO -- Prompt and then switch.
  1599. url = reposerver.internalreposervers[0]
  1600. }
  1601. return op['isurlaccessible']({ url }).then(( baccess )=>{
  1602. if(!baccess) {
  1603. console.log('Neither internal nor external servers are accessible.... Presenting choices...')
  1604. console.log('PB : TODO -- Present appropriate choices...')
  1605. // Redo whole command...
  1606. }
  1607. return dorefresh()
  1608. })
  1609. }
  1610. dorefresh()
  1611. console.log(baccess)
  1612. }).catch((err)=>{ console.error(err) })
  1613. function dorefresh(){
  1614. // if(args.url === selectedinstance.reposerver) {
  1615. // // No change. Just refresh with same url anyway. We do not know which of the repos is not up to date and is an outlier.
  1616. // }
  1617. // else {
  1618. // // Also refreshs anyway
  1619. // }
  1620. args = args || {}
  1621. var __args = {
  1622. url : args.url || processedArgs._[2] || selectedinstance.reposerver
  1623. // , branch : args.branch || processedArgs._[4]
  1624. }
  1625. var serial_perform = (repo) => {
  1626. // if(repo === 'setup' || repo === 'chess-server-lib'){
  1627. var options = { cwd: instanceroot + '/' + repo }
  1628. console.log('serial_perform : ' + repo)
  1629. return [
  1630. ['git', ['remote', '-v'], options]
  1631. ]
  1632. // }
  1633. // else return []
  1634. }
  1635. var x = (args) => {
  1636. // console.log('MapX was called')
  1637. var tasq = () => {
  1638. console.log('--------------------------')
  1639. console.log(args)
  1640. return nodeShellExec.apply(null, args).catch(e => {
  1641. console.log('caught error ------------------------' + JSON.stringify(e))
  1642. // We continue on failure.
  1643. console.error(tasq.toString() + args[2].cwd)
  1644. })
  1645. }
  1646. tasq.toString = function(){
  1647. // console.log('sadfasdf------------------------')
  1648. return JSON.stringify(args) // PB : TODO -- Is this needed ?
  1649. }
  1650. return tasq;
  1651. }
  1652. var remotenames = (selectedinstance.selectedremotes || []).concat( selectedinstance.permanentremotes )
  1653. var remotes = selectedinstance.reposerverinstances[__args.url].remotes
  1654. // use the repo manifest to create missing remotes.
  1655. function perform_remote_refresh(dir){
  1656. var repo = dir.name
  1657. var ___args = {url : __args.url, repo}
  1658. if(repo === '.elxr') return Promise.resolve(true)
  1659. if(repo === '.git') return Promise.resolve(true)
  1660. if(repo === 'Downloads') return Promise.resolve(true)
  1661. // PB : TODO -- pick up remote definitions per repository...
  1662. var reposmanfiest = utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  1663. , {}, selectedinstance, loadmanifest( selectedinstance.root + '/' + repo
  1664. , { utils, username : selectedinstance.username, instanceName : selectedinstance.instanceName
  1665. , node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver }
  1666. ))
  1667. if( !reposmanfiest.error ) {
  1668. var reporemotenames = remotenames.concat(reposmanfiest.selectedremotes || []).concat( reposmanfiest.permanentremotes || [] )
  1669. var reporemotes = utils.assign([], remotes, reposmanfiest.reposerverinstances[___args.url].remotes)
  1670. }
  1671. else {
  1672. var reporemotenames = remotenames
  1673. var reporemotes = remotes
  1674. }
  1675. return (()=>{
  1676. var promises = []
  1677. return any(serial_perform(repo).map(x)).then(()=>{
  1678. var branch = args.branch || 'master' // PB : TODO -- Dont default branch here.. Let each repos current state define this... ???
  1679. reporemotenames.forEach(rm =>{
  1680. console.log('Processing : ' + rm + ' ' + dir.name)
  1681. // if(repo != 'elxr') return //test
  1682. // if(repo != 'elixir-config-development') return //test
  1683. // if(repo != 'elixir-server') return //test
  1684. promises.push( ((rm) => {
  1685. var remotename = rm
  1686. var repodef = selectedinstance.reposindexed[repo];
  1687. if(!repodef) return
  1688. // if( repo !== 'cihsr-data') return
  1689. // username and owner are two different things. The repository (possibly forked) under the username is when the {{owner}} portion of the repo path is the same as the user.
  1690. // When one user or organiztion shares repos with others through a team without a fork a different user has access to a different {{owner}} path repo.
  1691. var remote = reporemotes[remotename]
  1692. // console.log(repodef)
  1693. // console.log(remote)
  1694. var owner = repodef.owner || remote.owner || defaultRepoOwner // should be based on the server, remote and repo combination.
  1695. var reposerver = repodef.server || remote.server || selectedinstance.reposerver
  1696. // selectedinstance.reposerverinstances[reposerver]
  1697. var auth = repodef.username ? repodef : remote.username ? remote : selectedinstance.reposerverinstances[reposerver].username ? reposerver : selectedinstance;
  1698. var httpoptions = new URL(reposerver);
  1699. httpoptions = {
  1700. hostname: httpoptions.hostname
  1701. , method: 'GET'
  1702. , protocol : httpoptions.protocol
  1703. }
  1704. httpoptions.username = auth.username // PB : TODO -- Handle remotes with different username. Also cache git credentials either globally or per repo...
  1705. httpoptions.password = (auth.password || selectedinstance.password || '') // PB : NOTE URL has some kind of a setter for password which converts to string "undefined" as password which is undesirable.. so we pre resolve and send.
  1706. // console.log(___args)
  1707. var repourl = reporemotes[remotename].url + '/' + repo
  1708. // PB : TOOD -- USE GITTEA API
  1709. // op['isurlaccessible']({ url : repourl }).then((baccess)=>{
  1710. return GITEA.repository.exists( httpoptions, repo, owner ).then((bexists)=>{
  1711. console.log(remotename + ' ' + repourl)
  1712. if(bexists) {
  1713. console.log(remotename + ' ' + repourl + ' is accessible')
  1714. return ((remotename)=>{
  1715. return op['remote set-url']( { dir, remotename, url : reporemotes[remotename].url, remote
  1716. , repodef : selectedinstance.reposindexed[repo] } ) // PB : TODO -- Handle add-url
  1717. })(remotename)
  1718. // get upstream remote choice from user !!!
  1719. // PB : TODO -- Set upstream , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  1720. }
  1721. }).catch(e => {
  1722. console.warn(remotename + ' ' + repourl + ' ' + e) // Skip nonexistant not necessarily quietly
  1723. })
  1724. })(rm)
  1725. )
  1726. })
  1727. return Promise.all(promises).then( accessibleremotes => {
  1728. while(!accessibleremotes[accessibleremotes.length -1] && accessibleremotes.length) accessibleremotes.splice(accessibleremotes.length -1, 1)
  1729. if(accessibleremotes.length) {
  1730. ((remotename)=>{
  1731. var upstream = `${remotename}/${branch}`
  1732. var remote = reporemotes[remotename]
  1733. return op['remote set-url']( { dir, remotename, url : reporemotes[remotename].url, remote
  1734. , upstream
  1735. , repodef : selectedinstance.reposindexed[repo] } ) // PB : TODO -- Handle add-url
  1736. })( accessibleremotes[accessibleremotes.length -1] )
  1737. }
  1738. }).catch((e) => { console.log('Processing Error : ' + dir.name); console.error(e); return { error: true, message: repo } })
  1739. })
  1740. })()
  1741. }
  1742. if(isElevated) {
  1743. var elevatedpromises = []
  1744. selectedinstance.elevated.forEach( r => { elevatedpromises.push(perform_remote_refresh({ name : r.repo })) } )
  1745. return Promise.all(elevatedpromises)
  1746. }
  1747. else return dirs(perform_remote_refresh)
  1748. }
  1749. }
  1750. , 'remote add': (args) => {
  1751. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  1752. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  1753. // That explicitly has a remote name prefix.
  1754. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  1755. // git branch branch_name -u your_new_remote/branch_name -- older versions
  1756. // git branch -vv -- Detect which branch are we tracking.
  1757. // default upstream should be users own fork.
  1758. // Also need alias branches to
  1759. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  1760. // probably git merge from all remotes... and relevant branches...
  1761. // alias pushall='for i in `git remote`; do git push $i; done;'
  1762. // alias pullall='for i in `git remote`; do git pull $i; done;'
  1763. // args === processedArgs ? args = {} : null;
  1764. var __args = {
  1765. remotename : args.remotename|| processedArgs._[2]
  1766. , reponame : args.reponame || (args.repodef ? args.repodef.repo : undefined)
  1767. , url : args.url || processedArgs._[3]
  1768. , branch : args.branch || processedArgs._[4] || 'master'
  1769. }
  1770. __args.upstream = args['upstream'] || processedArgs._[5] || `${remotename}/${branch}`
  1771. var remotename = __args.remotename
  1772. var url = __args.url
  1773. var branch = __args.branch
  1774. var upstream = __args.upstream
  1775. var pushable = processedArgs.pushable || (args.remote ? args.remote.pushable : false) || args.pushable;
  1776. var serial_perform_git_add = (reponame) => {
  1777. var options = { cwd: instanceroot + '/' + reponame }
  1778. // console.log(reponame)
  1779. if (pushable) {
  1780. var gacmds = [
  1781. ['git', ['remote', 'add', remotename, url + '/' + reponame], { cwd: instanceroot + '/' + reponame }]
  1782. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + reponame }]
  1783. // , ['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }]
  1784. ]
  1785. }
  1786. else {
  1787. var gacmds = [
  1788. ['git', ['remote', 'add', remotename, url + '/' + reponame], { cwd: instanceroot + '/' + reponame }]
  1789. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + reponame }]
  1790. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + reponame }]
  1791. // When we add a remote it should not automatically become the upstream. The upstream should be a chosen remote else we do not change
  1792. // , ['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }]
  1793. ]
  1794. }
  1795. if(__args['upstream']) gacmds.push(['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }])
  1796. return gacmds
  1797. }
  1798. // PB : TODO -- Accumulate using yield... and finally return a set of tasks or promises...
  1799. var perform_git_add = (dir) => {
  1800. return op['is-git-repo'](dir).then((logEntry) => {
  1801. // console.log(code)
  1802. if (logEntry.success) {
  1803. return nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  1804. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  1805. return remotename;
  1806. })
  1807. .catch((e) => {
  1808. return perform( serial_perform_git_add, dir.name ).then(()=>{
  1809. return remotename
  1810. })
  1811. })
  1812. }
  1813. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  1814. }).catch((e) => {
  1815. console.log('Failed : ' + dir.name)
  1816. })
  1817. }
  1818. if(__args.reponame) { return perform_git_add( { name : __args.reponame} ) }
  1819. else return dirs(perform_git_add)
  1820. }
  1821. , 'remote remove': (args) => {
  1822. var __args = {
  1823. remotename : args.remotename|| processedArgs._[2]
  1824. }
  1825. var remotename = __args.remotename
  1826. var serial_perform_git_remove = (repo) => {
  1827. var options = { cwd: instanceroot + '/' + repo }
  1828. // console.log(repo)
  1829. return [
  1830. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  1831. ]
  1832. }
  1833. var perform_git_remove = (dir) => {
  1834. op['is-git-repo'](dir).then((logEntry) => {
  1835. // console.log(code)
  1836. if (logEntry.success) {
  1837. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  1838. any(serial_perform_git_remove(dir.name).map(getnodeshellexectask))
  1839. })
  1840. .catch((e) => {
  1841. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`)
  1842. })
  1843. }
  1844. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  1845. }).catch((e) => {
  1846. // console.log('Failed : ' + dir.name)
  1847. })
  1848. }
  1849. dirs(perform_git_remove)
  1850. }
  1851. , 'get-remotes' : (args) => {
  1852. // var __args = {
  1853. // repo : args?.repo || processedArgs._[1]
  1854. // }
  1855. var repo = args.repo
  1856. var serial_perform = (repo) => {
  1857. return [
  1858. ['git', ['remote', '-vvvv'], { cwd: instanceroot + '/' + repo,
  1859. evaluateResult : function( issuccess, result){
  1860. if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
  1861. var lines = result.messages.join('').split('\n')
  1862. var remotes = {}
  1863. lines.forEach(line => {
  1864. // pattern = origin https://git.bbh.org.in/chess/elxr (fetch)
  1865. var match = new RegExp(`(\\S+)\\s(\\S+)/${repo}.git\\s\\((\\S+)\\)`).exec(line)
  1866. if(match) {
  1867. var r = remotes[match[1]] || (remotes[match[1]] = { title : match[1] })
  1868. if(match[3] === 'push') { r.push = match[2] }
  1869. else r.url = match[2]
  1870. }
  1871. })
  1872. return remotes
  1873. }}]
  1874. ]
  1875. }
  1876. return perform( serial_perform, repo )
  1877. }
  1878. , 'get-remote' : (upstream) => {
  1879. // var __args = {
  1880. // repo : args?.repo || processedArgs._[1]
  1881. // }
  1882. var repo = upstream.repo
  1883. var serial_perform = (repo) => {
  1884. return [
  1885. ['git', ['remote', '-vvvv'], { cwd: instanceroot + '/' + repo,
  1886. evaluateResult : function( issuccess, result){
  1887. if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
  1888. // origin https://git.bbh.org.in/chess/elxr (fetch)
  1889. var match = new RegExp(`${upstream.remotename}\\\s(\\S+)/${repo}.git\\s\\(fetch\\)`).exec(result.messages.join(' '))
  1890. if(match) { upstream.url = match[1] }
  1891. else throw Object.assign( new Error('No upstream found for active branch'), result)
  1892. return upstream
  1893. }}]
  1894. ]
  1895. }
  1896. return perform( serial_perform, repo )
  1897. }
  1898. , 'get-upstream' : (args) => {
  1899. var __args = {
  1900. repo : args?.repo || processedArgs._[1]
  1901. }
  1902. var repo = __args.repo
  1903. var serial_perform = (repo) => {
  1904. return [
  1905. ['git', ['branch', '-vvvv'], { cwd: instanceroot + '/' + repo,
  1906. evaluateResult : function( issuccess, result){
  1907. if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
  1908. var match = /\*\s(\S+)\s\S+\s\[(\S+)\/(\S+).*?\].*?/.exec(result.messages.join(' '))
  1909. if(match) { var upstream = { remotename : match[2], branch : match[1], remotebranch : match[3] } }
  1910. else throw Object.assign( new Error('No upstream found for active branch'), result)
  1911. if(args?.remotes) {
  1912. var r = args.remotes[upstream.remotename];
  1913. if(!r) return op['get-remote'](upstream)
  1914. r.branch = upstream.branch
  1915. r.remotebranch = upstream.remotebranch
  1916. return r
  1917. }
  1918. return op['get-remote'](upstream)
  1919. }}]
  1920. ]
  1921. }
  1922. return perform( serial_perform, repo )
  1923. }
  1924. , 'init-gitea': (username) => {
  1925. // Change user to an object that has user.username and use here..
  1926. username = username || processedArgs._[1]
  1927. if (!username) throw 'User name required'
  1928. var serial_perform_init_gitea = (repo) => {
  1929. var options = { cwd: instanceroot + '/' + repo }
  1930. // console.log(repo)
  1931. return [
  1932. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${username}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  1933. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  1934. , ['git', ['remote', 'set-url', 'userfork', `${selectedinstance.reposerver}/${username}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  1935. ]
  1936. }
  1937. var perform_init_gitea = (dir) => {
  1938. op['is-git-repo'](dir).then((logEntry) => {
  1939. // console.log(code)
  1940. if (logEntry.success) {
  1941. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  1942. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  1943. })
  1944. .catch((e) => {
  1945. perform( serial_perform_init_gitea, dir.name )
  1946. })
  1947. }
  1948. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  1949. }).catch((e) => {
  1950. // console.log('Failed : ' + dir.name)
  1951. })
  1952. }
  1953. dirs(perform_init_gitea)
  1954. }
  1955. , 'syncmaster': (label) => {
  1956. // Usage :
  1957. // elxr pull -- Defaults to run config
  1958. console.log('Running exlr pull : ' + path.dirname(__dirname))
  1959. if (!processedArgs.runas) gitRepos.map((def) => performPull(def, def.branch || 'master'))
  1960. var etask = ()=>{
  1961. return any(elevatedRunasRepos.map((def) => performPull(def, def.branch || 'master'))).then(() => {
  1962. fs.writeFileSync('run.done', 'success')
  1963. }).catch(() => {
  1964. fs.writeFileSync('run.done', 'error')
  1965. })
  1966. }
  1967. etask.statuslog = statuslog
  1968. etask.selectedinstance = selectedinstance
  1969. etask.processedArgs = processedArgs
  1970. etask.runtimestamp = runtimestamp
  1971. etask.ENV = ENV
  1972. return shell_verse.runElevated(etask)
  1973. }
  1974. , 'repo-relocate' : function(args){
  1975. // relocate a subfolder in source repo to same subfolder in target repo with history.
  1976. var args = args || {
  1977. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  1978. , folder : processedArgs._[3] || 'server'
  1979. , sourcerepo : processedArgs._[2] || 'client'
  1980. , targetrepo : processedArgs._[1] || 'elixir-server'
  1981. }
  1982. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  1983. // , stdio: ['pipe', process.stdout, process.stderr]
  1984. , inherit: true,
  1985. shell: true,
  1986. env: ENV
  1987. , runas: processedArgs.runas
  1988. }
  1989. return op['repo-split'](args).then(()=>{
  1990. return op['repo-merge'](args).then(()=>{
  1991. // cleanup folder from source.
  1992. var cmdseq = [
  1993. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  1994. // commits have to intentional...
  1995. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  1996. ]
  1997. return any(cmdseq.map(getshelltask))
  1998. })
  1999. }).catch(e=>{console.error(e)})
  2000. }
  2001. , 'repo-split' : function(args) {
  2002. // https://gist.github.com/smdabdoub/17065c348289158277b5
  2003. /**
  2004. * Eg : folder, remotebase, sourcerepo, targetrepo
  2005. * args.folder = 'server'
  2006. * args.remotebase = 'https://git.bbh/chess/'
  2007. * args.sourcerepo = 'client'
  2008. * args.targetrepo = 'elixir-server'
  2009. */
  2010. var args = args || {
  2011. folder : 'server'
  2012. , remotebase : 'http://git.bbh/chess/'
  2013. , sourcerepo : 'client'
  2014. , targetrepo : 'elixir-server'
  2015. }
  2016. var options = { cwd: `${instanceroot}/relocate`
  2017. // , stdio: ['pipe', process.stdout, process.stderr]
  2018. , inherit: true,
  2019. shell: true,
  2020. env: ENV
  2021. , runas: processedArgs.runas
  2022. }
  2023. var cmdseq = [
  2024. // create a temporary working dir in current folder where we started execution.
  2025. ['mkdir', [ '-p', `${instanceroot}/relocate`]]
  2026. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  2027. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  2028. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  2029. ]
  2030. return any(cmdseq.map(getshelltask)).then(() => {
  2031. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  2032. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  2033. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  2034. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  2035. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  2036. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  2037. // subtree split and filter-branch are options. We currently use repo-filter.
  2038. return op['filter-repo'](args)
  2039. }).catch(e=>{console.error(e); throw 'failed'})
  2040. }
  2041. , 'repo-merge' : function(args) {
  2042. // Merge source repo into target repo
  2043. var args = args || {
  2044. folder : 'server'
  2045. , remotebase : 'http://git.bbh/chess/'
  2046. , sourcerepo : 'client'
  2047. , targetrepo : 'elixir-server'
  2048. }
  2049. var sourcerepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  2050. // , stdio: ['pipe', process.stdout, process.stderr]
  2051. , inherit: true,
  2052. shell: true,
  2053. env: ENV
  2054. , runas: processedArgs.runas
  2055. }
  2056. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  2057. // , stdio: ['pipe', process.stdout, process.stderr]
  2058. , inherit: true,
  2059. shell: true,
  2060. env: ENV
  2061. , runas: processedArgs.runas
  2062. }
  2063. var cmdseq = [
  2064. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  2065. , targetrepooptions ]
  2066. // , ['git', ['push', targetrepooptions ] // manual push for now..
  2067. ]
  2068. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e)})
  2069. }
  2070. , 'filter-repo' : function(args){
  2071. // Merge source repo into target repo
  2072. var args = args || {
  2073. folder : 'server'
  2074. , remotebase : 'http://git.bbh/chess/'
  2075. , targetrepo : 'elixir-server'
  2076. }
  2077. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  2078. , inherit: true, shell: true
  2079. , env: ENV
  2080. , runas: processedArgs.runas
  2081. }
  2082. var cmdseq = [
  2083. // git checkout -b feature/merge-old-project
  2084. // git remote add src-project ../src-project
  2085. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  2086. ]
  2087. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e); throw 'failed' })
  2088. }
  2089. , 'filter-branch' : function(preservefolder, repo){
  2090. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  2091. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  2092. // Preserve a specific folder.
  2093. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  2094. /*
  2095. git clone repo reposplit
  2096. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  2097. git remote rm origin
  2098. */
  2099. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  2100. }
  2101. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  2102. // // Merge repo2 into a subfolder in repo1
  2103. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  2104. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  2105. // /*
  2106. // cd repo1
  2107. // git remote add -f tempmergesource ../{{mergesource}}/.git
  2108. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  2109. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  2110. // git commit
  2111. // // Repair History
  2112. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  2113. // #!/usr/bin/env bash
  2114. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  2115. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  2116. // subdir=server
  2117. // git filter-branch --tree-filter '
  2118. // first='"$first"'
  2119. // last='"$last"'
  2120. // subdir='"$subdir"'
  2121. // log_file=/tmp/filter.log
  2122. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  2123. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  2124. // echo "=== $GIT_COMMIT: making changes"
  2125. // files=$(git ls-tree --name-only $GIT_COMMIT)
  2126. // mkdir -p $subdir
  2127. // for i in $files; do
  2128. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  2129. // done
  2130. // else
  2131. // echo "=== $GIT_COMMIT: ignoring"
  2132. // fi \
  2133. // >> $log_file
  2134. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  2135. // status=0 # tell tree-filter never to fail
  2136. // '
  2137. // git remote rm tempmergesource
  2138. // */
  2139. // // better alternative for history
  2140. // /**
  2141. // *
  2142. // git clone git@server.com:old-project.git
  2143. // git clone git@server.com:new-project.git
  2144. // cd old-project
  2145. // mkdir old-project
  2146. // git mv !(old-project) old-project
  2147. // ls -la and gt mv hidden files ....
  2148. // git commit -a -S -m “Moving old project into its own subdirectory”
  2149. // cd ../new-project
  2150. // git remote add old-project ../old-project
  2151. // git fetch old-project
  2152. // git checkout -b feature/merge-old-project
  2153. // git merge -S --allow-unrelated-histories old-project/master
  2154. // git push origin feature/merge-old-project
  2155. // git remote rm old-project
  2156. // */
  2157. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  2158. // }
  2159. , 'pull' : (label) => {
  2160. // Usage :
  2161. // elxr pull -- Defaults to run config
  2162. return elxr.getpulltask(selectedinstance)
  2163. }
  2164. , 'isInstalled': () => {
  2165. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  2166. console.log(processedArgs._[1] + ' exists.')
  2167. return true;
  2168. });
  2169. }
  2170. , 'c' : ()=>{
  2171. }
  2172. , 'i' : () => {
  2173. var tasks = []
  2174. // tasks.push(op['pull']);
  2175. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
  2176. tasks.push(op['use']) // Will pull repos...
  2177. op['npmi'].statuslog = statuslog
  2178. tasks.push(shell_verse.getNonElevatedTask(op['npmi'])) // We do not run npm i with elevated privilege for security reasons.
  2179. // var tasksdefs = [
  2180. // ['elxr', ['pull']]
  2181. // , ['elxr', ['use', 'elixir']]
  2182. // , ['elxr', ['npmi']]
  2183. // ]
  2184. // tasksdefs.forEach(tasksdef=>{
  2185. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  2186. // })
  2187. return any(tasks);
  2188. }
  2189. , 'npmi': () => {
  2190. var tasks = [];
  2191. // Build fails without babel...
  2192. tasks.push(getShellTask(
  2193. 'npm',[ 'i', '-g', 'babel-cli' ]
  2194. ) )
  2195. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  2196. // npmbuildrepos = []
  2197. npmbuildrepos.forEach(repo => {
  2198. tasks.push(() => {
  2199. return nodeShellExec('npm', ['i --force'], {
  2200. inherit: true, shell: true
  2201. , cwd: instanceroot + '/' + repo
  2202. , env: ENV
  2203. , title: `npm i for ${repo}`
  2204. }).catch((e) => {
  2205. console.error('Ignoring Benign Error'); console.error(e);
  2206. }).then(() => {
  2207. console.log(`--npm run build for ${repo}--------------------`)
  2208. return nodeShellExec('npm', ['run build'], {
  2209. inherit: true, shell: true
  2210. , cwd: instanceroot + '/' + repo
  2211. , env: ENV
  2212. , title: `npm run build for ${repo}`
  2213. }).then(Tasq.then).catch(Tasq.catch)
  2214. })
  2215. })
  2216. })
  2217. return any(tasks).then(() => {
  2218. gitRepos.push({ repo : 'chess-server-lib/server'});
  2219. gitRepos = gitRepos.concat(elevatedRunasRepos);
  2220. // console.dir(gitRepos)
  2221. // throw ""
  2222. // gitRepos = [
  2223. // // 'bbhverse', 'serververse', 'elixir-server',
  2224. // // 'clientverse',
  2225. // 'client'
  2226. // ];
  2227. var rmtasks = []
  2228. var repotasks = []
  2229. var env = Object.assign({}, ENV)
  2230. delete env.NODE_ENV // PB : TODO -- Why delete ??? npm i fails with NODE_ENV...
  2231. gitRepos.forEach(repodef => {
  2232. rmtasks.push(
  2233. // () => {
  2234. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  2235. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  2236. callshelltask(['rm', ['package-lock.json'], {
  2237. inherit: true, shell: true
  2238. , cwd: instanceroot + '/' + repodef.repo
  2239. , env: ENV
  2240. , title: `rm 'package-lock.json' for ${repodef.repo}`
  2241. }])
  2242. .then(()=>{
  2243. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  2244. }).catch((e) => { console.error(e) })
  2245. // }
  2246. )
  2247. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  2248. repotasks.push(
  2249. () => {
  2250. console.log(`--npm i for ${repodef.repo}--------------------`)
  2251. var p = nodeShellExec('npm', ['i', '--force'], {
  2252. inherit: true, shell: true
  2253. , cwd: instanceroot + '/' + repodef.repo
  2254. , env
  2255. , title: `npm i for ${repodef.repo}`
  2256. }).then(Tasq.then).catch(Tasq.catch)
  2257. return p;
  2258. })
  2259. }
  2260. })
  2261. // NODE_ENV=development DEBUG=loopback:connector:mssql node --tls-min-v1.0 --inspect elixir/server.js
  2262. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  2263. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  2264. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  2265. // PB : TODO -- Investigate why NODE_ENV has an impact on npm i !??
  2266. // Second time try also doesnt work.
  2267. // repotasks.push(
  2268. // () => {
  2269. // var env = Object.assign({}, process.env)
  2270. // delete env.NODE_ENV
  2271. // console.log(`--------------------second time npm i for client--------------------`)
  2272. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  2273. // // return nodeShellExec('npm', ['i --force'], {
  2274. // inherit: true, shell: true
  2275. // , cwd: instanceroot + '/' + 'client'
  2276. // , env
  2277. // , title: `npm i for client`
  2278. // }).then(Tasq.then).catch(Tasq.catch)
  2279. // })
  2280. var bowerRepos = [{ repo : 'client'}]
  2281. var bowertasks = []
  2282. bowerRepos.forEach(repodef => {
  2283. bowertasks.push(() => {
  2284. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
  2285. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  2286. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  2287. inherit: true, shell: true
  2288. , cwd: instanceroot + '/' + repodef.repo
  2289. , env: ENV
  2290. , title: `bower i for ${repodef.repo}`
  2291. }).then(Tasq.then).catch(Tasq.catch)
  2292. return p;
  2293. })
  2294. })
  2295. // console.log('rmtasks.length : ' + rmtasks.length)
  2296. return Promise.all(rmtasks).then(() => any(repotasks)).then(()=>any(bowertasks));
  2297. }).catch(e => {
  2298. console.error(e)
  2299. }).finally(statuslog.finally)
  2300. }
  2301. , 'start': (args) => {
  2302. // Usage : elxr start {{instanceName=elixir}} {{all||server||client||{{microserviceName=elixir||express}}}}
  2303. var label = clioverrides.cmd
  2304. var env = Object.assign({}, ENV); // Shallow clone it.
  2305. var nodecmd = clioverrides.node_env === 'development' ? 'nodemon' : 'node';
  2306. function startFn( o ){
  2307. var cmd = [nodecmd, [`--inspect=${o.debugport}`, '--preserve-symlinks', o.script]]
  2308. console.log(`Starting ${o.name}.`);
  2309. if(shell_verse.iswin()){
  2310. var __cmd = 'cmd'
  2311. var a1 = '/k'
  2312. }
  2313. else if(shell_verse.islin()) {
  2314. var __cmd = 'sh'
  2315. var a1 = '-c'
  2316. }
  2317. if(o.cmd) {
  2318. cmd = o.cmd
  2319. var childPromise = nodeShellExec(...o.cmd, {
  2320. // inherit : true,
  2321. shell: true,
  2322. detached: true,
  2323. stdio: 'ignore',
  2324. cwd: instanceroot + o.path
  2325. , env
  2326. })
  2327. }
  2328. else {
  2329. var childPromise = nodeShellExec(__cmd, [a1, getCmdString(cmd) ], {
  2330. // inherit : true,
  2331. shell: true,
  2332. detached: true,
  2333. stdio: 'ignore',
  2334. cwd: instanceroot + o.path
  2335. , env
  2336. })
  2337. }
  2338. var child = childPromise.process;
  2339. var cpid = child.pid
  2340. childPromise.then(()=>{
  2341. console.log(` *** started ${o.name} PID(${cpid}) ${cmd}`);
  2342. fs.writeFileSync(o.pidstore, '' + cpid)
  2343. })
  2344. .catch(e => console.error(e) )
  2345. }
  2346. if(clioverrides.node_env === 'development') {
  2347. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  2348. if(!processedArgs._[2]) processedArgs._[2] = 'all'
  2349. if(processedArgs._[2] === 'server' || processedArgs._[2] === 'all'
  2350. || processedArgs._[2] === 'elixir' // specific microservice name.
  2351. ) {
  2352. startFn( { debugport : 9228, script : 'elixir/server.js', name : 'Elixir Loopback Server', path : '/' + 'elixir-server'
  2353. , pidstore : '.elixir-server.elixir.server.pid'
  2354. } )
  2355. }
  2356. if(processedArgs._[2] === 'server' || processedArgs._[2] === 'all'
  2357. || processedArgs._[2] === 'express' // specific microservice name.
  2358. ) {
  2359. startFn( { debugport : 9227, script : 'bin/www', name : 'Express Server', path : '/' + 'chess-server-lib/server'
  2360. , pidstore : '.express.server.pid'
  2361. } )
  2362. }
  2363. if(processedArgs._[2] === 'client' || processedArgs._[2] === 'all') {
  2364. startFn( {
  2365. name : 'Elixir Ember Client', path : '/' + 'client'
  2366. , cmd : ['node_modules/ember-cli/bin/ember', ['s']]
  2367. , pidstore : '.client.server.pid'
  2368. } )
  2369. }
  2370. }
  2371. }
  2372. , 'stop': (label) => {
  2373. const kill = require('tree-kill');
  2374. try{
  2375. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', { encoding: 'utf8'})
  2376. fs.unlinkSync('.elixir-server.elixir.server.pid')
  2377. console.log(serverPid)
  2378. kill(serverPid)
  2379. }
  2380. catch(e){ console.error(e) }
  2381. try{
  2382. serverPid = fs.readFileSync('.express.server.pid', { encoding: 'utf8' })
  2383. fs.unlinkSync('.express.server.pid')
  2384. console.log(serverPid)
  2385. kill(serverPid)
  2386. }
  2387. catch(e){ console.error(e) }
  2388. try{
  2389. serverPid = fs.readFileSync('.client.server.pid', { encoding: 'utf8' })
  2390. fs.unlinkSync('.client.server.pid')
  2391. console.log(serverPid)
  2392. kill(serverPid)
  2393. }
  2394. catch(e){ console.error(e) }
  2395. }
  2396. , 'model' : () => {
  2397. var etask = ()=>{
  2398. var tasks = [
  2399. () => {
  2400. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  2401. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  2402. inherit: true, shell: true
  2403. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  2404. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  2405. , env: ENV
  2406. }).catch((e) => { console.error(e) })
  2407. return p;
  2408. }
  2409. ];
  2410. return any(tasks).then(() => {
  2411. fs.writeFileSync('run.done', 'success') // PB : TODO -- IPC through files is needed only for windows.
  2412. }).catch(() => {
  2413. fs.writeFileSync('run.done', 'error')
  2414. })
  2415. }
  2416. etask.statuslog = statuslog
  2417. etask.selectedinstance = selectedinstance
  2418. etask.processedArgs = processedArgs
  2419. etask.runtimestamp = runtimestamp
  2420. etask.ENV = ENV
  2421. return shell_verse.runElevated(etask)
  2422. }
  2423. , 'use' : () => {
  2424. // use a certain named instance.
  2425. // Eg :
  2426. // 1) elxr use elixir
  2427. // 2) elxr use cihsr
  2428. // If environment is not specified defaults to development.
  2429. // 1) NODE=test elxr use elixir
  2430. /*// Steps
  2431. 1) Delete Config and Data symlinks
  2432. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  2433. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  2434. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  2435. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  2436. */
  2437. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  2438. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  2439. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  2440. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  2441. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  2442. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') } // PB : TODO -- IPC through files is needed only for windows.
  2443. if (existsSync('config') && existsSync('data')){
  2444. return
  2445. }
  2446. }
  2447. var tasks = [
  2448. () => {
  2449. var promise = new Promise((resolve, reject)=>{
  2450. existslink('config', function(err, data){
  2451. if(data) {
  2452. var p = shell_verse.removeJuncionOrLink('config')
  2453. .then(()=>{resolve(true)})
  2454. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
  2455. }
  2456. else resolve(false)
  2457. })
  2458. })
  2459. return promise;
  2460. },
  2461. () => {
  2462. var promise = new Promise((resolve, reject)=>{
  2463. existslink('data', function(err, data){
  2464. if(data) {
  2465. var p = shell_verse.removeJuncionOrLink('data')
  2466. .then(()=>{resolve(true)})
  2467. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
  2468. }
  2469. else resolve(false)
  2470. })
  2471. })
  2472. return promise;
  2473. },
  2474. ];
  2475. runconfig.NODE_ENV = ENV.NODE_ENV = ENV.NODE_ENV || runconfig.NODE_ENV || 'development';
  2476. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  2477. if (!runconfig.use && selectedinstance.instanceName) runconfig.use = selectedinstance.instanceName;
  2478. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  2479. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  2480. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  2481. var performPullOrCloneForBranch = (def)=>{
  2482. var promise = Promise.resolve(true)
  2483. if (!branch) {
  2484. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  2485. promise = nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{ branch = __branch})
  2486. .catch((e) => { console.error(e); return { error: true, message: repo } })
  2487. }
  2488. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e )})
  2489. }
  2490. var performCloneAndCheckout = null;
  2491. // cant use git checkout -b it fails when branch already exists.
  2492. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  2493. return performPullOrCloneForBranch(def).then(()=>{
  2494. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  2495. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  2496. // inherit : true, shell: true,
  2497. cwd: instanceroot + '/' + def.repo
  2498. // , stdio : ignore // Use when we want to silence output completely.
  2499. , runas: processedArgs.runas
  2500. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  2501. }).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 } })
  2502. })
  2503. }
  2504. // var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  2505. // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  2506. var elevatedqueue = [];
  2507. var enqueueOnce = (queue, task, def) => {
  2508. var found = queue.find(element => {
  2509. var keys = Object.keys( element )
  2510. for(var k=0; k < keys.length; k++) {
  2511. if(element[keys[k]] !== def[k]) return false;
  2512. }
  2513. })
  2514. queue.push(function(){ return task(this)}.bind(def));
  2515. }
  2516. var enqueue = (queue, task, def) => {
  2517. queue.push(function(){ return task(def)}.bind(def));
  2518. }
  2519. var mergeSources = {
  2520. 'development': null,
  2521. 'test': 'master',
  2522. 'production': 'master'
  2523. }
  2524. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  2525. // Checkout is reduced to pull provided the current branch is the targetbranch
  2526. if(branch === mergesource) performCheckout = (def) => {
  2527. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  2528. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  2529. if(branch === __branch) return performCloneAndCheckout(def)
  2530. return performPullOrCloneForBranch(def)
  2531. })
  2532. .catch((e) => { console.error(e); return { error: true, message: repo } })
  2533. }
  2534. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  2535. var performPullAll = (def) => {
  2536. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  2537. return nodeShellExec('git', ['pull', '--all'], {
  2538. // inherit : true, shell: true,
  2539. cwd: instanceroot + '/' + def.repo
  2540. , runas: processedArgs.runas
  2541. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  2542. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  2543. }
  2544. var excludeCheckouts = Object.assign(exludeMergeRepos)
  2545. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  2546. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  2547. var performMerge = (def) => {
  2548. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  2549. return nodeShellExec('git', ['merge', mergesource], {
  2550. inherit: true, shell: true,
  2551. cwd: instanceroot + '/' + def.repo
  2552. , runas: processedArgs.runas
  2553. }).catch((e) => { console.error(e) })
  2554. }
  2555. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
  2556. // var performRepoOperation = function(def) {
  2557. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  2558. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  2559. // }
  2560. return any(tasks).then(() => {
  2561. var task = ()=>{
  2562. // Default target is developent. if some other target is specified in NODE_ENV in for shell call for the 'use' command we will switch to that target..
  2563. //Switch to target branch
  2564. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  2565. // pull or clone target branch
  2566. .then(() => {
  2567. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2568. return any(gitRepos.map((repo) => performPullAll(repo)))
  2569. })
  2570. // switch to source branch
  2571. .then( () => {
  2572. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  2573. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  2574. })
  2575. //Pull on merge source branch
  2576. .then( () => {
  2577. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  2578. return any(gitRepos.map((repo) => performPullAll(repo)))
  2579. })
  2580. //Switch to target branch
  2581. .then( () => {
  2582. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  2583. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  2584. })
  2585. .then( //Merge source branch to target branch
  2586. () => {
  2587. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2588. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
  2589. })
  2590. }
  2591. task.statuslog = statuslog
  2592. var netask = shell_verse.getNonElevatedTask(task)
  2593. var eltask = ()=> {
  2594. var opts = {
  2595. inherit: true, shell: true
  2596. , cwd : instanceroot
  2597. , env: ENV
  2598. }
  2599. var tasks = [
  2600. () => {
  2601. // Use junctions to avoid npm package issues
  2602. var target = runconfig.use + '-' + 'config' + '-' + ENV.NODE_ENV
  2603. var p = shell_verse.createJuntionOrLink('config', target, opts)
  2604. return p;
  2605. }
  2606. ];
  2607. // if (processedArgs._[1]) {
  2608. tasks = tasks.concat( [
  2609. () => {
  2610. var dataToLink = runconfig.use + '-data' + '-' + ENV.NODE_ENV
  2611. if(!existsSync(dataToLink)) dataToLink = runconfig.use + '-data';
  2612. var p = shell_verse.createJuntionOrLink('data', dataToLink, opts)
  2613. return p;
  2614. }
  2615. ]
  2616. )
  2617. // }
  2618. return any(tasks).then(()=>{
  2619. // checkout target branch
  2620. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  2621. // pull or clone target branch
  2622. .then(() => {
  2623. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2624. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  2625. })
  2626. // switch to source branch
  2627. .then( () => {
  2628. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2629. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  2630. })
  2631. //Pull on merge source branch
  2632. .then( () => {
  2633. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2634. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  2635. })
  2636. //Switch to target branch
  2637. .then( () => {
  2638. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2639. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  2640. })
  2641. .then( //Merge source branch to target branch
  2642. () => {
  2643. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  2644. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
  2645. })
  2646. .then(() => {
  2647. fs.writeFileSync('run.done', 'success')
  2648. }).catch(() => {
  2649. fs.writeFileSync('run.done', 'error')
  2650. })
  2651. })
  2652. }
  2653. eltask.statuslog = statuslog
  2654. eltask.selectedinstance = selectedinstance
  2655. eltask.processedArgs = processedArgs
  2656. eltask.runtimestamp = runtimestamp
  2657. var eltask = shell_verse.getElevatedTask(eltask)
  2658. return eltask().then( ()=>{ return netask() })
  2659. }).catch((e) => {
  2660. fs.writeFileSync('run.done', 'error : ' + e)
  2661. })
  2662. // Antibiotic stewardship program.
  2663. // 1st use is fine.
  2664. // Max vials dispense
  2665. // 2nd use Pharmacy needs justification Form.
  2666. // Approval after a certain period of time.
  2667. }
  2668. , 'g' : () => {
  2669. if (processedArgs.h) {
  2670. console.log('elxr g model [modelname] => generate a model named [modelname]');
  2671. console.log('elxr g vmodel [modelname] => generate a model named [modelname]');
  2672. console.log('elxr g vmodel [modelname] --server=true => generate only a server model named [modelname]');
  2673. console.log('elxr g vmodel [modelname] --all=true => default generate server and client model named [modelname]');
  2674. console.log('elxr g => regenerate all known models');
  2675. return
  2676. }
  2677. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  2678. // try {
  2679. // child = child.on('close', () => { process.chdir(label) } );
  2680. // }
  2681. // catch (err) {
  2682. // console.log('chdir: ' + err);
  2683. // }
  2684. // child.on('close', function(){
  2685. // var options = {
  2686. // shell : true
  2687. // , inherit : true
  2688. // // , cwd : '' + process.cwd
  2689. // // , env : ENV
  2690. // };
  2691. // nodeShellExec('git', ['init'], { inherit : true});
  2692. if (0) {
  2693. // PB : TODO -- Special google chrome profile for tests etc.
  2694. nodeShellExec('pwd', { inherit: true });
  2695. // /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"
  2696. // "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
  2697. // "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
  2698. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  2699. "--profile-directory=Profile 1"
  2700. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  2701. }
  2702. // nodeShellExec('npm', ['init', '-y'], options);
  2703. // nodeShellExec('npm', ['init', '-y'], options);
  2704. // })
  2705. var g = {
  2706. 'client': () => {
  2707. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  2708. console.info('Creating new ember client named : ' + processedArgs._[2]);
  2709. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  2710. stdio: ['pipe', process.stdout, process.stderr],
  2711. inherit: true,
  2712. shell: true,
  2713. cwd: path.dirname(__dirname),
  2714. env : ENV
  2715. })
  2716. },
  2717. 'modelr': () => {
  2718. var tasks = [
  2719. () => {
  2720. var p = nodeShellExec('"ember"', [
  2721. 'g'
  2722. , 'modelr'
  2723. , processedArgs._[2]], {
  2724. inherit: true, shell: true, env: ENV
  2725. }).then(() => {
  2726. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  2727. return true;
  2728. }).catch((e) => { console.error(e) })
  2729. return p;
  2730. },
  2731. () => {
  2732. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  2733. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  2734. chromeprefs = JSON.parse(chromeprefs)
  2735. var previous = chromeprefs.download.default_directory;
  2736. var parentDir = path.dirname(__dirname);
  2737. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  2738. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  2739. // PB : TODO -- detect where chrome is installed.
  2740. // PB : TODO -- set the download dir to the place where files are needed.
  2741. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  2742. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  2743. , '--profile-directory="chess"'
  2744. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  2745. inherit: true, shell: true
  2746. , env: ENV
  2747. }).then(() => {
  2748. chromeprefs.download.default_directory = previous;
  2749. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  2750. return true;
  2751. }).catch((e) => { console.error(e) })
  2752. return p;
  2753. }
  2754. ,
  2755. () => {
  2756. console.log('Browser process should have closed here....')
  2757. return true;
  2758. }
  2759. ]
  2760. any(tasks)
  2761. }
  2762. , 'undefined' : ()=>{
  2763. console.warn('Are you sure you want to refresh all the models.');
  2764. throw 'NOT YET IMPLMENTED'
  2765. }
  2766. , 'vmodel' : (options)=>{
  2767. // node --inspect-brk elxr/index.js g vmodel qlabresults --server=true
  2768. options = options || {
  2769. generate : processedArgs['all'] ? 'all' : processedArgs['server'] ? 'server' : processedArgs['client'] ? 'client' : null
  2770. }
  2771. if(!options.generate) return 'Nothing specified for generation'
  2772. var name = processedArgs._[2];
  2773. if(!name) return 'No name specified for generation'
  2774. var templateverse = `${selectedinstance.root}/bbhverse/__universe__/vmodel`
  2775. // var templateverse = `${selectedinstance.root}/bbhverse/__universe__/vmodel/__base__-server-lib/common/lib`
  2776. var workingtarget = `${selectedinstance.root}/.elxr/run-${runtimestamp}/temp/vmodelworkingdir`
  2777. var destination = `${selectedinstance.root}`
  2778. // Create a tmp working copy for staging the changes.
  2779. return copyrecursive(templateverse, workingtarget).then( r => {
  2780. var base = 'chess' // -- The server base from where this instance was dervied from.
  2781. var patternsubstitutions = [
  2782. { strOrregexp : /(__name__)/g, substitutes : [name]}
  2783. , { strOrregexp : /(__instance__)/g, substitutes : [selectedinstance.instanceName]}
  2784. , { strOrregexp : /(__base__)/g, substitutes : [base]}
  2785. , { strOrregexp : /(__microservice__)/g, substitutes : [selectedinstance.microservice || selectedinstance.instanceName]}
  2786. , { strOrregexp : /(__microclient__)/g, substitutes : [selectedinstance.microclient || `${selectedinstance.instanceName}-client` || 'client']} // PB : TODO -- elixir-client etc... use a config to find the microclient..
  2787. ]
  2788. var options = { source : templateverse, target : workingtarget
  2789. , base , destinationroot : destination, workingtarget
  2790. , processingtype : 'inplace', sourcetype : 'filesystem', patternsubstitutions }
  2791. var actions = [
  2792. fswalk( workingtarget, options
  2793. , [ function(t, o){
  2794. // A series of tasks to be executed on each pattern in patternsubstitutions.
  2795. return any([
  2796. // PB : TODO -- Contentreplace is better addressed in memory instead of file IO so do all regexps in sequence in one shot and then rename.
  2797. ()=>{ return fscontentreplace( t, o ) }
  2798. , ()=>{ return fsrename( t, o ) }
  2799. ])
  2800. }] )
  2801. // Post process links in place.
  2802. , () => dirs((innernode, s, t, o ) => fswalk( path.join(workingtarget, innernode.name), utils.assign({}, o, { innernode }), [ templatelink ] )
  2803. , workingtarget, null, options)
  2804. // Move to the final destination. Whole tree should move only top level folders are required.
  2805. // , () => fswalk( workingtarget, options, [ fsrename ])
  2806. // , () => dirs( ( child, src, target, options )=>{ return fs.renameSync(path.join(src, child.name), path.join(target, child.name) ) }
  2807. // , workingtarget, destination )
  2808. ]
  2809. return any(actions);
  2810. })
  2811. }
  2812. }
  2813. g[processedArgs._[1]]();
  2814. }
  2815. , 'create' : () => { return createInstance(selectedinstance) }
  2816. , 'httpget' : () => {
  2817. // RESTAPI.get({
  2818. // hostname: 'git.bbh',
  2819. // // port: 443,
  2820. // protocol : 'http:',
  2821. // path: '/',
  2822. // method: 'GET'
  2823. // }, function(data){ console.log(data)}, function(error){ console.log(error)} )
  2824. return createInstance(selectedinstance)
  2825. }
  2826. , 'getuser' : ()=>{ return prerequisites.git.getuser().then(u=>{ console.log(u)}) }
  2827. , 'switch user' : (tousername)=>{ return GIT['switch user'](tousername) }
  2828. }
  2829. Object.keys(op).forEach( oper => {
  2830. if(cmds[oper]) return
  2831. cmds[oper] = {}
  2832. // cmds[oper] = {
  2833. // // return a interpreted set of arguments for this cmd run context.
  2834. // interpret() { return { cmd : oper, runchoice : 'c' } }
  2835. // }
  2836. })
  2837. var elxrcmd = (function(){
  2838. var __cmdprototype = function(){}
  2839. function subcommandlabelFor(cmd, sub){ return (`${cmd} ${sub || ''}`).trim() }
  2840. var __cmd = {
  2841. interpret() {
  2842. var interpreted = {}
  2843. // Non custom command has universal positiona args.
  2844. processedArgs._[1] ? interpreted.instanceName = processedArgs._[1] : null;
  2845. interpreted.runchoice = processedArgs._[0] || selectedinstance.runchoice;
  2846. // return clioverrides
  2847. // cmds[cmd] = {
  2848. // interpret() {
  2849. // return Object.assign(clioverrides, { cmd, runchoice : 'c' })
  2850. // }
  2851. // , getPossiblePrompts(){ return { cmd, username : true, password : true,
  2852. // instanceName : true, instanceType : true, reposerver : true } }
  2853. // }
  2854. // ... PB : TODO -- use cmd.toArgs
  2855. interpreted.cmd = this.cmd
  2856. return interpreted
  2857. }
  2858. , getPossiblePrompts(){ return { username : true, password : true, instanceName : true, instanceType : true, reposerver : true } }
  2859. , cmdFn : ()=>{ throw "Elxr Unknown command."}
  2860. , finalized : true
  2861. , toArgs : function( o ){
  2862. // PB : TODO -- need to call this before selectedinstance is built. The instanceName is dependent on the specific cmd.
  2863. return o }
  2864. }
  2865. function __createO(o){
  2866. if(o.finalized) return o;
  2867. var subs = Object.keys(cmds[o.cmd].subcommands || {})
  2868. // console.log(subs)
  2869. // console.log(o)
  2870. subs.forEach(sub=>elxrcmd.create( cmds[subcommandlabelFor(o.cmd, sub)] ))
  2871. var created = utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  2872. , {}, __cmd, cmds[o.cmd], o)
  2873. cmds[o.cmd] = created;
  2874. created.cmdFn = op[o.cmd] || o.cmdFn || created.cmdFn
  2875. op[o.cmd] = created.cmdFn;
  2876. noprerequisites[o.cmd] = created.noprerequisites
  2877. return created.cmdFn;
  2878. }
  2879. function create(o){ return __createO(o) }
  2880. __cmdprototype.create = create;
  2881. return __cmdprototype;
  2882. })()
  2883. var cmdFns = {
  2884. resetgitconfig, reinit, init, g : op['g'], 'get-upstream' : op['get-upstream']
  2885. }
  2886. Object.entries(cmds).forEach( ca => {
  2887. ca[1].cmd = ca[0]
  2888. ca[1].cmdFn = ca[1].cmdFn || cmdFns[ca[0]]
  2889. elxrcmd.create( ca[1] )
  2890. })
  2891. var __default = selectedinstance; // PB : TODO -- Eliminate __default references.
  2892. Tasq.addlistener(statuslog.statuslog)
  2893. // Instead of waiting for the root to be establised we start working at the current locatoin and then relocate when root changes.
  2894. var runlogjson = `${selectedinstance.root}/.elxr/run-${runtimestamp}/run.log`
  2895. ensureDirectoryExistence(runlogjson)
  2896. fs.writeFileSync(runlogjson, JSON.stringify( { message : `Started ${runtimestamp}`, success:true})) // Initialize a new log file with "logrotate" for every run
  2897. Tasq.addlistener((e)=>{ fs.writeFileSync(runlogjson, ', ' + JSON.stringify( e ), { 'flag': 'a+' }) })
  2898. var nodeShellExec = cli.nodeShellExec;
  2899. var chalk = require('chalk')
  2900. const homedir = require('os').homedir();
  2901. function sysAddPathVar(addpath){
  2902. // Object.assign({
  2903. // inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  2904. // }, options)
  2905. // powershell $env:Path -split ';'
  2906. var etask = ()=>{
  2907. return nodeShellExec('Powershell.exe', [
  2908. `$path = [Environment]::GetEnvironmentVariable('PATH', 'Machine')
  2909. $newpath = $path + ';${addpath}'
  2910. [Environment]::SetEnvironmentVariable("PATH", $newpath, 'Machine')`
  2911. ]).then(() => {
  2912. fs.writeFileSync('run.done', 'success') // PB : TODO -- IPC through files is needed only for windows.
  2913. }).catch(() => {
  2914. fs.writeFileSync('run.done', 'error')
  2915. })
  2916. }
  2917. etask.statuslog = statuslog
  2918. etask.selectedinstance = selectedinstance
  2919. etask.processedArgs = processedArgs
  2920. etask.runtimestamp = runtimestamp
  2921. etask.ENV = ENV
  2922. return shell_verse.runElevated(etask)
  2923. // var newpath = addpath.split(';');
  2924. // newpath.push(addpath)
  2925. // newpath = Array.from(new Set(newpath)).join(';')
  2926. // // addpath.split(';').forEach(pel => { var kv = pel.split('='); kv[0] === key ? null : newpath.push(pel); } )
  2927. // // setx /M PATH "%PATH%;<path-to-executable-folder>"
  2928. // // %AppData%\npm
  2929. // return nodeShellExec('setx', ['/m', 'PATH', `%PATH%;${addpath}` ]);
  2930. }
  2931. // singleton one time lazy
  2932. var getCredentials = function(){
  2933. // try {
  2934. // First call
  2935. var creds = fs.readFileSync(path.normalize(`${homedir}/.elxrcredentials`), { encoding: 'utf8' });
  2936. var creds = creds.split('\n').map( c => c.trim() && new URL(c));
  2937. console.log(creds);
  2938. creds.forEach(cred => {console.log( cred.hostname ); console.log( cred.username )} );
  2939. // }
  2940. // catch(e){
  2941. // console.warn('Credentials not cached. You will be prompted for username and password.')
  2942. // }
  2943. // Subsequent calls
  2944. getCredentials = ()=>{ return creds }
  2945. return getCredentials();
  2946. }
  2947. // console.dir(processedArgs)
  2948. // PB : TODO -- defaults for valuless arguments if passed.
  2949. // Object.keys(processedArgs).forEach(a=>{
  2950. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  2951. // }
  2952. // })
  2953. const { readdir } = require("fs").promises
  2954. // Directory shallow walk and do perform on each dir.
  2955. const dirs = async (perform, src, target, options) => {
  2956. var rs = []
  2957. for (const dir of await readdir(src || selectedinstance.root, { withFileTypes: true })) {
  2958. if (dir.isDirectory()) rs.push( perform(dir, src, target, options) )
  2959. }
  2960. return any(rs)
  2961. }
  2962. var fsMove = async function(from, to, options) {
  2963. if(!options?.innernode) {
  2964. var exists = fs.existsSync(from);
  2965. var stats = exists && fs.statSync(from);
  2966. var isDirectory = exists && stats.isDirectory();
  2967. }
  2968. else {
  2969. var isDirectory = options.innernode.isDirectory()
  2970. }
  2971. if(!isDirectory) return fs.renameSync(from, to)
  2972. fs.mkdirSync(to, { recursive : true })
  2973. var rs = [];
  2974. for (const innernode of await readdir(from, { withFileTypes: true })) {
  2975. rs.push( fsMove( path.join(from, innernode.name), path.join(to, innernode.name), { innernode } ) )
  2976. }
  2977. return any(rs)
  2978. };
  2979. // PB : TODO -- Should return a bunch of promises to wait for...
  2980. var copyrecursive = async function(src, target, options) {
  2981. if(!options?.innernode) {
  2982. var exists = fs.existsSync(src);
  2983. var stats = exists && fs.statSync(src);
  2984. var isDirectory = exists && stats.isDirectory();
  2985. }
  2986. else {
  2987. var isDirectory = options.innernode.isDirectory()
  2988. }
  2989. if(!isDirectory) return fs.copyFileSync(src, target)
  2990. fs.mkdirSync(target, { recursive : true })
  2991. var rs = [];
  2992. for (const innernode of await readdir(src, { withFileTypes: true })) {
  2993. rs.push( copyrecursive( path.join(src, innernode.name), path.join(target, innernode.name), { innernode } )
  2994. // .then(()=>{
  2995. // return any(actions.map( a => ()=>a(dir, { isDirectory : true}) ))
  2996. // })
  2997. )
  2998. }
  2999. return any(rs)
  3000. // return fswalk( src, {}, [
  3001. // (src, options)=> {
  3002. // if(options.innernode.isDirectory()) fs.mkdirSync(options.target, { recursive : true })
  3003. // else fs.copyFileSync(src, options.target)
  3004. // }
  3005. // ])
  3006. // var exists = fs.existsSync(src);
  3007. // var stats = exists && fs.statSync(src);
  3008. // var isDirectory = exists && stats.isDirectory();
  3009. // if (isDirectory) {
  3010. // fs.mkdirSync(dest, { recursive : true });
  3011. // return dirs( function(childItemName) {
  3012. // return copyrecursive(path.join(src, childItemName.name),
  3013. // path.join(dest, childItemName.name));
  3014. // }, src )
  3015. // } else {
  3016. // fs.copyFileSync(src, dest);
  3017. // }
  3018. };
  3019. // var renamerecursive = function(from, to){
  3020. // var exists = fs.existsSync(from);
  3021. // var stats = exists && fs.statSync(from);
  3022. // var isDirectory = exists && stats.isDirectory();
  3023. // if (isDirectory) {
  3024. // fs.mkdirSync(to);
  3025. // dirs( function(childItemName) {
  3026. // renamerecursive(path.join(from, childItemName),
  3027. // path.join(to, childItemName));
  3028. // }, from )
  3029. // // fs.readdirSync(from).forEach(function(childItemName) {
  3030. // // copyrecursive(path.join(from, childItemName),
  3031. // // path.join(to, childItemName));
  3032. // // });
  3033. // } else {
  3034. // fsrename(from, to);
  3035. // }
  3036. // }
  3037. var regexreplaceall = function(content, ps){
  3038. var repmatches
  3039. var replaced = content;
  3040. while (repmatches = ps.strOrregexp.exec(content)) {
  3041. if(content.length > 0) {
  3042. var replacement = repmatches[0]
  3043. for(var m = 1; m < repmatches.length; m++) {
  3044. replacement = replacement.replace(repmatches[m], ps.substitutes[m-1])
  3045. }
  3046. replaced = replaced.replace( repmatches[0], replacement )
  3047. }
  3048. }
  3049. return replaced
  3050. }
  3051. // filesystem walk
  3052. const fswalk = async (pathToWalk, options, actions) => {
  3053. // options = options || { depthfirst : true }
  3054. if(!options.innernode) {
  3055. var exists = fs.existsSync(pathToWalk);
  3056. var stats = exists && fs.statSync(pathToWalk);
  3057. var isDirectory = exists && stats.isDirectory();
  3058. }
  3059. else {
  3060. var isDirectory = options.innernode.isDirectory()
  3061. }
  3062. if(!isDirectory) return any(actions.map( a => ()=>a( pathToWalk, utils.assign({}, options
  3063. , { pathToWalk, innernode : options.innernode || { isDirectory : function(){ return true } } }) ) ))
  3064. var rs = [];
  3065. for (const innernode of await readdir(pathToWalk, { withFileTypes: true })) {
  3066. rs.push( fswalk( path.join(pathToWalk, innernode.name), utils.assign({}, options, {pathToWalk, innernode }), actions )
  3067. // .then(()=>{
  3068. // return any(actions.map( a => ()=>a(innernode, { isDirectory : true}) ))
  3069. // })
  3070. )
  3071. }
  3072. // Wait for the walk to complete before renaming directories.
  3073. Array.prototype.push.apply(rs, actions.map( a => ()=>a( pathToWalk, utils.assign({}, options
  3074. , { pathToWalk, innernode : options.innernode || { isDirectory : function(){ return true } } } ) ) ))
  3075. return any(rs)
  3076. }
  3077. var fsrecurse = function(target, options, actions, root) {
  3078. var exists = fs.existsSync(target);
  3079. var stats = exists && fs.statSync(target);
  3080. var isDirectory = exists && stats.isDirectory();
  3081. if (isDirectory) {
  3082. var tasks = []
  3083. tasks.push( dirs( function(childItemName) {
  3084. return fsrecurse(path.join(target, childItemName.name)
  3085. , options, actions, root);
  3086. }, target ))
  3087. return any(tasks)
  3088. } else {
  3089. var prevActionResult = null;
  3090. return any( actions.map( (action) => prevActionResult = action.apply(null, target, options) ))
  3091. }
  3092. };
  3093. // var fslink = function(to, options){ try { fs.linkSync( to, options.from ) } catch(e) { throw e } }
  3094. var fslink = function(to, options){ fs.symlinkSync( to, options.from /*, type = "junction"*/ ) }
  3095. var fsrename = function(target, options){
  3096. // PB : TODO -- streaming and async.. target could be a stream a string or a filesystem item or a tree node...
  3097. var targetname = options.innernode?.name || path.parse(target).base;
  3098. var replaced = targetname;
  3099. options.patternsubstitutions.forEach( ps => { replaced = regexreplaceall( replaced, ps ) })
  3100. if(replaced && replaced !== targetname) {
  3101. var tr = target.replace( targetname, replaced )
  3102. fs.renameSync(target, tr)
  3103. return tr;
  3104. }
  3105. else return replaced
  3106. }
  3107. var fscontentreplace = function( target, options ){
  3108. // do many replacements in one shot in the file.
  3109. if(options.processingtype === 'inplace' && options.sourcetype === 'filesystem' && !options.innernode.isDirectory() ) {
  3110. var content = fs.readFileSync(target, { encoding: 'utf8' }) // PB : TODO -- streaming and async..
  3111. options.patternsubstitutions.forEach( ps => { content = regexreplaceall( content, ps ) })
  3112. fs.writeFileSync(target, content)
  3113. }
  3114. }
  3115. var templatelink = function(target, options){
  3116. var targetSubPath = target.replace(options.workingtarget + '/', '' );
  3117. var targetSubPathsplit = targetSubPath.split("/")
  3118. var targetPathBaseDir = `${targetSubPathsplit[0]}/${targetSubPathsplit[1]}`
  3119. var linkToSubPathReplacement = `${options.base}-server-lib/common`
  3120. // var rgxp = new RegExp(`(__link__)${options.base}-server-lib`, "g")
  3121. var rgxp = new RegExp(`(__link__${options.base}-server-lib)`, "g")
  3122. var linkToSubPath = targetSubPath
  3123. var b = target.match(rgxp)
  3124. var linkFromName = regexreplaceall( target, { strOrregexp : rgxp, substitutes : [ '' ] } )
  3125. linkFromName = linkFromName.replace(options.workingtarget, options.destinationroot)
  3126. if( b ) {
  3127. // Only if the pattern matches which is link instruction.
  3128. linkToSubPath = regexreplaceall( linkToSubPath, { strOrregexp : rgxp, substitutes : [ '' ] } )
  3129. }
  3130. options.patternsubstitutions.forEach( ps => { linkToSubPath = regexreplaceall( linkToSubPath, ps ) })
  3131. var linkToName = `${options.destinationroot}/${linkToSubPath}`
  3132. if(b){
  3133. linkToSubPath = linkToSubPath.replace( targetPathBaseDir, linkToSubPathReplacement)
  3134. // PB : DONT DELETE EVERYTHING ??? Only the linkable ones... Or use an add strategy without deleting...
  3135. fs.unlinkSync( target );
  3136. fslink( `${options.destinationroot}/${linkToSubPath}`, { from : linkFromName } )
  3137. }
  3138. else {
  3139. fsMove( `${options.workingtarget}/${linkToSubPath}`, linkToName )
  3140. // fsMove( `${options.workingtarget}/${linkToSubPath}`, linkFromName )
  3141. }
  3142. }
  3143. // Source and Target are files or folders. We need another version or a unifed version for strings..
  3144. var processpatterns = function(target, options){
  3145. // Accept a set of patterns and substitutions and operate on a target and apply all patterns substitutions.
  3146. // options = options || { targettype : 'inplace', sourcetype : 'filesystem' }
  3147. // options.source, options.target sourcetype = 'string' | 'filesystem' options.targettype = 'inplace' | 'copy'
  3148. if(options.processingtype === 'inplace' && options.sourcetype === 'filesystem' ) {
  3149. options.patternsubstitutions.forEach( ps => {
  3150. // var replacement = regexreplaceall( from, ps.strOrregexp, ps.substitutes )
  3151. // if(targetname) { // Porcess all files. Even if file names dont have patterns the content needs to be replaced.
  3152. return options.tasks.map( t => { return t( target, ps ) } )
  3153. // }
  3154. // return str.replace(regex, function(match, key) {
  3155. // console.log(`Found match, group ${match}: ${key}`);
  3156. // return substitutes[key] || match;
  3157. // })
  3158. })
  3159. }
  3160. // while ((m = regex.exec(str)) !== null) {
  3161. // // This is necessary to avoid infinite loops with zero-width matches
  3162. // if (m.index === regex.lastIndex) {
  3163. // regex.lastIndex++;
  3164. // }
  3165. // var rstr = str;
  3166. // // The result can be accessed through the `m`-variable.
  3167. // m.forEach((match, groupIndex) => {
  3168. // // rstr = rstr.replace( groupIndex
  3169. // console.log(`Found match, group ${groupIndex}: ${match}`);
  3170. // if(groupIndex === 0) return
  3171. // });
  3172. // }
  3173. }
  3174. function copyFileSync( source, target , options) {
  3175. var targetFile = target;
  3176. // If target is a directory, a new file with the same name will be created
  3177. if ( fs.existsSync( target ) ) {
  3178. if ( fs.lstatSync( target ).isDirectory() ) {
  3179. targetFile = path.join( target, path.basename( source ) );
  3180. }
  3181. }
  3182. fs.writeFileSync(targetFile, fs.readFileSync(source));
  3183. }
  3184. function copyFolderRecursiveSync( source, target, options ) {
  3185. var files = [];
  3186. // Check if folder needs to be created or integrated
  3187. var targetFolder = path.join( target, path.basename( source ) );
  3188. if ( !fs.existsSync( targetFolder ) ) {
  3189. fs.mkdirSync( targetFolder );
  3190. }
  3191. // Copy
  3192. if ( fs.lstatSync( source ).isDirectory() ) {
  3193. files = fs.readdirSync( source );
  3194. files.forEach( function ( file ) {
  3195. var curSource = path.join( source, file );
  3196. if ( fs.lstatSync( curSource ).isDirectory() ) {
  3197. copyFolderRecursiveSync( curSource, targetFolder );
  3198. } else {
  3199. copyFileSync( curSource, targetFolder );
  3200. }
  3201. } );
  3202. }
  3203. }
  3204. var getShellTask = (command, args, options) => {
  3205. options = options || {}
  3206. var callshell = command === 'rm' ? getgitbashtask : getshelltask;
  3207. return () => {
  3208. var p = callshell( [command, args, Object.assign({
  3209. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  3210. }, options)
  3211. ])()
  3212. if (options.ignorefailures) {
  3213. return p.catch(e => {
  3214. // Ignore. Not a major error.
  3215. })
  3216. }
  3217. else return p;
  3218. }
  3219. }
  3220. var callshelltask = (args) => {
  3221. // console.dir(args)
  3222. if( Object.prototype.toString.call(args) === '[object Function]' ) {
  3223. return args;
  3224. }
  3225. return getshelltask(args)()
  3226. }
  3227. var getCmdString = function(args){ return `"${args[0]} ${args[1].join(' ')}"` }
  3228. var getshelltask = (args) => {
  3229. return args[0] === 'rm' ? getgitbashtask(args) : () => {
  3230. return nodeShellExec.apply(null, args).catch(function(e){
  3231. e.benign = args[2].benign;
  3232. if(!e.benign) { console.error(e); }
  3233. throw e
  3234. })
  3235. }
  3236. }
  3237. var getgitbashtask = (args, onEachError) => { return () => {
  3238. return nodeShellExec( `"${gitbash}"`, ['-c', getCmdString(args)], args[2]).catch( onEachError || function(e){ console.error(e) }) }
  3239. }
  3240. var getnodeshellexectask = (args) => { return () => { return nodeShellExec.apply(null, args) }}
  3241. var perform = function( serailtasks, taskvector ){ return any( serailtasks(taskvector).map(getnodeshellexectask)) }
  3242. var getTaskCheckExists = shell_verse.getTaskCheckExists
  3243. // var getTaskWithElevation = function(tasdef){ return shell_verse.getElevatedTask( tasdef.elevatedpulltasks ) }
  3244. // var getTaskWithoutElevation = function(tasdef){
  3245. // return ()=>{
  3246. // if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  3247. // else Promise.resolve(true)
  3248. // }
  3249. // }
  3250. var gitops = {
  3251. getdiscoverbranchcmd : function(repo){
  3252. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  3253. var cmd = [gitbash
  3254. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  3255. , { cwd: instanceroot + '/' + repo, title: 'discoverbranch for ' + repo + ' ' + parameters.join(' ') }]
  3256. return cmd
  3257. }
  3258. }
  3259. var getPullCmd = (repodef, branch) => {
  3260. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  3261. // console.log(useGitPull)
  3262. var repo = repodef.repo
  3263. var pullCmd = []
  3264. if(!branch) {
  3265. // console.warn('No branch was specified detecting from working client.')
  3266. // First check if working client exists.
  3267. // if (existsSync(instanceroot + '/' + repo)) {
  3268. pullCmd= gitops.getdiscoverbranchcmd(repo)
  3269. // }
  3270. // else performpull
  3271. }
  3272. // var pullCmd = [gitInstallDir
  3273. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  3274. // , { cwd: instanceroot + '/' + repo, title: 'pull all remotes for ' + repo }]
  3275. if(branch) {
  3276. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  3277. var pullCmd = [ gitbash
  3278. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  3279. , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  3280. }
  3281. // var pullCmd = ['pullall', [], { cwd : repo }]
  3282. if (useGitPull) pullCmd = ['git', ['pull'], {
  3283. inherit: true, shell: true,
  3284. cwd: instanceroot + '/' + repo
  3285. // , env: ENV
  3286. , runas: processedArgs.runas
  3287. , title: `git pull ${repo}`
  3288. }]
  3289. return pullCmd
  3290. }
  3291. // PB : TODO -- Use queueing with async tasks..
  3292. var performPull = (repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch) => {
  3293. var __inelevatedBatch = elevatedBatch, __inregularBatch = regularBatch;
  3294. var pT = getPullTask(repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch)
  3295. // var waitForBatchAdditions = function(){
  3296. // return pT;
  3297. // }
  3298. // Execute is implied.
  3299. // if(false && (__inelevatedBatch || __inregularBatch) ) return waitForBatchAdditions() // PB : Todo Implemnt a trigger which starts execution.
  3300. // else
  3301. return pT() // Execute it.
  3302. }
  3303. var getPullTask = (repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch) => {
  3304. // PB : TODO -- Handle no branch passed in case.
  3305. // if(!branch) { throw 'No branch specified' }
  3306. var repo = repodef.repo;
  3307. elevatedBatch = elevatedBatch || [];
  3308. regularBatch = regularBatch || [];
  3309. try{
  3310. // PB : TODO -- local repo folder named the same as the remote repository name is not enough to establish existence.
  3311. // This remote repo and branch may have been or may need to be added as a local tracking branch
  3312. // to any other local repo folder (with a different name)
  3313. var exists = existsSync(instanceroot + '/' + repo)
  3314. }
  3315. catch(e){
  3316. exists = false
  3317. console.log(e)
  3318. }
  3319. function initTask(etask){
  3320. etask.info = { repo }
  3321. etask.errHandler = errHandler
  3322. etask.statuslog = statuslog
  3323. etask.processedArgs = processedArgs
  3324. etask.selectedinstance = selectedinstance
  3325. etask.runtimestamp = runtimestamp
  3326. etask.ENV = ENV
  3327. }
  3328. function initElevatedBatch(){
  3329. elevatedBatch.info = { repo }
  3330. elevatedBatch.errHandler = errHandler
  3331. elevatedBatch.statuslog = statuslog
  3332. elevatedBatch.processedArgs = processedArgs
  3333. elevatedBatch.selectedinstance = selectedinstance
  3334. elevatedBatch.runtimestamp = runtimestamp
  3335. elevatedBatch.ENV = ENV
  3336. }
  3337. if (exists) {
  3338. var tasks = [];
  3339. return (()=>{
  3340. // PB : TODO -- We need a non cacheable set of properties that need to default to something but then need to escplicitly specified in each run.
  3341. if(selectedinstance.addremotes) {
  3342. return op['get-remotes']({repo}).then(( remotes )=>{
  3343. return op['get-upstream']({repo, remotes}).then(( upstream ) => {
  3344. return __addremotesandpull({ upstream, remotes})
  3345. })
  3346. })
  3347. }
  3348. else return __pull();
  3349. })()
  3350. function __pull(){
  3351. var branchprint = branch ? ' branch :' + branch : '';
  3352. var task = ()=>{
  3353. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  3354. return any(tasks).then( ()=>{
  3355. return nodeShellExec.apply(null, getPullCmd(repodef, branch)).then(() => {
  3356. return true;
  3357. })
  3358. })
  3359. }
  3360. initTask(task)
  3361. if(repodef.requiresElevation) {
  3362. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  3363. if(elevatedBatch.length === 1) { initElevatedBatch(); initTask(elevatedBatch[0]) } // PB : TDOO -- Make sure first task also has run context. May need to be moved to win_verse
  3364. else initTask(elevatedBatch[elevatedBatch.length-1])
  3365. return elevatedBatch[elevatedBatch.length-1]
  3366. }
  3367. else {
  3368. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  3369. return regularBatch[regularBatch.length-1]
  3370. }
  3371. }
  3372. function __addremotesandpull(options){
  3373. // Add the remotes
  3374. var tasks = []
  3375. // selectedinstance.selectedremotes are optional and need not be enforced to be chosen. The selection for hte selected remotes
  3376. // could also be derived from a crossfilter of remote-type selected for this run and the current chosen and operating reposervers.
  3377. var selectedremotes = Array.from( new Set(selectedinstance.selectedremotes.concat(Object.keys(repodef.remotes || {}))));
  3378. if(selectedremotes.length > 0) var selectedremoteFilter = function(rs) { return selectedremotes.find( rs.server ) }
  3379. else var selectedremoteFilter = function(){ return true }
  3380. var repoRemotes = Object.assign( {}, selectedinstance.remotes, options.remotes, options.upstream, repodef.remotes );
  3381. // We need a most permissive filtered list to use as an efficient starting point to further reduce to whats actually needed.
  3382. // However if such a cached list is not available we need to build it by scaning and apply all the filters anyway on the whole world.
  3383. Object.keys(repoRemotes).forEach((remotename)=>{
  3384. // PB : TODO -- ai prefix for all apis that require an answer amongst many choices.
  3385. var ai_RemoteAddNeeded = (r)=>{
  3386. if(r.server === reposerver && selectedremoteFilter() && r.accessibility.find( selectedinstance[ 'remote-type' ] )){ // currently chosen remotetype...
  3387. var exists = false;
  3388. if(exists = (options.remotes[r.remotename] || Object.keys(options.remotes).find( lrn => {
  3389. var exists = options.remotes[lrn].server === r.server && !options.remotes[r.remotename]
  3390. if(exists) console.warn('Found duplicate remote with a different name for the same server...')
  3391. return exists
  3392. } )) ) {
  3393. return false // Already a remote not required.
  3394. }
  3395. return true // PB : TODO -- Sort and display highest priority target.remotes.sort( )
  3396. }
  3397. return false
  3398. };
  3399. tasks.push(
  3400. ()=>{
  3401. return op['remote exists']({
  3402. remotename, repo, benign : true, ignorefailures : true
  3403. , url : repoRemotes[remotename].url + repo
  3404. , branch : checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  3405. }).then( (r) => {
  3406. if(!r[1]) return false; // PB : TODO -- Not accessible skip for now probably should remove.
  3407. else if(r[0]) return true; // Already added nothing to do
  3408. else if(ai_RemoteAddNeeded( repoRemotes[remotename] )) return op['remote add']( { remotename,
  3409. 'set-upstream' : (selectedinstance['upstream'] || `${remotename}/${branch}`) // ??? when url accessible... in order of highest priority
  3410. , reponame : repo
  3411. , url : repoRemotes[remotename].url , branch : checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  3412. })
  3413. // else skipped as remote is not relevant for this repo...
  3414. })
  3415. }
  3416. )
  3417. })
  3418. __pull()
  3419. }
  3420. }
  3421. else {
  3422. // PB : TODO -- detect if a clonable repo exists within the context of currentGitAuthUser on remote reposerver...
  3423. console.log('cloning ' + repo)
  3424. // PB : TODO -- add additional remotes after cloning and pull again...
  3425. var task = ()=>{
  3426. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${repodef.owner || repoowner || defaultRepoOwner}/` + repo + '.git'],
  3427. {
  3428. inherit: true, shell: true,
  3429. env: ENV
  3430. , cwd : instanceroot
  3431. , runas: processedArgs.runas
  3432. }).then(() => {
  3433. var task = ()=>{
  3434. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  3435. {
  3436. inherit: true, shell: true,
  3437. env: ENV
  3438. , cwd: instanceroot + '/' + repo
  3439. , runas: processedArgs.runas
  3440. , title: `'git', ${['config', '--replace-all', 'core.symlinks', selectedinstance.username].join(' ')}`
  3441. })
  3442. }
  3443. initTask(task)
  3444. if(repodef.requiresElevation) {
  3445. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  3446. return elevatedBatch[elevatedBatch.length-1]
  3447. }
  3448. else {
  3449. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  3450. return regularBatch[regularBatch.length-1]
  3451. }
  3452. })
  3453. }
  3454. initTask(task)
  3455. if(repodef.requiresElevation) {
  3456. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  3457. return elevatedBatch[elevatedBatch.length-1]
  3458. }
  3459. else {
  3460. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  3461. return regularBatch[regularBatch.length-1]
  3462. }
  3463. }
  3464. }
  3465. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current GITEA username
  3466. var defaultRepoOwner = 'chess';
  3467. var elevatedRunasRepos = null
  3468. var gitRepos = null
  3469. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  3470. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  3471. var dbForLabel = function (label) {
  3472. var dbsForLabel = {
  3473. devmysql: 'mysql'
  3474. , development: 'mssql'
  3475. , production: 'mssql'
  3476. }
  3477. return dbsForLabel[label] || 'mysql'
  3478. }
  3479. // Maps an environment to a branch. Not required if the branch is appropriately named.
  3480. var checkoutMap = { 'development': 'master' }
  3481. // SAM : TODO Use nodeshellexec where to detect git installation dir
  3482. var gitbash = shell_verse.getbash()
  3483. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  3484. // Relevant git repos
  3485. var exludeMergeRepos = [];
  3486. var useGitPull = processedArgs.useGitPull || false;
  3487. var configPromise = null
  3488. var reconfirmcmds = { create : true }
  3489. var subcommandlabels = {
  3490. switch : (`switch ${processedArgs._[1] || ''}`).trim()
  3491. }
  3492. var independentcmd = function(){
  3493. return false;
  3494. }
  3495. var util = require('util');
  3496. var cliname = 'elxr';
  3497. var ver = '1.1';
  3498. var readme = `
  3499. Command syntax examples
  3500. elxr
  3501. Displays help. Same as elxr h
  3502. elxr i
  3503. Runs interactive propmts to help choose installation options.
  3504. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  3505. General command syntax.
  3506. Eg: NODE_ENV=development elxr pull elixir
  3507. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  3508. The specific cmd defines what the value is interpreted as.
  3509. There are several cmds that do not require an {{instancename}} parameter.
  3510. Eg: elxr remote remove origin
  3511. Git operations or passthrough external commands on all repository folders in you working directory.
  3512. Main objectives.
  3513. elxr cli is a wrapper around other shell commands and api based operations.
  3514. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  3515. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  3516. `;
  3517. var help = `
  3518. ${readme}
  3519. # list of commands... please refer dveloper documentation for ${cliname}
  3520. \r\n\t${
  3521. Object.keys(op).join('\r\n\t')
  3522. }
  3523. `;
  3524. var elxr = {
  3525. help() {
  3526. return chalk.cyanBright(`
  3527. -------------------------------------------------------------------------------
  3528. *** BBH Elixir ***
  3529. -------------------------------------------------------------------------------
  3530. elxr ${ver}
  3531. A cli tool for chess
  3532. ${help}
  3533. -------------------------------------------------------------------------------
  3534. `)
  3535. }
  3536. , info() {
  3537. return chalk.cyanBright(`
  3538. -------------------------------------------------------------------------------
  3539. *** BBH Elixir ***
  3540. -------------------------------------------------------------------------------
  3541. elxr ${ver}
  3542. A cli tool for chess
  3543. -------------------------------------------------------------------------------
  3544. `)
  3545. }
  3546. , getpulltask(args){
  3547. // def can be an instance config
  3548. // Or an object with many repos and elevated repos
  3549. // Or a single repo ( Either Elevated or normal. )
  3550. // USAGE
  3551. // elxr pull elixir origin master
  3552. // elxr pull
  3553. // not all remote branches are setup to be tracked locally (respective remotes and branches).
  3554. // pull --all is useless. As it fetches all remotes and branches but only merges current branch.
  3555. // apart from remote tracking branches We are interested in pulling from all remotes and relavant branches.
  3556. // The branch pipline should feed back to master
  3557. // master -> test -> stage -> release[nnnn] -> production
  3558. // (master) <= git merge [all remotes] production && git merge [all remotes] release[nnnn]
  3559. // git merge [all remotes] stage && git merge [all remotes] test && git merge [all remotes] master
  3560. var __args = {
  3561. remotename : args.remotename|| processedArgs._[2]
  3562. , url : args.url || processedArgs._[3]
  3563. , branch : args.branch || processedArgs._[4] // If branch not specified opearte on the current branch of each working directorys
  3564. }
  3565. // var commands = [
  3566. // // ['git', ['checkout', __args.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]]
  3567. // ,
  3568. // ]
  3569. // var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  3570. // var pullCmd = [ gitbash
  3571. // , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  3572. // , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  3573. var def = args || {
  3574. repos : selectedinstance.repos,
  3575. elevated : selectedinstance.elevated
  3576. }
  3577. var elevatedpulltasks = null;
  3578. if(def.repo) {
  3579. // Single repo case.
  3580. if(def.repo.requiresElevation) {
  3581. var t1 = function() {
  3582. return performPull(def).then(() => {
  3583. return true;
  3584. }).catch((e) => {
  3585. console.error(e)
  3586. }).finally(Traq.finally)
  3587. }
  3588. t1.statuslog = statuslog
  3589. t1.selectedinstance = selectedinstance
  3590. t1.processedArgs = processedArgs
  3591. elevatedpulltasks = shell_verse.getElevatedTask( t1 )
  3592. }
  3593. else {
  3594. var t2 = function(){
  3595. return performPull(def).then(() => {
  3596. console.log('pulled ' + JSON.stringify(def.repo))
  3597. return true;
  3598. }).catch((e) => {
  3599. console.error(e)
  3600. })
  3601. // .finally(Traq.finally)
  3602. }
  3603. t2.statuslog = statuslog
  3604. var regularpulltasks = shell_verse.getNonElevatedTask( t2 )
  3605. }
  3606. if(elevatedpulltasks) return elevatedpulltasks //getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  3607. else return regularpulltasks // getTaskWithoutElevation({ regularpulltasks})
  3608. }
  3609. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  3610. console.dir(def)
  3611. console.log('Running exlr pull : ' + path.dirname(__dirname))
  3612. var useGitPull = processedArgs.useGitPull || false;
  3613. if(def.elevated || def.repos) {
  3614. if(def.elevated) def.requiresElevation = true;
  3615. else delete def.requiresElevation;
  3616. }
  3617. else {
  3618. if(def.requiresElevation) def.elevated = [def]
  3619. else def.repos = [def]
  3620. }
  3621. var regularpulltasks = function(){ return Promise.resolve(true) }
  3622. if(def.elevated){
  3623. elevatedpulltasks = function() {
  3624. var eBatch = []
  3625. def.elevated.map((def) => getPullTask(def, null, null, null, eBatch))
  3626. if(eBatch.length<1) return Promise.resolve(true);
  3627. eBatch[0].processedArgs = processedArgs
  3628. return shell_verse.runElevatedBatch(eBatch).then(() => {
  3629. return true;
  3630. }).catch((e) => {
  3631. console.error(e)
  3632. })
  3633. }
  3634. elevatedpulltasks.statuslog = statuslog
  3635. }
  3636. if(def.repos) {
  3637. var regularpulltasks = function(){
  3638. var pendingpulls = [];
  3639. def.repos.forEach((def) => {
  3640. pendingpulls.push(
  3641. // PB : TODO serializing to prevent out of memory.
  3642. // Need to optimize as batches and streams...
  3643. function(){
  3644. // if(def.repo === 'setup') return;
  3645. // if(def.repo !== 'chess-client-lib') return;
  3646. return performPull(def).then(()=>{ console.log('pulled ' + JSON.stringify(def.repo)) })
  3647. .catch(e => {
  3648. console.error(util.inspect(e)); throw e })
  3649. }
  3650. )
  3651. })
  3652. return any(pendingpulls).finally(Traq.finally)
  3653. }
  3654. regularpulltasks.statuslog = statuslog
  3655. }
  3656. // if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  3657. // else return getTaskWithoutElevation({ regularpulltasks})
  3658. return elevatedpulltasks().then(()=>{
  3659. if(isWin() && isElevated) return Promise.resolve(true);
  3660. return regularpulltasks()
  3661. })
  3662. }
  3663. }
  3664. function preworkerconfig(){
  3665. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  3666. gitRepos = selectedinstance.repos
  3667. // gitRepos = ['chess-server-lib'];
  3668. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  3669. elevatedRunasRepos = selectedinstance.elevated
  3670. // Repos that should excluded from merge for releases...
  3671. exludeMergeRepos = selectedinstance.exludeMergeRepos
  3672. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  3673. // mysql -u root -p db_name < drop_all_tables.sql
  3674. var mysql = '../xampp/mysql/bin/mysql'
  3675. var mysqldump = '../xampp/mysql/bin/mysqldump'
  3676. }
  3677. // The main elxr cli process
  3678. function elxrworker() {
  3679. var __runcmd = function (label) {
  3680. var distinquishedlabel = subcommandlabels[label] || label
  3681. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  3682. }
  3683. return __runcmd(processedArgs.label || processedArgs._[0] || 'undefined');
  3684. }
  3685. // function acquireChoices(selectedinstance) {
  3686. // var hasconfig = false;
  3687. // console.warn(chalk.cyan(`
  3688. // -------------------------------------------------------------------------------
  3689. // Could not locate your preferred configuration (you may not specified it)
  3690. // You should fork the default chess configuration to customize and make it
  3691. // your own instance with a named config as
  3692. // {{yourowninstancename}}-config-{{yourchosenenvironment}}
  3693. // And then run this tool as follows
  3694. // NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  3695. // OR
  3696. // Run this tool with the following command to use a quick start default.
  3697. // elxr --default
  3698. // OR
  3699. // Choose one of the options below to run interactively.
  3700. // We will run your choice at the next prompt.
  3701. // -------------------------------------------------------------------------------
  3702. // `))
  3703. // var choices = getInteractionPoints(detectedinstanceoptions, __interactive_prompts)
  3704. // var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  3705. // return initinstances(selectedinstance)
  3706. // })
  3707. // // var prompt = cli.prompter;
  3708. // // return prompt.ask(`Choose an option :
  3709. // // d) Install the default chess instance.
  3710. // // => elxr i chess node_env=development --default
  3711. // // n) Create your custom new instance interactively
  3712. // // => elxr i {{instanceName}} node_env={{environment}}
  3713. // // i) Choose an instance and environment to install
  3714. // // => elxr i {{instanceName}} node_env={{environment}}
  3715. // // c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  3716. // // => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  3717. // // h) Help
  3718. // // q) Quit
  3719. // // Default <= d
  3720. // // : `).then((choice) => {
  3721. // // if (choice && choice === 'd' || !choice) {
  3722. // // processedArgs._[0] = 'i'
  3723. // // selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  3724. // // selectedinstance.node_env = processedArgs.node_env = (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  3725. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  3726. // // }
  3727. // // else if (choice === 'h') {
  3728. // // processedArgs._[0] = 'h'
  3729. // // fs.writeFileSync('run.done', 'noop help');
  3730. // // console.log(elxr.help()); process.exit()
  3731. // // }
  3732. // // else if (choice === 'n' || choice === 'i') {
  3733. // // var p1 = cli.prompter;
  3734. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  3735. // // processedArgs._[0] = 'i'
  3736. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  3737. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  3738. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  3739. // // if (choice === 'n') {
  3740. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  3741. // // console.warn(
  3742. // // chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  3743. // // process.exit();
  3744. // // }
  3745. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  3746. // // selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  3747. // // })
  3748. // // })
  3749. // // })
  3750. // // } else if (choice === 'c') {
  3751. // // var p1 = cli.prompter;
  3752. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  3753. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  3754. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  3755. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  3756. // // return p1.ask(`Enter cmd :
  3757. // // p) pull
  3758. // // Default <= p
  3759. // // : `).then(function (cmd) {
  3760. // // if (!cmd || cmd === 'p') {
  3761. // // processedArgs._[0] = 'pull'
  3762. // // }
  3763. // // else processedArgs._[0] = cmd
  3764. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  3765. // // selectedinstance.reposerver = reposerver || selectedinstance.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  3766. // // })
  3767. // // })
  3768. // // })
  3769. // // })
  3770. // // } else {
  3771. // // 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.`));
  3772. // // fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  3773. // // fs.writeFileSync('run.done', 'noop quit');
  3774. // // process.exit()
  3775. // // }
  3776. // // })
  3777. // }
  3778. var os = require("os");
  3779. var hostname = os.hostname();
  3780. var clustername = null; // PB : TODO -- Prompt to acquire.
  3781. var configs = (function(){
  3782. // We need to discover and use the most specialized config available.
  3783. // Two passes are required as the config currently cloned may be switched by the discovery.
  3784. // If the repo name is the same but has different remotes the newly acquired config from multiple remotes may
  3785. // iteself redefine the remotes, repos and servers for the config which we need to honor..
  3786. return {
  3787. ownerClusterNodeConfig(selected) {
  3788. // Hostname and therefore clusternodename can be anything and can participate in many clusters.
  3789. // 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 )
  3790. var clusternodename = hostname || `CHESS0001${selected.username}`; // Cluster node names need to be unique accross all clusters to avoid collitions.
  3791. clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
  3792. return __acquireConfig(selected, { remote : 'userfork' } // PB : TODO -- accessiblity state should switch to public etc..
  3793. , selected.instanceName + '-config-' + selected.node_env + `-${clusternodename}`
  3794. , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
  3795. e.benign = true
  3796. return e; }
  3797. )
  3798. }
  3799. , ownerInstnace(selected) { return __acquireConfig(selected, { remote : 'userfork' }
  3800. , selected.instanceName + '-config-' + selected.node_env
  3801. , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
  3802. e.benign = true
  3803. return e }
  3804. )
  3805. }
  3806. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  3807. , commonInstance(selected) { return __acquireConfig(selected, { repoOwner : defaultRepoOwner }
  3808. , undefined
  3809. , function(e){
  3810. // PB : TODO -- console.info('This is probably an error unless the user is asking to create a new instance with this name.')
  3811. statuslog.statuslog(e, e)
  3812. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  3813. utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  3814. , selectedinstance, require(manifestpath)( null, { utils, username : selectedinstance.username, instanceName : selectedinstance.instanceName
  3815. , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' } ))
  3816. console.dir(selectedinstance.repos)
  3817. // Config from server always override merges into selection except for the current selection.
  3818. // PB : TODO -- utils.assign Array merges are non-distinct...
  3819. if(selectedinstance?.repos && !selectedinstance.repos[0].repo) {
  3820. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  3821. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  3822. }
  3823. if(selectedinstance?.elevated && !selectedinstance.elevated[0]?.repo) {
  3824. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  3825. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  3826. }
  3827. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  3828. , selected, selectedinstance)
  3829. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  3830. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  3831. cacheWriteInstanceConfig(chessinstances, selectedinstance.root, selectedinstance)
  3832. // ENV.NODE_ENV = selectedinstance.node_env;
  3833. throw e
  3834. }
  3835. ) }
  3836. // , genericChessInstance(selected) { return __acquireConfig(selected, { repoOwner : defaultRepoOwner }) }
  3837. }
  3838. })()
  3839. var eNotImplemented = function(){
  3840. console.error('Not yet implemented')
  3841. process.exit()
  3842. }
  3843. // PB : TODO -- accept additional arg - an array specifying custom configPriority.
  3844. var acquireConfig = function(slections){
  3845. var configPriority = [ 'ownerClusterNodeConfig', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  3846. return any(configPriority.map(cfg => { return function() { return configs[cfg](slections) } } ), true, true).then(()=>{
  3847. return acquireData(slections)
  3848. })
  3849. }
  3850. var instanceData = (function(){
  3851. return {
  3852. ownerClusterNodeData(selected) {
  3853. var clusternodename = hostname || `CHESS0001${selected.username}`; // Cluster node names need to be unique accross all clusters to avoid collitions.
  3854. clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
  3855. return __acquireData(selected, { remote : 'userfork' }
  3856. , selected.instanceName + '-data-' + selected.node_env + `-${clusternodename}`
  3857. , function(e){ console.info('Customized node level data not found. This is not an Error. Will attempt with owner level config.');
  3858. e.benign = true
  3859. return e; }
  3860. )
  3861. }
  3862. , ownerInstnace(selected) { return __acquireData(selected, { remote : 'userfork' }
  3863. , selected.instanceName + '-data-' + selected.node_env
  3864. , function(e){ console.info('Customized user level data not found. This is not an Error. Will attempt global common instance config.');
  3865. e.benign = true
  3866. return e }
  3867. )
  3868. }
  3869. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  3870. , commonInstance(selected) { return __acquireData(selected, { repoOwner : defaultRepoOwner }
  3871. // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
  3872. ) }
  3873. , genericChessInstance(selected) { return __acquireData(selected, { repoOwner : defaultRepoOwner }) }
  3874. }
  3875. })()
  3876. var acquireData = function(slections){
  3877. var configPriority = [ 'ownerClusterNodeData', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  3878. return any(configPriority.map(cfg => { return function() { return instanceData[cfg](slections) } } ), true, true)
  3879. }
  3880. function reinit(){
  3881. sysAddPathVar('%AppData%\\npm')
  3882. resetgitconfig()
  3883. }
  3884. function init(){
  3885. sysAddPathVar('%AppData%\\npm')
  3886. resetgitconfig()
  3887. }
  3888. function resetgitconfig(){
  3889. // https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows
  3890. // use git config --edit --system to remove the helper = manager line so that it is no longer registered as a credential helper.
  3891. // For bonus points, use git config --edit --global and insert:
  3892. // [core]
  3893. // askpass =
  3894. // https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage
  3895. // Git Credential storage...
  3896. // git config --global credential.helper 'store --file ~/.elxrcredentials'
  3897. // git credential fill
  3898. // protocol=https
  3899. // host=git.bbh.org.in
  3900. // username=bob
  3901. // password=pppp
  3902. // git credential-store --file ~/.gitcredentials store
  3903. // // notepad C:/Program Files/Git/etc/gitconfig
  3904. // git config --edit --system
  3905. // git credential-store --file ~/git.store store
  3906. // Find system git config
  3907. // git config --global --edit
  3908. // git config --list --show-origin
  3909. // git config --list --show-origin --show-scope
  3910. // https://stackoverflow.com/questions/35942754/how-can-i-save-username-and-password-in-git
  3911. // Recipie
  3912. // git config --global --unset credentials.helper
  3913. // cd /path/to/my/repo
  3914. // git config --unset credential.helper
  3915. // git config credential.helper 'store --file ~/.git_repo_credentials'
  3916. // git config credential.*.username my_user_name
  3917. // git config credential.https://gitlab.com.username my_user_name
  3918. // git credential fill
  3919. // git config --global credential.modalprompt false // doesnst work.
  3920. // core askpass = ;;; https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows
  3921. var options = {
  3922. inherit: true, shell: true, env: ENV
  3923. , cwd: instanceroot
  3924. , runas: processedArgs.runas
  3925. }
  3926. var task = ['git', ['config'], options]
  3927. var tasklist = [
  3928. // ['--global', '--unset credentials.helper']
  3929. // ['--unset', 'credentials.helper']
  3930. // ,
  3931. // ['credential.helper', `'store --file git_repo_credentials'`]
  3932. ['--global', 'credential.helper', "'store --file ~/.git_repo_credentials'"]
  3933. , ['--global', '--replace-all', 'user.name', 'pb']
  3934. , ['--global', '--replace-all', 'user.email', 'pradeep@bbh.org.in']
  3935. // , ['--list']
  3936. // , ['credential', 'fill']
  3937. ]
  3938. var onEachError = e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n')
  3939. var shellT = (args) => { return getgitbashtask(args, onEachError)
  3940. // .catch(e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n' + tasq.toString()) )
  3941. }
  3942. execserial(tasklist, task, shellT, onEachError )
  3943. }
  3944. var createTasq = (args, shellT, onEachError) => {
  3945. var tasq = shellT ? shellT(args) : (() => { return nodeShellExec.apply(null, args).catch( onEachError || function(e){ console.error(e) } ) })
  3946. tasq.toString = function(){ return JSON.stringify(args)}
  3947. return tasq;
  3948. }
  3949. var execserial = function(tasklist, task, shellT){
  3950. var exec = (taskArgs)=>{
  3951. var thistask = task.concat();
  3952. thistask[1] = thistask[1].concat()
  3953. thistask[1].push.apply(thistask[1], taskArgs)
  3954. return createTasq(thistask, shellT)
  3955. }
  3956. return any(tasklist.map(exec))
  3957. }
  3958. var execonce = function(taskArgs, task){ return any([task[1].push.apply(task[1], taskArgs)].map(createTasq)) }
  3959. var __acquireConfig = function (selected, options, configrepo, errHandler) {
  3960. configrepo = configrepo || selected.instanceName + '-config-' + selected.node_env;
  3961. var repoOwner = options.repoOwner || selected.username || options.defaultRepoOwner
  3962. var errorHandler = (e) => {
  3963. if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${repoOwner}/${configrepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
  3964. // console.error('Could not connect to repo server. Timed Out')
  3965. 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 => {
  3966. if(propValue === 'y') {
  3967. reconfirm = getReconfirmAll()
  3968. return startElxr()
  3969. }
  3970. else if(propValue === 'r'){
  3971. return acquireConfig(selected)
  3972. }
  3973. else process.exit()
  3974. })
  3975. }
  3976. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${repoOwner}/${configrepo}.git/' not found`))){
  3977. var choices = {
  3978. t : `install a new temporary local instance with this name ( will not persist ).
  3979. Use your own username for additional options. You can request for a username at chess@bbh.org.in )`
  3980. , e : 'exit' }
  3981. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  3982. choices = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  3983. , {
  3984. i : 'create a new instance with this name => will fork the default config under your username'
  3985. , f : 'fork a new instance with this name for yourself for this node from another instance'
  3986. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  3987. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  3988. , p : 'create a custom config for yourself '
  3989. }, choices)
  3990. }
  3991. return cli.prompt( choices
  3992. , 'Config for instance not found. Would you like to ', 'e' ).then(propValue => {
  3993. if(propValue === 't') {
  3994. selectedinstance.local = true; return createInstance(selectedinstance)
  3995. }
  3996. if(propValue === 'i') return eNotImplemented()
  3997. if(propValue === 'f') return eNotImplemented()
  3998. if(propValue === 'o') return eNotImplemented()
  3999. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  4000. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  4001. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  4002. else process.exit()
  4003. })
  4004. }
  4005. console.warn(e)
  4006. throw e; //('Config acquisition failed.')
  4007. }
  4008. var successHandler = () => {
  4009. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  4010. utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  4011. , selectedinstance, require(manifestpath)( null, { utils, username : selectedinstance.username, instanceName : selectedinstance.instanceName
  4012. , node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver }))
  4013. console.dir(selectedinstance.repos)
  4014. // Config from server always override merges into selection except for the current selection.
  4015. // PB : TODO -- utils.assign Array merges are non-distinct...
  4016. if(!selectedinstance.repos[0].repo) {
  4017. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  4018. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  4019. }
  4020. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  4021. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  4022. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  4023. }
  4024. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  4025. , selected, selectedinstance)
  4026. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  4027. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  4028. cacheWriteInstanceConfig(chessinstances, selectedinstance.root)
  4029. ENV.NODE_ENV = selectedinstance.node_env;
  4030. }
  4031. return performPull( selected.reposindexed[configrepo] || { repo : configrepo }
  4032. , null, repoOwner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  4033. .catch( (e)=>{
  4034. // if(e){
  4035. if(Promise.resolve(e) === e) return e;
  4036. // console.error(e)
  4037. e.benign = true;
  4038. throw e; // Not a hard error but we need this for bcontinueonfailure as we still want to stop on firstsuccess.
  4039. // }
  4040. })
  4041. }
  4042. var __acquireData = function (selected, options, datarepo, errHandler) {
  4043. datarepo = datarepo || selected.instanceName + '-data';
  4044. var repoOwner = options.repoOwner || selected.username || options.defaultRepoOwner
  4045. var errorHandler = (e) => {
  4046. if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${repoOwner}/${datarepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
  4047. // console.error('Could not connect to repo server. Timed Out')
  4048. 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 => {
  4049. if(propValue === 'y') {
  4050. reconfirm = getReconfirmAll()
  4051. return startElxr()
  4052. }
  4053. else if(propValue === 'r'){
  4054. return acquireConfig(selected)
  4055. }
  4056. else process.exit()
  4057. })
  4058. }
  4059. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${repoOwner}/${datarepo}.git/' not found`))){
  4060. var choices = {
  4061. t : `install a temporary local data folder.
  4062. For more options. Request and use a personal username at chess@bbh.org.in )`
  4063. , e : 'exit' }
  4064. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  4065. choices = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  4066. , {
  4067. i : 'create a new instance with this name => will fork the default config under your username'
  4068. , f : 'fork a new instance with this name for yourself for this node from another instance'
  4069. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  4070. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  4071. , p : 'create a custom config for yourself '
  4072. }, choices)
  4073. }
  4074. return cli.prompt( choices
  4075. , 'Data repo for instance not found. Would you like to ', 'e' ).then(propValue => {
  4076. if(propValue === 't') {
  4077. selectedinstance.local = true; return createInstanceData(selectedinstance)
  4078. }
  4079. if(propValue === 'i') return eNotImplemented()
  4080. if(propValue === 'f') return eNotImplemented()
  4081. if(propValue === 'o') return eNotImplemented()
  4082. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  4083. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  4084. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  4085. else process.exit()
  4086. })
  4087. }
  4088. console.warn(e)
  4089. throw e; //('Config acquisition failed.')
  4090. }
  4091. var successHandler = () => {
  4092. }
  4093. return performPull( selected.reposindexed[datarepo] || { repo : datarepo }
  4094. , null, repoOwner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  4095. .catch( (e)=>{
  4096. // if(e){
  4097. if(Promise.resolve(e) === e) return e;
  4098. // console.error(e)
  4099. e.benign = true;
  4100. throw e; // Not a hard error but we need this for bcontinueonfailure
  4101. // }
  4102. })
  4103. }
  4104. // ----------------------------------------------------------------
  4105. // PB : TODO -- Review and obsolete...
  4106. // ----------------------------------------------------------------
  4107. // var launchpath = path.resolve(path.normalize(ENV.wd))
  4108. var launchpath = selectedinstance.root
  4109. // // we were run.
  4110. // // The easisest would be to ask for a target directory and default to current dir....
  4111. // // path.dirname(launchpath).split(path.sep).pop()
  4112. // var parent = path.dirname(launchpath);
  4113. // var pp = launchpath;
  4114. // var instancediscoverytasks = [];
  4115. // while(parent !== pp){
  4116. // instancediscoverytasks.push(
  4117. // ((pa)=>{
  4118. // var p = pa;
  4119. // return function(){
  4120. // return hasElxr(p).then((value)=>{
  4121. // if(value) return p
  4122. // // PB : TODO -- Using throw like this is not friendly with any...
  4123. // throw Object.assign( new Error('Benign Failure in Batch')
  4124. // , { value : false, benign : true });
  4125. // })
  4126. // }
  4127. // })(pp)
  4128. // )
  4129. // pp = parent;
  4130. // parent = path.dirname(parent);
  4131. // }
  4132. // var instanceroot = null
  4133. // var detectInstanceRoot = any(instancediscoverytasks, true, true).then( ir => {
  4134. // if(ir.error) { instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ; }
  4135. // else instanceroot = ir.pVal
  4136. // return instanceroot
  4137. // }).catch(()=>{
  4138. // instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
  4139. // })
  4140. // We first load the default and then override with a runconfig if it exists else we override with the interactive prompts.
  4141. // Then acquire and reload and replace this default.
  4142. var __interactive_prompts = function( target, choices, promptsfilter ){
  4143. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  4144. var interactionpoints = unbound_interactionpoints.bind({target, choices})(selectedinstance)
  4145. function getPromptKeys() {
  4146. // PB : TODO -- get interactionpoints
  4147. if(! (processedArgs.label || processedArgs._[0]) ) return Object.assign({}, interactionpoints);
  4148. return promptkeys // PB : TODO __ Convert pormptkeys to filtered interactionpoints.
  4149. }
  4150. var eachPrompt = getBoundEachPrompt( target, getPromptKeys() , interactionpoints, choices, promptsfilter)
  4151. return Object.keys(promptsfilter || interactionpoints).reduce(eachPrompt, [])
  4152. }
  4153. var downloadsdir = '../Downloads';
  4154. var prerequisites = [
  4155. {
  4156. shellcmd: 'git',
  4157. name : 'git',
  4158. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  4159. , installer: 'Git-2.31.0-64-bit.exe'
  4160. , installcmd: ['cmd', ['/c', 'start',
  4161. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  4162. , '/VERYSILENT'
  4163. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  4164. ]]
  4165. , preinstallsteps: function() {
  4166. var steps = [
  4167. () => {
  4168. if (!existsSync(downloadsdir + '/' + this.installer)) {
  4169. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  4170. }
  4171. else return Promise.resolve(true)
  4172. }
  4173. ]
  4174. var prompts = this.getuser(null, ()=>{
  4175. // console.log('preinstallsteps')
  4176. // var gitUser = 'guest';
  4177. // var gitEmail = 'guest@bbh.org.in';
  4178. // var prompts = [];
  4179. // prompts.push( ()=>{ return cli.prompt(choices['username'], 'git user name').then(gituser => gitUser = gituser) } )
  4180. // prompts.push( ()=>{ return cli.prompt(choices['useremail'], 'git user email').then(gitemail => gitEmail = gitemail) } )
  4181. // console.log('prompting in preinstallsteps')
  4182. // return any(prompts).then(()=>{
  4183. // var steps = [
  4184. // ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  4185. // , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  4186. // ]
  4187. // return any(steps.map(getshelltask)).then(() => {
  4188. // })
  4189. // });
  4190. return Promise.resolve(true)
  4191. })
  4192. return any([any(steps), prompts])
  4193. }
  4194. , installsteps: function () {
  4195. return any([this.installcmd].map(getshelltask))
  4196. }
  4197. , postinstallsteps: function(err, users){
  4198. return this.getuser(null, (err, data)=>{
  4199. // ignore err and proceed with data as guest.
  4200. console.dir(data)
  4201. if(data && data.length === 1 && !shouldPrompt('username', promptkeys, selectedinstance) ) {
  4202. return username = data[0];
  4203. }
  4204. data = data || ['guest']
  4205. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  4206. console.log('prompting in postinstallsteps')
  4207. var username = 'guest';
  4208. var email = 'guest@bbh.org.in';
  4209. var password = '***';
  4210. return any( getInteractionPoints([selectedinstance], promptkeys, { username, password, email}) ).then(()=>{
  4211. if(!data.find(e => e === selectedinstance.username)) {
  4212. var steps = [
  4213. ['git', ['config', '--global', '--add', 'user.name', `${username}`]]
  4214. , ['git', ['config', '--global', '--add', 'user.email', `${email}`]]
  4215. ]
  4216. return any(steps.map(getshelltask)).then(() => {
  4217. })
  4218. }
  4219. else {
  4220. return Promise.resolve(true)
  4221. }
  4222. });
  4223. })
  4224. }
  4225. , install: function () {
  4226. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  4227. }
  4228. , verifyAndInstall : function(){
  4229. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  4230. if(exists) {
  4231. // return any(['git', ['config', '--global', '-l']].map(getshelltask))
  4232. return this.postinstallsteps.bind(this)()
  4233. }
  4234. return this.install();
  4235. });
  4236. }
  4237. , getuser : function(repo, onResult){
  4238. var __onResult = onResult || function(e, data){
  4239. data = data || []
  4240. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  4241. // console.dir(choices)
  4242. return data[0]
  4243. }
  4244. var globalOrLocal = '--global';
  4245. if(repo) globalOrLocal = '--local'
  4246. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(getshelltask)).then((result)=>{
  4247. // not yet configured.
  4248. if(!result.success) return __onResult(result)
  4249. else {
  4250. var users = result.messages[0].trim().split('\n');
  4251. if(users.length === 0 ||
  4252. users.length === 1 && users[0] === 'guest') {
  4253. return __onResult(result)
  4254. }
  4255. else {
  4256. return __onResult(null, Array.from( new Set( users ) ) ); }// PB : TODO == We should probably prompt with all the users available for selection !
  4257. }
  4258. })
  4259. .catch((e)=>{
  4260. console.error(e)
  4261. return __onResult(e)
  4262. })
  4263. }
  4264. }
  4265. ,
  4266. {
  4267. shellcmd: 'node',
  4268. name : 'node',
  4269. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  4270. , installer: 'node-v14.16.0-x64.msi'
  4271. , installcmd: ['MSIEXEC.exe', ['/i'
  4272. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  4273. , 'ACCEPT=YES', '/passive']]
  4274. , install : function() { return any([this.installcmd].map(getshelltask)).then(() => { }) }
  4275. }
  4276. ]
  4277. for(var i=0; i<prerequisites.length; i++) {
  4278. prerequisites[prerequisites[i].name] = prerequisites[i];
  4279. }
  4280. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  4281. function ensureDirectoryExistence(filePath) {
  4282. var dirname = path.dirname(filePath);
  4283. if (fs.existsSync(dirname)) {
  4284. return filePath;
  4285. }
  4286. ensureDirectoryExistence(dirname);
  4287. fs.mkdirSync(dirname);
  4288. return filePath;
  4289. }
  4290. var mainTasks = [];
  4291. function verifyAndInstallPrerequisites() {
  4292. var downloadtasks = [];
  4293. var installtasks = [];
  4294. prerequisites.forEach(preq => {
  4295. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  4296. if (exists) console.log(`${preq.shellcmd} exists`)
  4297. else {
  4298. console.log(`${preq.shellcmd} is not installed`)
  4299. return preq.preinstallsteps.call(preq).then(() => {
  4300. installtasks.push(preq.install.bind(preq))
  4301. })
  4302. }
  4303. }))
  4304. })
  4305. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  4306. }
  4307. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  4308. var runconfig = null;
  4309. var promptkeys = {
  4310. cmd : processedArgs._[0] || 'pull'
  4311. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  4312. // 'instanceName' : true
  4313. // , 'node_env' : true
  4314. // , username : ''
  4315. // , runchoice : 'c'
  4316. }
  4317. // promptkeys.runchoice = promptkeys.cmd ? 'c' : undefined
  4318. var choices = {
  4319. 'instanceName' : []
  4320. , 'reposerver' : []
  4321. , 'upstream-remote' : []
  4322. , 'instanceType' : []
  4323. , username : ['guest', 'chessdemo', 'demo']
  4324. }
  4325. var getInteractionPoints = function(detectedinstanceoptions, possiblePrompts, promptsfilter){
  4326. var instances = []
  4327. var reposervers = [];
  4328. var remotes = [];
  4329. var instanceNames = []
  4330. var instanceTypes = ['development', 'production'];
  4331. // Accumulate all known choices from every possible instance...
  4332. Object.keys( chessinstances).forEach(instanceName => {
  4333. if(instanceName === 'current_run') return ;
  4334. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  4335. var instance = chessinstances[instanceName][node_env];
  4336. reposervers = reposervers.concat(instance.reposervers)
  4337. if(instance.reposerver) reposervers.push(instance.reposerver)
  4338. instances.push(instance)
  4339. instanceTypes.push(instance.node_env)
  4340. instanceNames.push(instance.instanceName)
  4341. var otherremotes = instance?.reposerverinstances
  4342. if(otherremotes) otherremotes = otherremotes[instance?.reposerver]?.remotes
  4343. otherremotes = otherremotes || {}
  4344. Array.prototype.push.apply(remotes, Object.keys(otherremotes))
  4345. })
  4346. })
  4347. instances = instances.concat(detectedinstanceoptions)
  4348. if(selectedinstance['instanceName']) instanceNames.push(selectedinstance['instanceName'])
  4349. if(possiblePrompts['instanceName']) instanceNames.push(possiblePrompts['instanceName'])
  4350. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers'])
  4351. choices['instanceName'] = Array.from( new Set(instanceNames.concat(choices['instanceName'])) )
  4352. choices['reposerver'] = Array.from( new Set(reposervers.concat(choices['reposerver'])) )
  4353. // choices['upstream-remote'] = Array.from( new Set(remotes.concat(choices['upstream-remote'])) )
  4354. choices['instanceType'] = Array.from( new Set(instanceTypes.concat(choices['instanceType'])) )
  4355. return __interactive_prompts(selectedinstance, choices, promptsfilter)
  4356. }
  4357. var detection_state = {
  4358. localInstanceDetected : false
  4359. }
  4360. function createInstanceData(target, source) {
  4361. var sourceinstance = source || target;
  4362. console.dir(sourceinstance)
  4363. var args = {
  4364. remotebase : sourceinstance.reposerver + '/chess/'
  4365. , sourcerepo : sourceinstance.repo || 'chess-data'
  4366. , targetrepo : `${target.instanceName}-data-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  4367. }
  4368. if(sourceinstance.local) {
  4369. var options = {
  4370. inherit: true, shell: true,
  4371. env: ENV
  4372. , cwd : instanceroot
  4373. , runas: processedArgs.runas
  4374. }
  4375. var cmdseq = [
  4376. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  4377. ]
  4378. return any(cmdseq.map(getshelltask)).then(() => { return true })
  4379. }
  4380. else {
  4381. // http://try.gitea.io/api/v1/org/{org}/repos
  4382. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  4383. throw 'createInstanceData is possible only within the same repository server.'
  4384. }
  4385. var server = new URL(target.reposerver);
  4386. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  4387. , username : target.username, password : target.password
  4388. }
  4389. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  4390. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  4391. return GITEA.repository.updateattributes( {
  4392. hostname : server.host, protocol : server.protocol
  4393. , username : target.username, password : target.password
  4394. }
  4395. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  4396. , { name : `${args.targetrepo}`}
  4397. )
  4398. }
  4399. )
  4400. }
  4401. // GITEA.repository.updateattributes( {
  4402. // hostname : server.host, protocol : server.protocol
  4403. // , username : selectedinstance.username, password : selectedinstance.password
  4404. // }
  4405. // , { repo : `chess-config`, owner : selectedinstance.username }
  4406. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  4407. // )
  4408. // return selectedinstance
  4409. }
  4410. function createInstance(target, source) {
  4411. var sourceinstance = source || target;
  4412. console.dir(sourceinstance)
  4413. var args = {
  4414. remotebase : sourceinstance.reposerver + '/chess/'
  4415. , sourcerepo : sourceinstance.repo || 'chess-config'
  4416. , targetrepo : `${target.instanceName}-config-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  4417. }
  4418. if(sourceinstance.local) {
  4419. var options = {
  4420. inherit: true, shell: true,
  4421. env: ENV
  4422. , cwd : instanceroot
  4423. , runas: processedArgs.runas
  4424. }
  4425. var cmdseq = [
  4426. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  4427. ]
  4428. return any(cmdseq.map(getshelltask)).then(() => { return true })
  4429. }
  4430. else {
  4431. // http://try.gitea.io/api/v1/org/{org}/repos
  4432. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  4433. throw 'createInstance is possible only within the same repository server.'
  4434. }
  4435. var server = new URL(target.reposerver);
  4436. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  4437. , username : target.username, password : target.password
  4438. }
  4439. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  4440. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  4441. return GITEA.repository.updateattributes( {
  4442. hostname : server.host, protocol : server.protocol
  4443. , username : target.username, password : target.password
  4444. }
  4445. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  4446. , { name : `${args.targetrepo}`}
  4447. )
  4448. }
  4449. )
  4450. }
  4451. // GITEA.repository.updateattributes( {
  4452. // hostname : server.host, protocol : server.protocol
  4453. // , username : selectedinstance.username, password : selectedinstance.password
  4454. // }
  4455. // , { repo : `chess-config`, owner : selectedinstance.username }
  4456. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  4457. // )
  4458. // return selectedinstance
  4459. }
  4460. var skipprerequisites = false;
  4461. function initinstances() {
  4462. // var root = selectedinstance.root
  4463. var instanceName = selectedinstance.instanceName
  4464. var node_env = selectedinstance.node_env
  4465. var reposerver = selectedinstance.reposerver
  4466. // var instanceName = selectedinstance.instanceName
  4467. // || clioverrides.instanceName
  4468. // // || processedArgs._[1]
  4469. // || chessinstances.current_run.instanceName
  4470. // var node_env = selectedinstance.node_env
  4471. // || clioverrides.node_env
  4472. // // || processedArgs.node_env
  4473. // || chessinstances.current_run.node_env
  4474. // var reposerver = selectedinstance.reposerver
  4475. // || clioverrides.reposerver
  4476. // // || processedArgs.node_env
  4477. // || chessinstances.current_run.reposerver
  4478. // if(!instanceName) {
  4479. // promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  4480. // promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  4481. // promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  4482. // }
  4483. // if(!node_env) {
  4484. // promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  4485. // promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  4486. // }
  4487. // if(!reposerver) {
  4488. // promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  4489. // }
  4490. // chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
  4491. // instanceName, node_env, root : selectedinstance.root, reposerver : selectedinstance.reposerver /* promptkeys['reposerver'] */ } );
  4492. // chessinstances['current_run'] = { instanceName: selectedinstance.instanceName, node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver, root }
  4493. // if(path.normalize(selectedinstance.root) !== path.normalize(chessinstances[selectedinstance.instanceName][selectedinstance.node_env].root)) {
  4494. // throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selectedinstance.root
  4495. // }
  4496. // Override sequence.
  4497. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  4498. // PB : TODO -- Undefined keys are overriding and deleting values. We should not allow that.
  4499. // This is ordinary utils.assign behavior. The key should not exist as undefined in the override.
  4500. // PB : TODO -- We now have options that can be passed into assign_core to control this behavior.
  4501. if(selectedinstance.node_env === undefined) delete selectedinstance.node_env
  4502. // selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  4503. // , __default
  4504. // , chessinstances[instanceName][node_env]
  4505. // , clioverrides
  4506. // , selectedinstance
  4507. // // , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
  4508. // );
  4509. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  4510. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  4511. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  4512. // // Brand New.
  4513. // selectedinstance = Object.assign( __default, selectedinstance )
  4514. // }
  4515. // Upgrade old formats..
  4516. if(selectedinstance?.repos && !selectedinstance?.repos[0]?.repo) {
  4517. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  4518. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  4519. }
  4520. if(selectedinstance?.elevated && !selectedinstance?.elevated[0]?.repo) {
  4521. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  4522. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  4523. }
  4524. // Config from server always override merges into selection except for the current selection.
  4525. // PB : TODO -- utils.assign Array merges are non-distinct...
  4526. // chessinstances[instanceName][node_env] = selectedinstance;
  4527. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  4528. cacheWriteInstanceConfig(chessinstances, selectedinstance.root)
  4529. // PB : TODO -- We should probably write the new server config also...
  4530. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  4531. return chessinstances
  4532. }
  4533. var skipprereqs = {}
  4534. var maintask = () => {
  4535. // Default cmd to run !
  4536. processedArgs._[0] === processedArgs._[0] || 'pull';
  4537. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  4538. if(!noprerequisites[processedArgs._[0]]
  4539. && !skipprereqs[processedArgs._[0]]
  4540. ) {
  4541. return prerequisites.git.verifyAndInstall().then(()=>{
  4542. var e = { message : 'verifyAndInstall', success : true}
  4543. var inittasks = []
  4544. var commontask = () => { preworkerconfig(); return elxrworker(true) }
  4545. if(!detection_state.localInstanceDetected) {
  4546. var t1 = ()=>{ return createInstance(selectedinstance) };
  4547. t1.statuslog = statuslog
  4548. var specifictask = shell_verse.getNonElevatedTask(t1)
  4549. }
  4550. else {
  4551. var t2 = ()=>{ return acquireConfig(selectedinstance) };
  4552. t2.statuslog = statuslog
  4553. var specifictask = shell_verse.getNonElevatedTask(t2)
  4554. }
  4555. inittasks.push( specifictask().catch((err) => {
  4556. e = err;
  4557. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  4558. console.error(err)
  4559. }).then( commontask )
  4560. // .finally(()=>{
  4561. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  4562. // if(!e.success) fs.writeFileSync('run.done', 'error');
  4563. // // return process.exit()
  4564. // }))
  4565. )
  4566. return any(inittasks)
  4567. })
  4568. }
  4569. else {
  4570. console.log('cmd has no preqs or has been configured to skip preqs')
  4571. preworkerconfig()
  4572. return elxrworker()
  4573. }
  4574. }
  4575. function generateDependencies(){
  4576. // PB : TODO -- Keep only the last n runs...
  4577. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  4578. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
  4579. fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
  4580. // PB : TODO include and build from files... using rollup..
  4581. var downloadbatch =
  4582. `::**************************************************************************
  4583. :Download_ <url> <File>
  4584. Powershell.exe ^
  4585. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  4586. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  4587. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  4588. exit /b
  4589. ::**************************************************************************`
  4590. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch)
  4591. var windowselevate =
  4592. `
  4593. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  4594. <script language="vbscript">
  4595. document.title = "elxr control panel"
  4596. self.ResizeTo 200,600
  4597. Sub Window_Onload
  4598. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  4599. End Sub
  4600. Set objShell = CreateObject("WScript.Shell")
  4601. Set objENV = objShell.Environment("Process")
  4602. dim NODE_ENV
  4603. NODE_ENV = objENV("NODE_ENV")
  4604. </script>
  4605. <script language="javascript">
  4606. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  4607. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  4608. // alert(windowselevate.commandLine)
  4609. var args = windowselevate.commandLine.split('"').slice(3);
  4610. // alert(args)
  4611. var processedArgs = { _ : [] }
  4612. var namedArgs = [];
  4613. namedArgs.push('--wd=' + objENV('wd'))
  4614. // alert(namedArgs)
  4615. for(var item in args){
  4616. if(args[item].charAt(0) === '-'){
  4617. namedArgs.push(args[item])
  4618. var split = args[item].split('=');
  4619. processedArgs[split[0].slice(2)] = split[1] || true;
  4620. }
  4621. else processedArgs._.push(args[item]);
  4622. }
  4623. // args = args.forEach(function(item){ })
  4624. // alert('processedArgs._ : ' + processedArgs._);
  4625. // alert(processedArgs.runas);
  4626. // alert(objENV('wd'))
  4627. // PB : TODO -- Convert all the cli args back to string.
  4628. // __filename will sure we are launhed using the same entry point.
  4629. var cargs = (processedArgs.debug ? '--inspect-brk=9226' : '') + ' ${__filename.replace(/\\/g, '\\\\')} ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  4630. var shell = new ActiveXObject('shell.application');
  4631. // alert('launching node privilged. ' + processedArgs['nodepath'])
  4632. // shell.ShellExecute('cmd.exe', '/k where node', '', '', 10);
  4633. // shell.ShellExecute('cmd.exe', '/k notepad.exe', '', 'runas', 1);
  4634. // shell.ShellExecute('cmd.exe ', '/k node ', '', 'runas', 1);
  4635. // shell.ShellExecute('cmd.exe ', '/k node ' + cargs + '', '', 'runas', 1);
  4636. shell.ShellExecute('node', cargs, '', 'runas', 1);
  4637. // alert('/k node ' + cargs + '')
  4638. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  4639. var fso = new ActiveXObject('Scripting.FileSystemObject');
  4640. window.onload = function() {
  4641. document.body.style.backgroundColor = 'black';
  4642. document.body.style.fontFamily = 'arial';
  4643. var log = document.createElement('div');
  4644. log.innerHTML='Please Wait';
  4645. function l(msg){ log.innerHTML+= msg; };
  4646. log.style.color = 'blue';
  4647. log.style.width = '95%';
  4648. log.id = 'log';
  4649. document.body.appendChild(log);
  4650. l('<Br/>Current config : ')
  4651. l('<Br/>NODE_ENV = ' + NODE_ENV)
  4652. l('<Br/>cmd = ' + processedArgs._[0])
  4653. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  4654. l('<Br/><Br/>')
  4655. // alert(fso.GetAbsolutePathName("."))
  4656. var timer = function(){
  4657. l('.');
  4658. if(fso.FileExists("run.done")) {
  4659. fso.DeleteFile('run.done') // PB : TODO -- IPC through files is needed only for windows we need to do it per run...
  4660. close();
  4661. }
  4662. else window.setTimeout(timer, 1000);
  4663. };
  4664. window.setTimeout(timer, 3000);
  4665. };
  4666. </script>
  4667. </html>
  4668. `
  4669. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate)
  4670. }
  4671. var startElxr = function() {
  4672. const retaincount = 2
  4673. var min = runtimestamp;
  4674. var collect = []
  4675. if(reconfirmcmds[processedArgs.label || processedArgs._[0]]) {
  4676. reconfirm = getReconfirmAll()
  4677. }
  4678. // detectedinstanceoptions.splice(0,0, __default) // PB : TODO -- Merge multiple...
  4679. var detectedinstanceoptions = [selectedinstance]
  4680. var cmdinstance = cmds[clioverrides.cmd]
  4681. var cmdprompts = cmdinstance.getPossiblePrompts()
  4682. // selectedinstance.node_env ? selectedinstance.node_env : selectedinstance.node_env = clioverrides.node_env
  4683. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  4684. utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }, selectedinstance, promptkeys )
  4685. // promptkeys = utils.assign(promptkeys, clioverrides)
  4686. // startElxr requires instance // Independent cmds should have already been bypassed.
  4687. // if(cmdprompts.instanceName) {
  4688. // not an instanceless cmd.
  4689. // console.dir(selectedinstance)
  4690. try {
  4691. // chessinstances = acquirelocalinstances(selectedinstance);
  4692. // findlocalinstances(chessinstances, detectedinstanceoptions)
  4693. initinstances(selectedinstance) // use the local instances for defaults if at all possible.
  4694. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  4695. var inst = initinstances(selectedinstance)
  4696. detection_state.localInstanceDetected = true;
  4697. return inst;
  4698. })
  4699. }
  4700. catch (e) {
  4701. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  4702. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  4703. return initinstances(selectedinstance)
  4704. })
  4705. // if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  4706. // // Weve not been told what to do.
  4707. // todo = todo.then(() => { return acquireChoices(selectedinstance) })
  4708. // }
  4709. todo = todo.then(() => {
  4710. try {
  4711. // chessinstances = acquirelocalinstances(selectedinstance)
  4712. // findlocalinstances(chessinstances, detectedinstanceoptions)
  4713. // detectedinstanceoptions.splice(0,0, __default)
  4714. initinstances(selectedinstance)
  4715. detection_state.localInstanceDetected = true;
  4716. }
  4717. catch (e) {
  4718. // console.error(e)
  4719. console.log('No local instances config found in current root = ' + selectedinstance.root);
  4720. console.log('A config will be createed with the instance and environment chosen...')
  4721. // return (async ()=>{return await __default.reposerver})().then(()=>{
  4722. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  4723. // return selectedinstance = Object.assign(__default, selectedinstance);
  4724. // })
  4725. detection_state.localInstanceDetected = false;
  4726. return selectedinstance
  4727. }
  4728. })
  4729. }
  4730. return todo.then( ()=>{
  4731. // PB : TODO -- Embed this in the build instead of inlining it.
  4732. // PB : TODO -- Also attepmt to load from ../chess-config/... as base for new instances...
  4733. initinstances(selectedinstance) // PB : TODO Review Initinstancess... and cleanup
  4734. // ---------------------------
  4735. runconfig = { NODE_ENV: selectedinstance.node_env }
  4736. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  4737. generateDependencies();
  4738. if(noprerequisites[processedArgs._[0]]
  4739. || skipprereqs[processedArgs._[0]]
  4740. ) {
  4741. return elxrworker()
  4742. }
  4743. var neTask = ()=>{
  4744. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`)
  4745. // collect garbage
  4746. return dirs( (dir)=>{
  4747. var matches = /run-(.*)/gm.exec(dir.name)
  4748. if(matches) {
  4749. if(+(matches[1]) < min) {
  4750. min = matches[1]
  4751. collect.splice( 0, 0, matches[1] )
  4752. }
  4753. else collect.push(matches[1])
  4754. }
  4755. return Promise.resolve(collect);
  4756. }, `${selectedinstance.root}/.elxr` )
  4757. .then(()=>{
  4758. // delete garbage
  4759. if(collect.length > retaincount) {
  4760. var asyncs = [];
  4761. while((collect.length - asyncs.length) > retaincount) {
  4762. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  4763. }
  4764. return Promise.all(asyncs)
  4765. }
  4766. else return true
  4767. })
  4768. .catch(e => {
  4769. console.error
  4770. })
  4771. }
  4772. neTask.statuslog = statuslog
  4773. shell_verse.getNonElevatedTask( neTask )()
  4774. var commonTask = ()=>{
  4775. verifyAndInstallPrerequisites.statuslog = statuslog
  4776. if((!skipprerequisites || processedArgs.forceprereqs)) mainTasks.push(verifyAndInstallPrerequisites);
  4777. mainTasks.push(maintask)
  4778. return any(mainTasks);
  4779. }
  4780. return commonTask()
  4781. })
  4782. // }
  4783. // else return Promise.resolve(true)
  4784. }
  4785. // return detectInstanceRoot.then(()=>{
  4786. var cmdobj = cmds[selectedinstance.cmd]
  4787. return Promise.all((cmdobj.requires || []).map( (r) => utils.promisify(null, r) ) ).then(()=>{
  4788. if(cmdobj.independentcmd) {
  4789. if(cmdobj.requiresElevation) {
  4790. return cmdobj.cmdFn(cmdobj.toArgs(processedArgs))
  4791. }
  4792. else return cmdobj.cmdFn(cmdobj.toArgs(processedArgs))
  4793. }
  4794. else return startElxr()
  4795. })
  4796. .catch(e => {
  4797. if(typeof e === 'symbol') console.log('error : ' + 'symbol')
  4798. else console.log('error : ' + e)
  4799. })
  4800. // })
  4801. })
  4802. })
  4803. // .then( () => {
  4804. // console.log(process._getActiveHandles());
  4805. // console.log(process._getActiveRequests());
  4806. // })
  4807. // detect if alread installed -> Take no action.
  4808. // download if no installer avalable -> next()
  4809. // install
  4810. function checkandinstall(items) {
  4811. var tasks = []
  4812. items.forEach(item => {
  4813. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  4814. })
  4815. return Promise.all(tasks).then(existances => {
  4816. existances.forEach((exists, i) => {
  4817. if (!exists) {
  4818. return downloadandinstall([items[i]])
  4819. }
  4820. })
  4821. })
  4822. }
  4823. function downloadandinstall(items) {
  4824. var tasks = []
  4825. items.forEach(item => {
  4826. tasks.push(getTaskDownload(item))
  4827. })
  4828. return Promise.all(tasks)
  4829. }
  4830. // Sample instances config.
  4831. // var instances = {
  4832. // "elixir": {
  4833. // "production": {
  4834. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  4835. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  4836. // , "exludeMergeRepos": {
  4837. // "elixir-config-development": true, "elixir-config-test": true
  4838. // , "elixir-config-production": true, "elixir-data": true
  4839. // }
  4840. // , "instanceName": "elixir", "node_env": "production"
  4841. // }
  4842. // },
  4843. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  4844. // }
  4845. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...