Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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