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

index.js 241KB

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