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

index.js 226KB

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