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

index.js 207KB

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