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

index.js 262KB

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