555
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 226KB

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