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 238KB

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