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

index.js 262KB

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