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

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