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.

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