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

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