Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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