555
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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