Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

index.js 241KB

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