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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367
  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( `${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. var instanceName = selectedinstance.instanceName ;
  2093. var node_env = selectedinstance.node_env;
  2094. // PB : TODO -- handle current_run switch...
  2095. // console.dir(chessinstances)
  2096. // PB : TODO -- We should be able to do simply merge at a higher level using assign
  2097. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos || [], 'repo') ;
  2098. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated || [], 'repo') ;
  2099. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  2100. }
  2101. var loadmanifest = function( mpath, moverrides ){
  2102. try {
  2103. // PB : TODO -- pick up remote definitions per repository...
  2104. return utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  2105. , {}, require(path.normalize( mpath + '/repo-manifest'))( null, moverrides ))
  2106. }
  2107. catch(e){
  2108. // console.warn(e);
  2109. return utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }, { error : true, e }, moverrides)
  2110. }
  2111. }
  2112. var selectedinstance = (function() {
  2113. // PB : TODO -- Override cli prefs and call with undefined selectedinstance only if there is no cli overide or selection.
  2114. var chessinstances = acquirelocalinstances( { root : ENV.wd } )
  2115. if(chessinstances.error) {
  2116. delete chessinstances.error
  2117. // use installchoices only when we don't find chessinstances.
  2118. try { var installchoices = require(path.normalize(ENV.wd + '/installchoices.js'))
  2119. chessinstances[installchoices.instanceName] = chessinstances[installchoices.instanceName] || {}
  2120. chessinstances[installchoices.instanceName][installchoices.node_env || clioverrides.node_env] = installchoices
  2121. }
  2122. catch(e){
  2123. console.warn( 'Install choices not found. WIll prompt for choices' ) // This is not an error. A new fresh instance is probably being setup.
  2124. throw 'PROMPT FOR INSTLL CHOICES TO BE IMPLEMENTED'
  2125. chessinstances[installchoices.instanceName] = chessinstances[installchoices.instanceName] || {}
  2126. chessinstances[installchoices.instanceName][installchoices.node_env || clioverrides.node_env] = installchoices
  2127. }
  2128. }
  2129. // PB : chessinstances.js update if we are switching repo servers, username etc... Myabe always refresh on each run.
  2130. // root location for instance swithc ?? should not be allowd...
  2131. var selectedInstanceName = chessinstances[clioverrides.instanceName || chessinstances.current_run.instanceName];
  2132. var instance = selectedInstanceName ? selectedInstanceName[clioverrides.node_env || (selectedinstance && selectedinstance.node_env) || [chessinstances.current_run.node_env] ]
  2133. : clioverrides
  2134. // PB : TODO -- Handle instance not found cases. and prompt cases..
  2135. // PB : TODO -- Embed defaults in the build instead of inlining here...
  2136. var __default = {
  2137. // Common baseline repos for all chess chessinstances.
  2138. repos : [
  2139. { repo : 'ember-masonry-grid' /*, branch : master*/ } // Default need not be specified.
  2140. , { repo : 'bbhverse' }
  2141. , { repo : 'clientverse' }
  2142. , { repo : 'serververse' }
  2143. , { repo : 'elxr' }
  2144. , { repo : 'ember-searchable-select' }
  2145. , { repo : 'loopback-component-jsonapi' }
  2146. , { repo : 'loopback-jsonapi-model-serializer' }
  2147. , { repo : 'loopback-connector-mysql' }
  2148. , { repo : 'loopback-connector-ds' }
  2149. , { repo : 'ember-service-worker' }
  2150. , { repo : 'ember-service-worker-asset-cache' }
  2151. , { repo : 'ember-service-worker-cache-fallback' }
  2152. , { repo : 'ember-service-worker-index' }
  2153. , { repo : 'ember-sw-client-route' }
  2154. , { repo : 'global-this' }
  2155. ]
  2156. // Requires elevation only in windows
  2157. , elevated : [ { repo : 'chess-server-lib', requiresElevation : true } ]
  2158. , exludeMergeRepos : { }
  2159. }; // PB : TODO -- Use initialized instance instead of __default everywhere.
  2160. // PB : TODO -- All these values instanceName, node_env, username, reposervers should come from instace overridden by a finalized cliovrrides...
  2161. // Also attepmt to load preconfig specially for new chessinstances from ../chess-config/...
  2162. var __repo_manifest_elxr = loadmanifest( instance.root + '/elxr'
  2163. , { utils, username : instance.username /** ??? TODO */ , instanceName : instance.instanceName /** ??? TODO */
  2164. , node_env : clioverrides.node_env, reposerver : instance.instanceName /** ??? TODO */ } // options
  2165. )
  2166. if(__repo_manifest_elxr.error) console.log(__repo_manifest_elxr.e.message)
  2167. var instance_specific_config_manifest = loadmanifest( instance.root + `/${instance.instanceName}-config-${clioverrides.node_env}`
  2168. , { utils, username : instance.username /** ??? TODO */ , instanceName : instance.instanceName /** ??? TODO */
  2169. , node_env : clioverrides.node_env, reposerver : instance.instanceName /** ??? TODO */ } // options
  2170. )
  2171. if(instance_specific_config_manifest.error) console.log(instance_specific_config_manifest.e.message)
  2172. delete __repo_manifest_elxr.error
  2173. delete __repo_manifest_elxr.e
  2174. delete __repo_manifest_elxr.utils
  2175. delete instance_specific_config_manifest.error
  2176. delete instance_specific_config_manifest.e
  2177. delete instance_specific_config_manifest.utils
  2178. // selectedinstance is not complete until we load in the following order of priority...
  2179. // 1) inline defaults
  2180. // 2) elxr defaults & manifest
  2181. // 3) ../chess-config/... defaults TODO
  2182. // 4) local cached lastrun or cli selected instance from chessinstances
  2183. // 5) instance specific manifest from {{instanceName}}-config-{{node_env}} ( can work with stale or on demand currently pulled updated version )
  2184. // 5.5) runconfig ??? lastrun vs fixed runconfig for repetitive stuff. TODO -- runconfig overrides lastrun...
  2185. // 6) cli overrides from command promnt
  2186. // 7) promted selections and reconfirms.
  2187. var __pvt = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  2188. , __default, __repo_manifest_elxr, instance
  2189. , { root : ENV.wd, node_env : ENV.NODE_ENV
  2190. , get instanceName() {
  2191. // FInalize to prevent subsequent overrides...
  2192. return instance.instanceName
  2193. }
  2194. }
  2195. , instance_specific_config_manifest
  2196. , clioverrides
  2197. )
  2198. // Unmergable server overrides
  2199. Object.keys(instance_specific_config_manifest).forEach( key => {
  2200. __pvt[key] = instance_specific_config_manifest[key]
  2201. })
  2202. var __pub = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }, {}, __pvt
  2203. // Finalized immutables.
  2204. // We don't need pub to prevent immutability.
  2205. , { get root(){ return __pvt.root }
  2206. , get node_env(){ return __pvt.node_env }
  2207. , get instanceName() { return __pvt.instanceName }
  2208. , get reposindexed(){
  2209. // PB : TODO -- Implement -- One time gettor and then cached...
  2210. var indexed = {}
  2211. this.repos.forEach(r => { indexed[r.repo] = r })
  2212. this.elevated.forEach(r => { indexed[r.repo] = r })
  2213. Object.defineProperty(this, 'reposindexed', { value: indexed, writable: false });
  2214. return indexed;
  2215. }
  2216. , set root(val){
  2217. throw 'root changes not yet supported'
  2218. // if the root changes while we r invoked from somewhere else... we need to reload everything from that location...
  2219. if(__pvt.root === val){
  2220. return __pvt.root = val
  2221. }
  2222. else __pvt.root
  2223. }
  2224. }
  2225. )
  2226. chessinstances[__pub.instanceName] = chessinstances[__pub.instanceName] || {}
  2227. chessinstances[__pub.instanceName][__pub.instanceType] = __pub
  2228. cacheWriteInstanceConfig(chessinstances, __pub.root, __pub )
  2229. Object.defineProperty(__g, 'selectedinstance', {
  2230. get(){ return __pub}
  2231. , set( inst ){ __pvt = inst; return __pub }
  2232. })
  2233. return __pub;
  2234. })()
  2235. var __default = selectedinstance; // PB : TODO -- Eliminate __default references.
  2236. // console.log(selectedinstance)
  2237. // initinstances(selectedinstance)
  2238. var any = utils.any;
  2239. var Tasq = utils.Tasq
  2240. var statuslog = utils.Traq
  2241. var Traq = utils.Traq
  2242. Tasq.addlistener(statuslog.statuslog)
  2243. // Instead of waiting for the root to be establised we start working at the current locatoin and then relocate when root changes.
  2244. var runlogjson = `${selectedinstance.root}/.elxr/run-${runtimestamp}/run.log`
  2245. ensureDirectoryExistence(runlogjson)
  2246. fs.writeFileSync(runlogjson, JSON.stringify( { message : `Started ${runtimestamp}`, success:true})) // Initialize a new log file with "logrotate" for every run
  2247. Tasq.addlistener((e)=>{ fs.writeFileSync(runlogjson, ', ' + JSON.stringify( e ), { 'flag': 'a+' }) })
  2248. var cli = require('./cliverse')
  2249. var nodeShellExec = cli.nodeShellExec;
  2250. var chalk = require('chalk')
  2251. const homedir = require('os').homedir();
  2252. function sysAddPathVar(addpath){
  2253. // Object.assign({
  2254. // inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  2255. // }, options)
  2256. // powershell $env:Path -split ';'
  2257. var etask = ()=>{
  2258. return nodeShellExec('Powershell.exe', [
  2259. `$path = [Environment]::GetEnvironmentVariable('PATH', 'Machine')
  2260. $newpath = $path + ';${addpath}'
  2261. [Environment]::SetEnvironmentVariable("PATH", $newpath, 'Machine')`
  2262. ]).then(() => {
  2263. fs.writeFileSync('run.done', 'success') // PB : TODO -- IPC through files is needed only for windows.
  2264. }).catch(() => {
  2265. fs.writeFileSync('run.done', 'error')
  2266. })
  2267. }
  2268. etask.statuslog = statuslog
  2269. etask.selectedinstance = selectedinstance
  2270. etask.processedArgs = processedArgs
  2271. etask.runtimestamp = runtimestamp
  2272. etask.ENV = ENV
  2273. return shell_verse.runElevated(etask)
  2274. // var newpath = addpath.split(';');
  2275. // newpath.push(addpath)
  2276. // newpath = Array.from(new Set(newpath)).join(';')
  2277. // // addpath.split(';').forEach(pel => { var kv = pel.split('='); kv[0] === key ? null : newpath.push(pel); } )
  2278. // // setx /M PATH "%PATH%;<path-to-executable-folder>"
  2279. // // %AppData%\npm
  2280. // return nodeShellExec('setx', ['/m', 'PATH', `%PATH%;${addpath}` ]);
  2281. }
  2282. // singleton one time lazy
  2283. var getCredentials = function(){
  2284. // try {
  2285. // First call
  2286. var creds = fs.readFileSync(path.normalize(`${homedir}/.elxrcredentials`), { encoding: 'utf8' });
  2287. var creds = creds.split('\n').map( c => c.trim() && new URL(c));
  2288. console.log(creds);
  2289. creds.forEach(cred => {console.log( cred.hostname ); console.log( cred.username )} );
  2290. // }
  2291. // catch(e){
  2292. // console.warn('Credentials not cached. You will be prompted for username and password.')
  2293. // }
  2294. // Subsequent calls
  2295. getCredentials = ()=>{ return creds }
  2296. return getCredentials();
  2297. }
  2298. // console.dir(processedArgs)
  2299. // PB : TODO -- defaults for valuless arguments if passed.
  2300. // Object.keys(processedArgs).forEach(a=>{
  2301. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  2302. // }
  2303. // })
  2304. const { readdir } = require("fs").promises
  2305. // Directory shallow walk and do perform on each dir.
  2306. const dirs = async (perform, src, target, options) => {
  2307. var rs = []
  2308. for (const dir of await readdir(src || selectedinstance.root, { withFileTypes: true })) {
  2309. if (dir.isDirectory()) rs.push( perform(dir, src, target, options) )
  2310. }
  2311. return any(rs)
  2312. }
  2313. var fsMove = async function(from, to, options) {
  2314. if(!options?.innernode) {
  2315. var exists = fs.existsSync(from);
  2316. var stats = exists && fs.statSync(from);
  2317. var isDirectory = exists && stats.isDirectory();
  2318. }
  2319. else {
  2320. var isDirectory = options.innernode.isDirectory()
  2321. }
  2322. if(!isDirectory) return fs.renameSync(from, to)
  2323. fs.mkdirSync(to, { recursive : true })
  2324. var rs = [];
  2325. for (const innernode of await readdir(from, { withFileTypes: true })) {
  2326. rs.push( fsMove( path.join(from, innernode.name), path.join(to, innernode.name), { innernode } ) )
  2327. }
  2328. return any(rs)
  2329. };
  2330. // PB : TODO -- Should return a bunch of promises to wait for...
  2331. var copyrecursive = async function(src, target, options) {
  2332. if(!options?.innernode) {
  2333. var exists = fs.existsSync(src);
  2334. var stats = exists && fs.statSync(src);
  2335. var isDirectory = exists && stats.isDirectory();
  2336. }
  2337. else {
  2338. var isDirectory = options.innernode.isDirectory()
  2339. }
  2340. if(!isDirectory) return fs.copyFileSync(src, target)
  2341. fs.mkdirSync(target, { recursive : true })
  2342. var rs = [];
  2343. for (const innernode of await readdir(src, { withFileTypes: true })) {
  2344. rs.push( copyrecursive( path.join(src, innernode.name), path.join(target, innernode.name), { innernode } )
  2345. // .then(()=>{
  2346. // return any(actions.map( a => ()=>a(dir, { isDirectory : true}) ))
  2347. // })
  2348. )
  2349. }
  2350. return any(rs)
  2351. // return fswalk( src, {}, [
  2352. // (src, options)=> {
  2353. // if(options.innernode.isDirectory()) fs.mkdirSync(options.target, { recursive : true })
  2354. // else fs.copyFileSync(src, options.target)
  2355. // }
  2356. // ])
  2357. // var exists = fs.existsSync(src);
  2358. // var stats = exists && fs.statSync(src);
  2359. // var isDirectory = exists && stats.isDirectory();
  2360. // if (isDirectory) {
  2361. // fs.mkdirSync(dest, { recursive : true });
  2362. // return dirs( function(childItemName) {
  2363. // return copyrecursive(path.join(src, childItemName.name),
  2364. // path.join(dest, childItemName.name));
  2365. // }, src )
  2366. // } else {
  2367. // fs.copyFileSync(src, dest);
  2368. // }
  2369. };
  2370. // var renamerecursive = function(from, to){
  2371. // var exists = fs.existsSync(from);
  2372. // var stats = exists && fs.statSync(from);
  2373. // var isDirectory = exists && stats.isDirectory();
  2374. // if (isDirectory) {
  2375. // fs.mkdirSync(to);
  2376. // dirs( function(childItemName) {
  2377. // renamerecursive(path.join(from, childItemName),
  2378. // path.join(to, childItemName));
  2379. // }, from )
  2380. // // fs.readdirSync(from).forEach(function(childItemName) {
  2381. // // copyrecursive(path.join(from, childItemName),
  2382. // // path.join(to, childItemName));
  2383. // // });
  2384. // } else {
  2385. // fsrename(from, to);
  2386. // }
  2387. // }
  2388. var regexreplaceall = function(content, ps){
  2389. var repmatches
  2390. var replaced = content;
  2391. while (repmatches = ps.strOrregexp.exec(content)) {
  2392. if(content.length > 0) {
  2393. var replacement = repmatches[0]
  2394. for(var m = 1; m < repmatches.length; m++) {
  2395. replacement = replacement.replace(repmatches[m], ps.substitutes[m-1])
  2396. }
  2397. replaced = replaced.replace( repmatches[0], replacement )
  2398. }
  2399. }
  2400. return replaced
  2401. }
  2402. // filesystem walk
  2403. const fswalk = async (pathToWalk, options, actions) => {
  2404. // options = options || { depthfirst : true }
  2405. if(!options.innernode) {
  2406. var exists = fs.existsSync(pathToWalk);
  2407. var stats = exists && fs.statSync(pathToWalk);
  2408. var isDirectory = exists && stats.isDirectory();
  2409. }
  2410. else {
  2411. var isDirectory = options.innernode.isDirectory()
  2412. }
  2413. if(!isDirectory) return any(actions.map( a => ()=>a( pathToWalk, utils.assign({}, options
  2414. , { pathToWalk, innernode : options.innernode || { isDirectory : function(){ return true } } }) ) ))
  2415. var rs = [];
  2416. for (const innernode of await readdir(pathToWalk, { withFileTypes: true })) {
  2417. rs.push( fswalk( path.join(pathToWalk, innernode.name), utils.assign({}, options, {pathToWalk, innernode }), actions )
  2418. // .then(()=>{
  2419. // return any(actions.map( a => ()=>a(innernode, { isDirectory : true}) ))
  2420. // })
  2421. )
  2422. }
  2423. // Wait for the walk to complete before renaming directories.
  2424. Array.prototype.push.apply(rs, actions.map( a => ()=>a( pathToWalk, utils.assign({}, options
  2425. , { pathToWalk, innernode : options.innernode || { isDirectory : function(){ return true } } } ) ) ))
  2426. return any(rs)
  2427. }
  2428. var fsrecurse = function(target, options, actions, root) {
  2429. var exists = fs.existsSync(target);
  2430. var stats = exists && fs.statSync(target);
  2431. var isDirectory = exists && stats.isDirectory();
  2432. if (isDirectory) {
  2433. var tasks = []
  2434. tasks.push( dirs( function(childItemName) {
  2435. return fsrecurse(path.join(target, childItemName.name)
  2436. , options, actions, root);
  2437. }, target ))
  2438. return any(tasks)
  2439. } else {
  2440. var prevActionResult = null;
  2441. return any( actions.map( (action) => prevActionResult = action.apply(null, target, options) ))
  2442. }
  2443. };
  2444. // var fslink = function(to, options){ try { fs.linkSync( to, options.from ) } catch(e) { throw e } }
  2445. var fslink = function(to, options){ fs.symlinkSync( to, options.from /*, type = "junction"*/ ) }
  2446. var fsrename = function(target, options){
  2447. // PB : TODO -- streaming and async.. target could be a stream a string or a filesystem item or a tree node...
  2448. var targetname = options.innernode?.name || path.parse(target).base;
  2449. var replaced = targetname;
  2450. options.patternsubstitutions.forEach( ps => { replaced = regexreplaceall( replaced, ps ) })
  2451. if(replaced && replaced !== targetname) {
  2452. var tr = target.replace( targetname, replaced )
  2453. fs.renameSync(target, tr)
  2454. return tr;
  2455. }
  2456. else return replaced
  2457. }
  2458. var fscontentreplace = function( target, options ){
  2459. // do many replacements in one shot in the file.
  2460. if(options.processingtype === 'inplace' && options.sourcetype === 'filesystem' && !options.innernode.isDirectory() ) {
  2461. var content = fs.readFileSync(target, { encoding: 'utf8' }) // PB : TODO -- streaming and async..
  2462. options.patternsubstitutions.forEach( ps => { content = regexreplaceall( content, ps ) })
  2463. fs.writeFileSync(target, content)
  2464. }
  2465. }
  2466. var templatelink = function(target, options){
  2467. var targetSubPath = target.replace(options.workingtarget + '/', '' );
  2468. var targetSubPathsplit = targetSubPath.split("/")
  2469. var targetPathBaseDir = `${targetSubPathsplit[0]}/${targetSubPathsplit[1]}`
  2470. var linkToSubPathReplacement = `${options.base}-server-lib/common`
  2471. // var rgxp = new RegExp(`(__link__)${options.base}-server-lib`, "g")
  2472. var rgxp = new RegExp(`(__link__${options.base}-server-lib)`, "g")
  2473. var linkToSubPath = targetSubPath
  2474. var b = target.match(rgxp)
  2475. var linkFromName = regexreplaceall( target, { strOrregexp : rgxp, substitutes : [ '' ] } )
  2476. linkFromName = linkFromName.replace(options.workingtarget, options.destinationroot)
  2477. if( b ) {
  2478. // Only if the pattern matches which is link instruction.
  2479. linkToSubPath = regexreplaceall( linkToSubPath, { strOrregexp : rgxp, substitutes : [ '' ] } )
  2480. }
  2481. options.patternsubstitutions.forEach( ps => { linkToSubPath = regexreplaceall( linkToSubPath, ps ) })
  2482. var linkToName = `${options.destinationroot}/${linkToSubPath}`
  2483. if(b){
  2484. linkToSubPath = linkToSubPath.replace( targetPathBaseDir, linkToSubPathReplacement)
  2485. // PB : DONT DELETE EVERYTHING ??? Only the linkable ones... Or use an add strategy without deleting...
  2486. fs.unlinkSync( target );
  2487. fslink( `${options.destinationroot}/${linkToSubPath}`, { from : linkFromName } )
  2488. }
  2489. else {
  2490. fsMove( `${options.workingtarget}/${linkToSubPath}`, linkToName )
  2491. // fsMove( `${options.workingtarget}/${linkToSubPath}`, linkFromName )
  2492. }
  2493. }
  2494. // Source and Target are files or folders. We need another version or a unifed version for strings..
  2495. var processpatterns = function(target, options){
  2496. // Accept a set of patterns and substitutions and operate on a target and apply all patterns substitutions.
  2497. // options = options || { targettype : 'inplace', sourcetype : 'filesystem' }
  2498. // options.source, options.target sourcetype = 'string' | 'filesystem' options.targettype = 'inplace' | 'copy'
  2499. if(options.processingtype === 'inplace' && options.sourcetype === 'filesystem' ) {
  2500. options.patternsubstitutions.forEach( ps => {
  2501. // var replacement = regexreplaceall( from, ps.strOrregexp, ps.substitutes )
  2502. // if(targetname) { // Porcess all files. Even if file names dont have patterns the content needs to be replaced.
  2503. return options.tasks.map( t => { return t( target, ps ) } )
  2504. // }
  2505. // return str.replace(regex, function(match, key) {
  2506. // console.log(`Found match, group ${match}: ${key}`);
  2507. // return substitutes[key] || match;
  2508. // })
  2509. })
  2510. }
  2511. // while ((m = regex.exec(str)) !== null) {
  2512. // // This is necessary to avoid infinite loops with zero-width matches
  2513. // if (m.index === regex.lastIndex) {
  2514. // regex.lastIndex++;
  2515. // }
  2516. // var rstr = str;
  2517. // // The result can be accessed through the `m`-variable.
  2518. // m.forEach((match, groupIndex) => {
  2519. // // rstr = rstr.replace( groupIndex
  2520. // console.log(`Found match, group ${groupIndex}: ${match}`);
  2521. // if(groupIndex === 0) return
  2522. // });
  2523. // }
  2524. }
  2525. function copyFileSync( source, target , options) {
  2526. var targetFile = target;
  2527. // If target is a directory, a new file with the same name will be created
  2528. if ( fs.existsSync( target ) ) {
  2529. if ( fs.lstatSync( target ).isDirectory() ) {
  2530. targetFile = path.join( target, path.basename( source ) );
  2531. }
  2532. }
  2533. fs.writeFileSync(targetFile, fs.readFileSync(source));
  2534. }
  2535. function copyFolderRecursiveSync( source, target, options ) {
  2536. var files = [];
  2537. // Check if folder needs to be created or integrated
  2538. var targetFolder = path.join( target, path.basename( source ) );
  2539. if ( !fs.existsSync( targetFolder ) ) {
  2540. fs.mkdirSync( targetFolder );
  2541. }
  2542. // Copy
  2543. if ( fs.lstatSync( source ).isDirectory() ) {
  2544. files = fs.readdirSync( source );
  2545. files.forEach( function ( file ) {
  2546. var curSource = path.join( source, file );
  2547. if ( fs.lstatSync( curSource ).isDirectory() ) {
  2548. copyFolderRecursiveSync( curSource, targetFolder );
  2549. } else {
  2550. copyFileSync( curSource, targetFolder );
  2551. }
  2552. } );
  2553. }
  2554. }
  2555. var getShellTask = (command, args, options) => {
  2556. options = options || {}
  2557. var callshell = command === 'rm' ? getgitbashtask : getshelltask;
  2558. return () => {
  2559. var p = callshell( [command, args, Object.assign({
  2560. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  2561. }, options)
  2562. ])()
  2563. if (options.ignorefailures) {
  2564. return p.catch(e => {
  2565. // Ignore. Not a major error.
  2566. })
  2567. }
  2568. else return p;
  2569. }
  2570. }
  2571. var callshelltask = (args) => {
  2572. // console.dir(args)
  2573. if( Object.prototype.toString.call(args) === '[object Function]' ) {
  2574. return args;
  2575. }
  2576. return getshelltask(args)()
  2577. }
  2578. var getCmdString = function(args){ return `"${args[0]} ${args[1].join(' ')}"` }
  2579. var getshelltask = (args) => {
  2580. return args[0] === 'rm' ? getgitbashtask(args) : () => {
  2581. return nodeShellExec.apply(null, args).catch(function(e){
  2582. e.benign = args[2].benign;
  2583. if(!e.benign) { console.error(e); }
  2584. throw e
  2585. })
  2586. }
  2587. }
  2588. var getgitbashtask = (args, onEachError) => { return () => {
  2589. return nodeShellExec( `"${gitbash}"`, ['-c', getCmdString(args)], args[2]).catch( onEachError || function(e){ console.error(e) }) }
  2590. }
  2591. var getnodeshellexectask = (args) => { return () => { return nodeShellExec.apply(null, args) }}
  2592. var perform = function( serailtasks, taskvector ){ return any( serailtasks(taskvector).map(getnodeshellexectask)) }
  2593. var getTaskCheckExists = shell_verse.getTaskCheckExists
  2594. // var getTaskWithElevation = function(tasdef){ return shell_verse.getElevatedTask( tasdef.elevatedpulltasks ) }
  2595. // var getTaskWithoutElevation = function(tasdef){
  2596. // return ()=>{
  2597. // if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  2598. // else Promise.resolve(true)
  2599. // }
  2600. // }
  2601. var gitops = {
  2602. getdiscoverbranchcmd : function(repo){
  2603. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  2604. var cmd = [gitbash
  2605. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  2606. , { cwd: instanceroot + '/' + repo, title: 'discoverbranch for ' + repo + ' ' + parameters.join(' ') }]
  2607. return cmd
  2608. }
  2609. }
  2610. var getPullCmd = (repodef, branch) => {
  2611. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  2612. // console.log(useGitPull)
  2613. var repo = repodef.repo
  2614. var pullCmd = []
  2615. if(!branch) {
  2616. // console.warn('No branch was specified detecting from working client.')
  2617. // First check if working client exists.
  2618. // if (existsSync(instanceroot + '/' + repo)) {
  2619. pullCmd= gitops.getdiscoverbranchcmd(repo)
  2620. // }
  2621. // else performpull
  2622. }
  2623. // var pullCmd = [gitInstallDir
  2624. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  2625. // , { cwd: instanceroot + '/' + repo, title: 'pull all remotes for ' + repo }]
  2626. if(branch) {
  2627. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  2628. var pullCmd = [ gitbash
  2629. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  2630. , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  2631. }
  2632. // var pullCmd = ['pullall', [], { cwd : repo }]
  2633. if (useGitPull) pullCmd = ['git', ['pull'], {
  2634. inherit: true, shell: true,
  2635. cwd: instanceroot + '/' + repo
  2636. // , env: ENV
  2637. , runas: processedArgs.runas
  2638. , title: `git pull ${repo}`
  2639. }]
  2640. return pullCmd
  2641. }
  2642. // PB : TODO -- Use queueing with async tasks..
  2643. var performPull = (repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch) => {
  2644. var __inelevatedBatch = elevatedBatch, __inregularBatch = regularBatch;
  2645. var pT = getPullTask(repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch)
  2646. // var waitForBatchAdditions = function(){
  2647. // return pT;
  2648. // }
  2649. // Execute is implied.
  2650. // if(false && (__inelevatedBatch || __inregularBatch) ) return waitForBatchAdditions() // PB : Todo Implemnt a trigger which starts execution.
  2651. // else
  2652. return pT() // Execute it.
  2653. }
  2654. var getPullTask = (repodef, branch, repoowner, errHandler, elevatedBatch, regularBatch) => {
  2655. // PB : TODO -- Handle no branch passed in case.
  2656. // if(!branch) { throw 'No branch specified' }
  2657. var repo = repodef.repo;
  2658. elevatedBatch = elevatedBatch || [];
  2659. regularBatch = regularBatch || [];
  2660. try{
  2661. // PB : TODO -- local repo folder named the same as the remote repository name is not enough to establish existence.
  2662. // This remote repo and branch may have been or may need to be added as a local tracking branch
  2663. // to any other local repo folder (with a different name)
  2664. var exists = existsSync(instanceroot + '/' + repo)
  2665. }
  2666. catch(e){
  2667. exists = false
  2668. console.log(e)
  2669. }
  2670. function initTask(etask){
  2671. etask.info = { repo }
  2672. etask.errHandler = errHandler
  2673. etask.statuslog = statuslog
  2674. etask.processedArgs = processedArgs
  2675. etask.selectedinstance = selectedinstance
  2676. etask.runtimestamp = runtimestamp
  2677. etask.ENV = ENV
  2678. }
  2679. function initElevatedBatch(){
  2680. elevatedBatch.info = { repo }
  2681. elevatedBatch.errHandler = errHandler
  2682. elevatedBatch.statuslog = statuslog
  2683. elevatedBatch.processedArgs = processedArgs
  2684. elevatedBatch.selectedinstance = selectedinstance
  2685. elevatedBatch.runtimestamp = runtimestamp
  2686. elevatedBatch.ENV = ENV
  2687. }
  2688. if (exists) {
  2689. var tasks = [];
  2690. return (()=>{
  2691. // 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.
  2692. if(selectedinstance.addremotes) {
  2693. return op['get-remotes']({repo}).then(( remotes )=>{
  2694. return op['get-upstream']({repo, remotes}).then(( upstream ) => {
  2695. return __addremotesandpull({ upstream, remotes})
  2696. })
  2697. })
  2698. }
  2699. else return __pull();
  2700. })()
  2701. function __pull(){
  2702. var branchprint = branch ? ' branch :' + branch : '';
  2703. var task = ()=>{
  2704. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  2705. return any(tasks).then( ()=>{
  2706. return nodeShellExec.apply(null, getPullCmd(repodef, branch)).then(() => {
  2707. return true;
  2708. })
  2709. })
  2710. }
  2711. initTask(task)
  2712. if(repodef.requiresElevation) {
  2713. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  2714. 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
  2715. else initTask(elevatedBatch[elevatedBatch.length-1])
  2716. return elevatedBatch[elevatedBatch.length-1]
  2717. }
  2718. else {
  2719. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  2720. return regularBatch[regularBatch.length-1]
  2721. }
  2722. }
  2723. function __addremotesandpull(options){
  2724. // Add the remotes
  2725. var tasks = []
  2726. // selectedinstance.selectedremotes are optional and need not be enforced to be chosen. The selection for hte selected remotes
  2727. // could also be derived from a crossfilter of remote-type selected for this run and the current chosen and operating reposervers.
  2728. var selectedremotes = Array.from( new Set(selectedinstance.selectedremotes.concat(Object.keys(repodef.remotes || {}))));
  2729. if(selectedremotes.length > 0) var selectedremoteFilter = function(rs) { return selectedremotes.find( rs.server ) }
  2730. else var selectedremoteFilter = function(){ return true }
  2731. var repoRemotes = Object.assign( {}, selectedinstance.remotes, options.remotes, options.upstream, repodef.remotes );
  2732. // We need a most permissive filtered list to use as an efficient starting point to further reduce to whats actually needed.
  2733. // 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.
  2734. Object.keys(repoRemotes).forEach((remotename)=>{
  2735. // PB : TODO -- ai prefix for all apis that require an answer amongst many choices.
  2736. var ai_RemoteAddNeeded = (r)=>{
  2737. if(r.server === reposerver && selectedremoteFilter() && r.accessibility.find( selectedinstance[ 'remote-type' ] )){ // currently chosen remotetype...
  2738. var exists = false;
  2739. if(exists = (options.remotes[r.remotename] || Object.keys(options.remotes).find( lrn => {
  2740. var exists = options.remotes[lrn].server === r.server && !options.remotes[r.remotename]
  2741. if(exists) console.warn('Found duplicate remote with a different name for the same server...')
  2742. return exists
  2743. } )) ) {
  2744. return false // Already a remote not required.
  2745. }
  2746. return true // PB : TODO -- Sort and display highest priority target.remotes.sort( )
  2747. }
  2748. return false
  2749. };
  2750. tasks.push(
  2751. ()=>{
  2752. return op['remote exists']({
  2753. remotename, repo, benign : true, ignorefailures : true
  2754. , url : repoRemotes[remotename].url + repo
  2755. , branch : checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  2756. }).then( (r) => {
  2757. if(!r[1]) return false; // PB : TODO -- Not accessible skip for now probably should remove.
  2758. else if(r[0]) return true; // Already added nothing to do
  2759. else if(ai_RemoteAddNeeded( repoRemotes[remotename] )) return op['remote add']( { remotename,
  2760. 'set-upstream' : (selectedinstance['upstream'] || `${remotename}/${branch}`) // ??? when url accessible... in order of highest priority
  2761. , reponame : repo
  2762. , url : repoRemotes[remotename].url , branch : checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  2763. })
  2764. // else skipped as remote is not relevant for this repo...
  2765. })
  2766. }
  2767. )
  2768. })
  2769. __pull()
  2770. }
  2771. }
  2772. else {
  2773. // PB : TODO -- detect if a clonable repo exists within the context of currentGitAuthUser on remote reposerver...
  2774. console.log('cloning ' + repo)
  2775. // PB : TODO -- add additional remotes after cloning and pull again...
  2776. var task = ()=>{
  2777. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${repodef.owner || repoowner || defaultRepoOwner}/` + repo + '.git'],
  2778. {
  2779. inherit: true, shell: true,
  2780. env: ENV
  2781. , cwd : instanceroot
  2782. , runas: processedArgs.runas
  2783. }).then(() => {
  2784. var task = ()=>{
  2785. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  2786. {
  2787. inherit: true, shell: true,
  2788. env: ENV
  2789. , cwd: instanceroot + '/' + repo
  2790. , runas: processedArgs.runas
  2791. , title: `'git', ${['config', '--replace-all', 'core.symlinks', selectedinstance.username].join(' ')}`
  2792. })
  2793. }
  2794. initTask(task)
  2795. if(repodef.requiresElevation) {
  2796. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  2797. return elevatedBatch[elevatedBatch.length-1]
  2798. }
  2799. else {
  2800. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  2801. return regularBatch[regularBatch.length-1]
  2802. }
  2803. })
  2804. }
  2805. initTask(task)
  2806. if(repodef.requiresElevation) {
  2807. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  2808. return elevatedBatch[elevatedBatch.length-1]
  2809. }
  2810. else {
  2811. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  2812. return regularBatch[regularBatch.length-1]
  2813. }
  2814. }
  2815. }
  2816. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current GITEA username
  2817. var defaultRepoOwner = 'chess';
  2818. var elevatedRunasRepos = null
  2819. var gitRepos = null
  2820. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  2821. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  2822. var dbForLabel = function (label) {
  2823. var dbsForLabel = {
  2824. devmysql: 'mysql'
  2825. , development: 'mssql'
  2826. , production: 'mssql'
  2827. }
  2828. return dbsForLabel[label] || 'mysql'
  2829. }
  2830. // Maps an environment to a branch. Not required if the branch is appropriately named.
  2831. var checkoutMap = { 'development': 'master' }
  2832. // SAM : TODO Use nodeshellexec where to detect git installation dir
  2833. var gitbash = shell_verse.getbash()
  2834. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  2835. // Relevant git repos
  2836. var exludeMergeRepos = [];
  2837. var useGitPull = processedArgs.useGitPull || false;
  2838. var configPromise = null
  2839. var reconfirmcmds = { create : true }
  2840. var subcommandlabels = {
  2841. switch : (`switch ${processedArgs._[1] || ''}`).trim()
  2842. }
  2843. var independentcmd = function(){
  2844. return false;
  2845. }
  2846. var util = require('util');
  2847. var cliname = 'elxr';
  2848. var ver = '1.1';
  2849. var readme = `
  2850. Command syntax examples
  2851. elxr
  2852. Displays help. Same as elxr h
  2853. elxr i
  2854. Runs interactive propmts to help choose installation options.
  2855. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  2856. General command syntax.
  2857. Eg: NODE_ENV=development elxr pull elixir
  2858. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  2859. The specific cmd defines what the value is interpreted as.
  2860. There are several cmds that do not require an {{instancename}} parameter.
  2861. Eg: elxr remote remove origin
  2862. Git operations or passthrough external commands on all repository folders in you working directory.
  2863. Main objectives.
  2864. elxr cli is a wrapper around other shell commands and api based operations.
  2865. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  2866. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  2867. `;
  2868. var help = `
  2869. ${readme}
  2870. # list of commands... please refer dveloper documentation for ${cliname}
  2871. \r\n\t${
  2872. Object.keys(op).join('\r\n\t')
  2873. }
  2874. `;
  2875. var elxr = {
  2876. help() {
  2877. return chalk.cyanBright(`
  2878. -------------------------------------------------------------------------------
  2879. *** BBH Elixir ***
  2880. -------------------------------------------------------------------------------
  2881. elxr ${ver}
  2882. A cli tool for chess
  2883. ${help}
  2884. -------------------------------------------------------------------------------
  2885. `)
  2886. }
  2887. , info() {
  2888. return chalk.cyanBright(`
  2889. -------------------------------------------------------------------------------
  2890. *** BBH Elixir ***
  2891. -------------------------------------------------------------------------------
  2892. elxr ${ver}
  2893. A cli tool for chess
  2894. -------------------------------------------------------------------------------
  2895. `)
  2896. }
  2897. , getpulltask(args){
  2898. // def can be an instance config
  2899. // Or an object with many repos and elevated repos
  2900. // Or a single repo ( Either Elevated or normal. )
  2901. // USAGE
  2902. // elxr pull elixir origin master
  2903. // elxr pull
  2904. // not all remote branches are setup to be tracked locally (respective remotes and branches).
  2905. // pull --all is useless. As it fetches all remotes and branches but only merges current branch.
  2906. // apart from remote tracking branches We are interested in pulling from all remotes and relavant branches.
  2907. // The branch pipline should feed back to master
  2908. // master -> test -> stage -> release[nnnn] -> production
  2909. // (master) <= git merge [all remotes] production && git merge [all remotes] release[nnnn]
  2910. // git merge [all remotes] stage && git merge [all remotes] test && git merge [all remotes] master
  2911. var __args = {
  2912. remotename : args.remotename|| processedArgs._[2]
  2913. , url : args.url || processedArgs._[3]
  2914. , branch : args.branch || processedArgs._[4] // If branch not specified opearte on the current branch of each working directorys
  2915. }
  2916. // var commands = [
  2917. // // ['git', ['checkout', __args.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]]
  2918. // ,
  2919. // ]
  2920. // var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  2921. // var pullCmd = [ gitbash
  2922. // , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  2923. // , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  2924. var def = args || {
  2925. repos : selectedinstance.repos,
  2926. elevated : selectedinstance.elevated
  2927. }
  2928. var elevatedpulltasks = null;
  2929. if(def.repo) {
  2930. // Single repo case.
  2931. if(def.repo.requiresElevation) {
  2932. var t1 = function() {
  2933. return performPull(def).then(() => {
  2934. return true;
  2935. }).catch((e) => {
  2936. console.error(e)
  2937. }).finally(Traq.finally)
  2938. }
  2939. t1.statuslog = statuslog
  2940. t1.selectedinstance = selectedinstance
  2941. t1.processedArgs = processedArgs
  2942. elevatedpulltasks = shell_verse.getElevatedTask( t1 )
  2943. }
  2944. else {
  2945. var t2 = function(){
  2946. return performPull(def).then(() => {
  2947. console.log('pulled ' + JSON.stringify(def.repo))
  2948. return true;
  2949. }).catch((e) => {
  2950. console.error(e)
  2951. }).finally(Traq.finally)
  2952. }
  2953. t2.statuslog = statuslog
  2954. var regularpulltasks = shell_verse.getNonElevatedTask( t2 )
  2955. }
  2956. if(elevatedpulltasks) return elevatedpulltasks //getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  2957. else return regularpulltasks // getTaskWithoutElevation({ regularpulltasks})
  2958. }
  2959. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  2960. console.dir(def)
  2961. console.log('Running exlr pull : ' + path.dirname(__dirname))
  2962. var useGitPull = processedArgs.useGitPull || false;
  2963. if(def.elevated || def.repos) {
  2964. if(def.elevated) def.requiresElevation = true;
  2965. else delete def.requiresElevation;
  2966. }
  2967. else {
  2968. if(def.requiresElevation) def.elevated = [def]
  2969. else def.repos = [def]
  2970. }
  2971. var regularpulltasks = function(){ return Promise.resolve(true) }
  2972. if(def.elevated){
  2973. elevatedpulltasks = function() {
  2974. var eBatch = []
  2975. def.elevated.map((def) => getPullTask(def, null, null, null, eBatch))
  2976. eBatch[0].processedArgs = processedArgs
  2977. return shell_verse.runElevatedBatch(eBatch).then(() => {
  2978. return true;
  2979. }).catch((e) => {
  2980. console.error(e)
  2981. })
  2982. }
  2983. elevatedpulltasks.statuslog = statuslog
  2984. }
  2985. if(def.repos) {
  2986. var regularpulltasks = function(){
  2987. var pendingpulls = [];
  2988. def.repos.forEach((def) => {
  2989. pendingpulls.push(
  2990. performPull(def).then(()=>{ console.log('pulled ' + JSON.stringify(def.repo)) })
  2991. .catch(e => { console.log(e); throw e })
  2992. )
  2993. })
  2994. return any(pendingpulls).finally(Traq.finally)
  2995. }
  2996. regularpulltasks.statuslog = statuslog
  2997. }
  2998. // if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  2999. // else return getTaskWithoutElevation({ regularpulltasks})
  3000. return elevatedpulltasks().then(()=>{
  3001. if(isWin() && isElevated) return Promise.resolve(true);
  3002. return regularpulltasks()
  3003. })
  3004. }
  3005. }
  3006. function preworkerconfig(){
  3007. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  3008. gitRepos = selectedinstance.repos
  3009. // gitRepos = ['chess-server-lib'];
  3010. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  3011. elevatedRunasRepos = selectedinstance.elevated
  3012. // Repos that should excluded from merge for releases...
  3013. exludeMergeRepos = selectedinstance.exludeMergeRepos
  3014. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  3015. // mysql -u root -p db_name < drop_all_tables.sql
  3016. var mysql = '../xampp/mysql/bin/mysql'
  3017. var mysqldump = '../xampp/mysql/bin/mysqldump'
  3018. }
  3019. // The main elxr cli process
  3020. function elxrworker() {
  3021. var __runcmd = function (label) {
  3022. var distinquishedlabel = subcommandlabels[label] || label
  3023. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  3024. }
  3025. return __runcmd(processedArgs.label || processedArgs._[0] || 'undefined');
  3026. }
  3027. // function acquireChoices(selectedinstance) {
  3028. // var hasconfig = false;
  3029. // console.warn(chalk.cyan(`
  3030. // -------------------------------------------------------------------------------
  3031. // Could not locate your preferred configuration (you may not specified it)
  3032. // You should fork the default chess configuration to customize and make it
  3033. // your own instance with a named config as
  3034. // {{yourowninstancename}}-config-{{yourchosenenvironment}}
  3035. // And then run this tool as follows
  3036. // NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  3037. // OR
  3038. // Run this tool with the following command to use a quick start default.
  3039. // elxr --default
  3040. // OR
  3041. // Choose one of the options below to run interactively.
  3042. // We will run your choice at the next prompt.
  3043. // -------------------------------------------------------------------------------
  3044. // `))
  3045. // var choices = getInteractionPoints(detectedinstanceoptions, __interactive_prompts)
  3046. // var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  3047. // return initinstances(selectedinstance)
  3048. // })
  3049. // // var prompt = cli.prompter;
  3050. // // return prompt.ask(`Choose an option :
  3051. // // d) Install the default chess instance.
  3052. // // => elxr i chess node_env=development --default
  3053. // // n) Create your custom new instance interactively
  3054. // // => elxr i {{instanceName}} node_env={{environment}}
  3055. // // i) Choose an instance and environment to install
  3056. // // => elxr i {{instanceName}} node_env={{environment}}
  3057. // // c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  3058. // // => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  3059. // // h) Help
  3060. // // q) Quit
  3061. // // Default <= d
  3062. // // : `).then((choice) => {
  3063. // // if (choice && choice === 'd' || !choice) {
  3064. // // processedArgs._[0] = 'i'
  3065. // // selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  3066. // // selectedinstance.node_env = processedArgs.node_env = (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  3067. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  3068. // // }
  3069. // // else if (choice === 'h') {
  3070. // // processedArgs._[0] = 'h'
  3071. // // fs.writeFileSync('run.done', 'noop help');
  3072. // // console.log(elxr.help()); process.exit()
  3073. // // }
  3074. // // else if (choice === 'n' || choice === 'i') {
  3075. // // var p1 = cli.prompter;
  3076. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  3077. // // processedArgs._[0] = 'i'
  3078. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  3079. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  3080. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  3081. // // if (choice === 'n') {
  3082. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  3083. // // console.warn(
  3084. // // chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  3085. // // process.exit();
  3086. // // }
  3087. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  3088. // // selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  3089. // // })
  3090. // // })
  3091. // // })
  3092. // // } else if (choice === 'c') {
  3093. // // var p1 = cli.prompter;
  3094. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  3095. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  3096. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  3097. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  3098. // // return p1.ask(`Enter cmd :
  3099. // // p) pull
  3100. // // Default <= p
  3101. // // : `).then(function (cmd) {
  3102. // // if (!cmd || cmd === 'p') {
  3103. // // processedArgs._[0] = 'pull'
  3104. // // }
  3105. // // else processedArgs._[0] = cmd
  3106. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  3107. // // selectedinstance.reposerver = reposerver || selectedinstance.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  3108. // // })
  3109. // // })
  3110. // // })
  3111. // // })
  3112. // // } else {
  3113. // // 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.`));
  3114. // // fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  3115. // // fs.writeFileSync('run.done', 'noop quit');
  3116. // // process.exit()
  3117. // // }
  3118. // // })
  3119. // }
  3120. var os = require("os");
  3121. var hostname = os.hostname();
  3122. var clustername = null; // PB : TODO -- Prompt to acquire.
  3123. var configs = (function(){
  3124. // We need to discover and use the most specialized config available.
  3125. // Two passes are required as the config currently cloned may be switched by the discovery.
  3126. // If the repo name is the same but has different remotes the newly acquired config from multiple remotes may
  3127. // iteself redefine the remotes, repos and servers for the config which we need to honor..
  3128. return {
  3129. ownerClusterNodeConfig(selected) {
  3130. // Hostname and therefore clusternodename can be anything and can participate in many clusters.
  3131. // 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 )
  3132. var clusternodename = hostname || `CHESS0001${selected.username}`; // Cluster node names need to be unique accross all clusters to avoid collitions.
  3133. clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
  3134. return __acquireConfig(selected, { remote : 'userfork' } // PB : TODO -- accessiblity state should switch to public etc..
  3135. , selected.instanceName + '-config-' + selected.node_env + `-${clusternodename}`
  3136. , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
  3137. e.benign = true
  3138. return e; }
  3139. )
  3140. }
  3141. , ownerInstnace(selected) { return __acquireConfig(selected, { remote : 'userfork' }
  3142. , selected.instanceName + '-config-' + selected.node_env
  3143. , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
  3144. e.benign = true
  3145. return e }
  3146. )
  3147. }
  3148. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  3149. , commonInstance(selected) { return __acquireConfig(selected, { repoOwner : defaultRepoOwner }
  3150. , undefined
  3151. , function(e){
  3152. // PB : TODO -- console.info('This is probably an error unless the user is asking to create a new instance with this name.')
  3153. statuslog.statuslog(e, e)
  3154. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  3155. utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  3156. , selectedinstance, require(manifestpath)( null, { utils, username : selectedinstance.username, instanceName : selectedinstance.instanceName
  3157. , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' } ))
  3158. console.dir(selectedinstance.repos)
  3159. // Config from server always override merges into selection except for the current selection.
  3160. // PB : TODO -- utils.assign Array merges are non-distinct...
  3161. if(selectedinstance?.repos && !selectedinstance.repos[0].repo) {
  3162. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  3163. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  3164. }
  3165. if(selectedinstance?.elevated && !selectedinstance.elevated[0]?.repo) {
  3166. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  3167. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  3168. }
  3169. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  3170. , selected, selectedinstance)
  3171. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  3172. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  3173. cacheWriteInstanceConfig(chessinstances, selectedinstance.root)
  3174. // ENV.NODE_ENV = selectedinstance.node_env;
  3175. throw e
  3176. }
  3177. ) }
  3178. // , genericChessInstance(selected) { return __acquireConfig(selected, { repoOwner : defaultRepoOwner }) }
  3179. }
  3180. })()
  3181. var eNotImplemented = function(){
  3182. console.error('Not yet implemented')
  3183. process.exit()
  3184. }
  3185. // PB : TODO -- accept additional arg - an array specifying custom configPriority.
  3186. var acquireConfig = function(slections){
  3187. var configPriority = [ 'ownerClusterNodeConfig', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  3188. return any(configPriority.map(cfg => { return function() { return configs[cfg](slections) } } ), true, true).then(()=>{
  3189. return acquireData(slections)
  3190. })
  3191. }
  3192. var instanceData = (function(){
  3193. return {
  3194. ownerClusterNodeData(selected) {
  3195. var clusternodename = hostname || `CHESS0001${selected.username}`; // Cluster node names need to be unique accross all clusters to avoid collitions.
  3196. clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
  3197. return __acquireData(selected, { remote : 'userfork' }
  3198. , selected.instanceName + '-data-' + selected.node_env + `-${clusternodename}`
  3199. , function(e){ console.info('Customized node level data not found. This is not an Error. Will attempt with owner level config.');
  3200. e.benign = true
  3201. return e; }
  3202. )
  3203. }
  3204. , ownerInstnace(selected) { return __acquireData(selected, { remote : 'userfork' }
  3205. , selected.instanceName + '-data-' + selected.node_env
  3206. , function(e){ console.info('Customized user level data not found. This is not an Error. Will attempt global common instance config.');
  3207. e.benign = true
  3208. return e }
  3209. )
  3210. }
  3211. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  3212. , commonInstance(selected) { return __acquireData(selected, { repoOwner : defaultRepoOwner }
  3213. // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
  3214. ) }
  3215. , genericChessInstance(selected) { return __acquireData(selected, { repoOwner : defaultRepoOwner }) }
  3216. }
  3217. })()
  3218. var acquireData = function(slections){
  3219. var configPriority = [ 'ownerClusterNodeData', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  3220. return any(configPriority.map(cfg => { return function() { return instanceData[cfg](slections) } } ), true, true)
  3221. }
  3222. function reinit(){
  3223. sysAddPathVar('%AppData%\\npm')
  3224. resetgitconfig()
  3225. }
  3226. function init(){
  3227. sysAddPathVar('%AppData%\\npm')
  3228. resetgitconfig()
  3229. }
  3230. function resetgitconfig(){
  3231. // https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage
  3232. // Git Credential storage...
  3233. // git config --global credential.helper 'store --file ~/.gitcredentials'
  3234. // git credential fill
  3235. // protocol=https
  3236. // host=git.bbh.org.in
  3237. // username=bob
  3238. // password=pppp
  3239. // git credential-store --file ~/.gitcredentials store
  3240. // // notepad C:/Program Files/Git/etc/gitconfig
  3241. // git config --edit --system
  3242. // git credential-store --file ~/git.store store
  3243. // Find system git config
  3244. // git config --global --edit
  3245. // git config --list --show-origin
  3246. // git config --list --show-origin --show-scope
  3247. // https://stackoverflow.com/questions/35942754/how-can-i-save-username-and-password-in-git
  3248. // Recipie
  3249. // git config --global --unset credentials.helper
  3250. // cd /path/to/my/repo
  3251. // git config --unset credential.helper
  3252. // git config credential.helper 'store --file ~/.git_repo_credentials'
  3253. // git config credential.*.username my_user_name
  3254. // git config credential.https://gitlab.com.username my_user_name
  3255. // git credential fill
  3256. // git config --global credential.modalprompt false // doesnst work.
  3257. // core askpass = ;;; https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows
  3258. var options = {
  3259. inherit: true, shell: true, env: ENV
  3260. , cwd: instanceroot
  3261. , runas: processedArgs.runas
  3262. }
  3263. var task = ['git', ['config'], options]
  3264. var tasklist = [
  3265. // ['--global', '--unset credentials.helper']
  3266. // ['--unset', 'credentials.helper']
  3267. // ,
  3268. // ['credential.helper', `'store --file git_repo_credentials'`]
  3269. ['--global', 'credential.helper', "'store --file ~/.git_repo_credentials'"]
  3270. , ['--global', '--replace-all', 'user.name', 'pb']
  3271. , ['--global', '--replace-all', 'user.email', 'pradeep@bbh.org.in']
  3272. // , ['--list']
  3273. // , ['credential', 'fill']
  3274. ]
  3275. var onEachError = e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n')
  3276. var shellT = (args) => { return getgitbashtask(args, onEachError)
  3277. // .catch(e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n' + tasq.toString()) )
  3278. }
  3279. execserial(tasklist, task, shellT, onEachError )
  3280. }
  3281. var createTasq = (args, shellT, onEachError) => {
  3282. var tasq = shellT ? shellT(args) : (() => { return nodeShellExec.apply(null, args).catch( onEachError || function(e){ console.error(e) } ) })
  3283. tasq.toString = function(){ return JSON.stringify(args)}
  3284. return tasq;
  3285. }
  3286. var execserial = function(tasklist, task, shellT){
  3287. var exec = (taskArgs)=>{
  3288. var thistask = task.concat();
  3289. thistask[1] = thistask[1].concat()
  3290. thistask[1].push.apply(thistask[1], taskArgs)
  3291. return createTasq(thistask, shellT)
  3292. }
  3293. return any(tasklist.map(exec))
  3294. }
  3295. var execonce = function(taskArgs, task){ return any([task[1].push.apply(task[1], taskArgs)].map(createTasq)) }
  3296. var __acquireConfig = function (selected, options, configrepo, errHandler) {
  3297. configrepo = configrepo || selected.instanceName + '-config-' + selected.node_env;
  3298. var repoOwner = options.repoOwner || selected.username || options.defaultRepoOwner
  3299. var errorHandler = (e) => {
  3300. 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`))){
  3301. // console.error('Could not connect to repo server. Timed Out')
  3302. 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 => {
  3303. if(propValue === 'y') {
  3304. reconfirm = getReconfirmAll()
  3305. return startElxr()
  3306. }
  3307. else if(propValue === 'r'){
  3308. return acquireConfig(selected)
  3309. }
  3310. else process.exit()
  3311. })
  3312. }
  3313. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${repoOwner}/${configrepo}.git/' not found`))){
  3314. var choices = {
  3315. t : `install a new temporary local instance with this name ( will not persist ).
  3316. Use your own username for additional options. You can request for a username at chess@bbh.org.in )`
  3317. , e : 'exit' }
  3318. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  3319. choices = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  3320. , {
  3321. i : 'create a new instance with this name => will fork the default config under your username'
  3322. , f : 'fork a new instance with this name for yourself for this node from another instance'
  3323. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  3324. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  3325. , p : 'create a custom config for yourself '
  3326. }, choices)
  3327. }
  3328. return cli.prompt( choices
  3329. , 'Config for instance not found. Would you like to ', 'e' ).then(propValue => {
  3330. if(propValue === 't') {
  3331. selectedinstance.local = true; return createInstance(selectedinstance)
  3332. }
  3333. if(propValue === 'i') return eNotImplemented()
  3334. if(propValue === 'f') return eNotImplemented()
  3335. if(propValue === 'o') return eNotImplemented()
  3336. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  3337. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  3338. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  3339. else process.exit()
  3340. })
  3341. }
  3342. console.warn(e)
  3343. throw e; //('Config acquisition failed.')
  3344. }
  3345. var successHandler = () => {
  3346. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  3347. utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  3348. , selectedinstance, require(manifestpath)( null, { utils, username : selectedinstance.username, instanceName : selectedinstance.instanceName
  3349. , node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver }))
  3350. console.dir(selectedinstance.repos)
  3351. // Config from server always override merges into selection except for the current selection.
  3352. // PB : TODO -- utils.assign Array merges are non-distinct...
  3353. if(!selectedinstance.repos[0].repo) {
  3354. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  3355. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  3356. }
  3357. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  3358. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  3359. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  3360. }
  3361. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  3362. , selected, selectedinstance)
  3363. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  3364. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  3365. cacheWriteInstanceConfig(chessinstances, selectedinstance.root)
  3366. ENV.NODE_ENV = selectedinstance.node_env;
  3367. }
  3368. return performPull( selected.reposindexed[configrepo] || { repo : configrepo }
  3369. , null, repoOwner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  3370. .catch( (e)=>{
  3371. // if(e){
  3372. if(Promise.resolve(e) === e) return e;
  3373. // console.error(e)
  3374. e.benign = true;
  3375. throw e; // Not a hard error but we need this for bcontinueonfailure as we still want to stop on firstsuccess.
  3376. // }
  3377. })
  3378. }
  3379. var __acquireData = function (selected, options, datarepo, errHandler) {
  3380. datarepo = datarepo || selected.instanceName + '-data';
  3381. var repoOwner = options.repoOwner || selected.username || options.defaultRepoOwner
  3382. var errorHandler = (e) => {
  3383. 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`))){
  3384. // console.error('Could not connect to repo server. Timed Out')
  3385. 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 => {
  3386. if(propValue === 'y') {
  3387. reconfirm = getReconfirmAll()
  3388. return startElxr()
  3389. }
  3390. else if(propValue === 'r'){
  3391. return acquireConfig(selected)
  3392. }
  3393. else process.exit()
  3394. })
  3395. }
  3396. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${repoOwner}/${datarepo}.git/' not found`))){
  3397. var choices = {
  3398. t : `install a temporary local data folder.
  3399. For more options. Request and use a personal username at chess@bbh.org.in )`
  3400. , e : 'exit' }
  3401. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  3402. choices = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  3403. , {
  3404. i : 'create a new instance with this name => will fork the default config under your username'
  3405. , f : 'fork a new instance with this name for yourself for this node from another instance'
  3406. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  3407. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  3408. , p : 'create a custom config for yourself '
  3409. }, choices)
  3410. }
  3411. return cli.prompt( choices
  3412. , 'Data repo for instance not found. Would you like to ', 'e' ).then(propValue => {
  3413. if(propValue === 't') {
  3414. selectedinstance.local = true; return createInstanceData(selectedinstance)
  3415. }
  3416. if(propValue === 'i') return eNotImplemented()
  3417. if(propValue === 'f') return eNotImplemented()
  3418. if(propValue === 'o') return eNotImplemented()
  3419. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  3420. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  3421. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  3422. else process.exit()
  3423. })
  3424. }
  3425. console.warn(e)
  3426. throw e; //('Config acquisition failed.')
  3427. }
  3428. var successHandler = () => {
  3429. }
  3430. return performPull( selected.reposindexed[datarepo] || { repo : datarepo }
  3431. , null, repoOwner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  3432. .catch( (e)=>{
  3433. // if(e){
  3434. if(Promise.resolve(e) === e) return e;
  3435. // console.error(e)
  3436. e.benign = true;
  3437. throw e; // Not a hard error but we need this for bcontinueonfailure
  3438. // }
  3439. })
  3440. }
  3441. // ----------------------------------------------------------------
  3442. // PB : TODO -- Review and obsolete...
  3443. // ----------------------------------------------------------------
  3444. // var launchpath = path.resolve(path.normalize(ENV.wd))
  3445. var launchpath = selectedinstance.root
  3446. 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
  3447. // // we were run.
  3448. // // The easisest would be to ask for a target directory and default to current dir....
  3449. // // path.dirname(launchpath).split(path.sep).pop()
  3450. // var parent = path.dirname(launchpath);
  3451. // var pp = launchpath;
  3452. // var instancediscoverytasks = [];
  3453. // while(parent !== pp){
  3454. // instancediscoverytasks.push(
  3455. // ((pa)=>{
  3456. // var p = pa;
  3457. // return function(){
  3458. // return hasElxr(p).then((value)=>{
  3459. // if(value) return p
  3460. // // PB : TODO -- Using throw like this is not friendly with any...
  3461. // throw Object.assign( new Error('Benign Failure in Batch')
  3462. // , { value : false, benign : true });
  3463. // })
  3464. // }
  3465. // })(pp)
  3466. // )
  3467. // pp = parent;
  3468. // parent = path.dirname(parent);
  3469. // }
  3470. // var instanceroot = null
  3471. // var detectInstanceRoot = any(instancediscoverytasks, true, true).then( ir => {
  3472. // if(ir.error) { instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ; }
  3473. // else instanceroot = ir.pVal
  3474. // return instanceroot
  3475. // }).catch(()=>{
  3476. // instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
  3477. // })
  3478. var instanceroot = selectedinstance.root
  3479. // We first load the default and then override with a runconfig if it exists else we override with the interactive prompts.
  3480. // Then acquire and reload and replace this default.
  3481. var detectfromroot = function(root){
  3482. return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(root) ) }
  3483. }
  3484. // DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
  3485. // PB : TODO -- Cleanup this should no longer be needed... selectedinstance is properly initialized...
  3486. var detectLocalInstances = function(){
  3487. // console.log(`launchpath = ${launchpath}`)
  3488. // console.log(`thisscriptdir = ${thisscriptdir}`)
  3489. // PB : TODO -- !Postpone this.
  3490. // console.log(`instanceroot = ${instanceroot}`) // Not yet confirmed...
  3491. // Note : Paths should already be normalized fefore this.
  3492. var root = instanceroot;
  3493. var detected = { root };
  3494. var instanceoptions = [clioverrides]
  3495. return hasElxr(launchpath).then( (launchpathHasElxr) => {
  3496. // We need a reference to the root directory for elxr cli to be properly oriented.
  3497. if (( launchpathHasElxr && path.normalize(launchpath + '/elxr')) === thisscriptdir) {
  3498. // We were run from the proper root with elxr cli in the subfolder.
  3499. // PB : TODO -- Cleanup this should no longer be needed... selectedinstance is properly initialized...
  3500. instanceroot = root = launchpath;
  3501. instanceoptions.splice( 0, 0, detected = { root })
  3502. instanceoptions.splice( 0, 0, detectfromroot(root))
  3503. }
  3504. else {
  3505. if(path.normalize(launchpath + '/elxr') === thisscriptdir) {
  3506. // launchpathHasElxr is false -- and yet thiscriptdir is still proper.
  3507. // PB : TODO -- Maybe a warning / abort if for some reason thisscriptdir should not be used...
  3508. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.')
  3509. instanceroot = root = launchpath;
  3510. instanceoptions.splice( 0, 0, detected = { root })
  3511. instanceoptions.splice( 0, 0, detectfromroot(root))
  3512. }
  3513. else if (launchpath === thisscriptdir) {
  3514. var parentHasElxr = hasElxrSync(launchpath + '/..')
  3515. // PB : TODO -- verify if we have .elxr folder in the parent...
  3516. if(!parentHasElxr) {
  3517. // ! thisscriptdir is not elxr.
  3518. console.error('Invalid run location in subfolder that looks like elxr. We should probably abort as elxr will not sync.')
  3519. }
  3520. // Same directory doesn't mean we are being run from elxr sub directory.
  3521. // In standalone build script we may or not be in the same location.
  3522. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  3523. // Unbuilt therefore we are in the elxr sub directory.
  3524. instanceroot = root = path.normalize(launchpath + '/..');
  3525. instanceoptions.splice( 0, 0, detected = { root });
  3526. instanceoptions.splice( 0, 0, detectfromroot(root));
  3527. }
  3528. else {
  3529. // Built version.
  3530. // We could have been run from the elxr subfolder. Highly likely that the built version isn't the full elxr.
  3531. if(parentHasElxr) {
  3532. // Built version was run from the full elxr subfolder. Should work
  3533. // PB : TODO -- but we should switch to the full version...
  3534. instanceroot = root = path.normalize(launchpath + '/..');
  3535. instanceoptions.splice( 0, 0, detected = { root })
  3536. instanceoptions.splice( 0, 0, detectfromroot(root))
  3537. }
  3538. else {
  3539. instanceroot = root = launchpath;
  3540. instanceoptions.splice( 0, 0, detected = { root })
  3541. instanceoptions.splice( 0, 0, detectfromroot(root))
  3542. // Assume current launchpath is a new instance and create.
  3543. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  3544. // if(clioverrides.instanceName) {
  3545. // if(clioverrides.node_env) {
  3546. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  3547. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  3548. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  3549. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  3550. // // eg : floder name can be elixir01 but instance name is elixr
  3551. // }
  3552. // else {
  3553. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + 'development')
  3554. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  3555. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  3556. // }
  3557. // }
  3558. // else {
  3559. // instanceroot = root = launchpath;
  3560. // if(clioverrides.node_env) {
  3561. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  3562. // instanceoptions.splice( 0, 0, detectfromroot(root))
  3563. // }
  3564. // else {
  3565. // // Nothing was specified... We only have one option from root.
  3566. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  3567. // }
  3568. // }
  3569. }
  3570. }
  3571. }
  3572. else {
  3573. if(launchpathHasElxr) {
  3574. instanceroot = root = launchpath;
  3575. instanceoptions.splice( 0, 0, detected = { root })
  3576. instanceoptions.splice( 0, 0, detectfromroot(root))
  3577. }
  3578. }
  3579. }
  3580. instanceroot = detected.root
  3581. clioverrides.root = clioverrides.root || root;
  3582. // Resolves empty array when No known instances detected.
  3583. return Promise.resolve(instanceoptions)
  3584. })
  3585. }
  3586. var getReconfirmAll = ()=>{return { instanceName : true, instanceType : true, reposerver : true, username : true, password : true } }
  3587. if(clioverrides.reconfirm) {
  3588. var reconfirm = getReconfirmAll()
  3589. }
  3590. else { var reconfirm = {}; }
  3591. var shouldPrompt = function(k, possiblePrompts, target){
  3592. return ((possiblePrompts[k] !== undefined && possiblePrompts[k] !== null) && target[k] !== possiblePrompts[k]
  3593. || (possiblePrompts[k] === undefined || possiblePrompts[k] === null) && (target[k] === undefined || target[k] === null)
  3594. || reconfirm[k])
  3595. }
  3596. var getBoundEachPrompt = function(target, possiblePrompts, promptables, choices, promptsfilter) {
  3597. return function(prompts, k, i, a){
  3598. // Reducer for all prompts on targets.
  3599. // No local instances config found. We use a default initialized instance available in selectedinstance
  3600. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  3601. // PB : TODO -- selectedinstance === __default check to prompt everything...
  3602. if( shouldPrompt(k, possiblePrompts, target) ) {
  3603. delete reconfirm[k];
  3604. // console.log(k)
  3605. // console.dir(possiblePrompts); //console.dir(target)
  3606. prompts.push(async ()=>{
  3607. // PB : NOTE -- Important in async cases when this {{target}} needs to be in the same state as when it was invoked.
  3608. // We need to take a snapshot... Shallow.. !! If required deep should be used based on use case.
  3609. // var asyncthis = Object.assign(this);
  3610. // By default Latest altered state is provided which is an implicit reference directly.
  3611. promptables[k].choices = choices[k]
  3612. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  3613. return await target[k]
  3614. })
  3615. }
  3616. delete possiblePrompts[k] // PB : TODO We should keep this around instead of deleting so we can do a second pass if required.
  3617. return prompts
  3618. }
  3619. }
  3620. var __interactive_prompts = function( target, choices, promptsfilter ){
  3621. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  3622. var interactionpoints = {
  3623. runchoice : {
  3624. label :
  3625. `Choose an option :
  3626. d) Install the default chess instance.
  3627. => elxr i chess node_env=development --default
  3628. n) Create your custom new instance interactively
  3629. => elxr i {{instanceName}} node_env={{environment}}
  3630. i) Choose an instance and environment to install
  3631. => elxr i {{instanceName}} node_env={{environment}}
  3632. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  3633. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  3634. h) Help
  3635. q) Quit
  3636. : `
  3637. , choices : []
  3638. , defaultchoice : 'c'
  3639. , selectedchoice : target.runchoice
  3640. , interpret : function(choice){
  3641. var interpret_map = {
  3642. d : function(){
  3643. processedArgs._[0] = 'i'
  3644. target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  3645. target.node_env = processedArgs.node_env = (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  3646. target.reposerver = 'https://git.bbh.org.in' // PB : TODO -- Read from global defaults...
  3647. }
  3648. , n : function() { processedArgs._[0] = 'i' }
  3649. , i : function() {
  3650. processedArgs._[0] = 'i'
  3651. // processedArgs._[1] = target.instanceName || processedArgs._[1] || 'chess';
  3652. }
  3653. , c : async function() {
  3654. // this here will always be the target.
  3655. Object.defineProperty(this, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  3656. label : `Enter cmd :
  3657. p) pull
  3658. Default <= p
  3659. : `
  3660. , defaultchoice : 'pull'
  3661. }
  3662. ));
  3663. var cmd = await target['cmd'];
  3664. if (!cmd || cmd === 'p') { target['cmd'] = processedArgs._[0] = 'pull' }
  3665. else target['cmd'] = processedArgs._[0] = cmd
  3666. return cmd;
  3667. }
  3668. , h : function() { console.log(elxr.help()); process.exit() } // PB : TODO -- Why do we need log.
  3669. , q : function() { process.exit() }
  3670. }
  3671. if(Promise.resolve(choice) === choice){
  3672. return choice.then( resolvedchoice => {
  3673. return (interpret_map[choice] || interpret_map['c']).call(target)
  3674. })
  3675. }
  3676. else return Promise.resolve( (interpret_map[choice] || interpret_map['c']).call(target) )
  3677. // var __interpreter = interpret_map[choice] || interpret_map['c']
  3678. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  3679. // if(interpret_map[choice]) __interpreter = interpret_map[choice];
  3680. // return __interpreter.call(target)
  3681. }
  3682. }
  3683. , instanceName : { label : `Enter Instance Name ( <= ${target.instanceName || 'chess'} ) : `
  3684. , choices : choices['instanceName'], defaultchoice : 'chess'
  3685. , selectedchoice : target.instanceName
  3686. }
  3687. , instanceType : { label : `Enter Instance Type ( <= ${target.instanceType || 'development'} ) : `
  3688. , choices : choices['instanceType'], defaultchoice : 'development'
  3689. , selectedchoice : target.instanceType || 'development'
  3690. }
  3691. , reposerver : { label : `Enter Repo Server Base Url ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `
  3692. , get choices() {
  3693. choices['reposerver'].forEach( rs => {
  3694. var __rs = new URL(rs);
  3695. __rs.hostname = __rs.host;
  3696. __rs.path = '/'
  3697. __rs.method = 'GET'
  3698. RESTAPI.get(__rs, function(data){ rs.accessibility = 'accessible' }
  3699. , function(error){ rs.accessibility = 'unaccessible' } )
  3700. })
  3701. return choices['reposerver']
  3702. }
  3703. , defaultchoice : 'https://git.bbh.org.in'
  3704. , selectedchoice : target.reposerver
  3705. }
  3706. , 'upstream-remote' : { label : `Enter Remote Name ( <= ${target['upstream-remote'] || 'chess'} ) : `
  3707. , get choices() {
  3708. var reposerver = target['reposerver']
  3709. var remotes = []
  3710. var trs = target.reposervers || []
  3711. trs.forEach(rs => {
  3712. if(rs.server === reposerver){
  3713. remotes.push(remote)
  3714. // PB : TODO -- Sort and display highest priority target.remotes.sort( )
  3715. }
  3716. })
  3717. return remotes
  3718. }
  3719. , defaultchoice : 'userfork'
  3720. , selectedchoice : target['upstream-remote'] || 'userfork'
  3721. // Just using getters resolves dependencies..., dependencies : [ ()=>{ return target['reposerver'] } ]
  3722. }
  3723. , 'remote-type' : { label : `Enter Remote Type ( <= ${target['remote-type'] || 'public'} ) : `
  3724. , get choices() {
  3725. return ['external', 'public', 'private', 'github', 'unc']
  3726. }
  3727. , defaultchoice : 'public'
  3728. , selectedchoice : target['remote-type'] || 'public'
  3729. // Just using getters resolves dependencies..., dependencies : [ ()=>{ return target['reposerver'] } ]
  3730. }
  3731. , 'selectedremotes' : { label : `Chose Remote Names ( <= ${target['selectedremotes'] || 'chess'} ) : `
  3732. , get choices() {
  3733. var reposerver = target['reposerver'] // PB : TODO -- We need options to work with multiple selected reposervers at the same time..
  3734. var remotenames = []
  3735. Object.entries(target.remotes || []).forEach( ([rname, r]) => {
  3736. if(r.server === reposerver && r.accessibility.find( target[ 'remote-type' ] )){
  3737. remotes.push(rname)
  3738. // PB : TODO -- Sort and display highest priority target.remotes.sort( )
  3739. }
  3740. })
  3741. // PB : TODO -- Need to generate all possible permuted choices nP( 1 -> n )
  3742. // Currenty handles all combinations without any priority order.
  3743. var _remotechoices = [] // Array of arrays of choices.
  3744. remotenames.forEach( r => {
  3745. var __rcs = []
  3746. _remotechoices.forEach(rc => {
  3747. __rcs.push( rc.concat(r) )
  3748. })
  3749. Array.prototype.push.apply( _remotechoices, __rcs)
  3750. _remotechoices.push(r)
  3751. })
  3752. return _remotechoices
  3753. }
  3754. , defaultchoice : ['userfork', 'chess'] // userfork and chess should imlicitly point to userfork-external and chess-external when external connectivity is dtetected.
  3755. , selectedchoice : target['selectedremotes'] || ['userfork-external', 'chess-external']
  3756. // , defaultchoice : { 'userfork-external' : target.remotes['userfork-external'] , 'chess-external' : target.remotes['chess-external'] }
  3757. // , selectedchoice : target['selectedremotes'] || { 'userfork-external' : target.remotes['userfork-external'] , 'chess-external' : target.remotes['chess-external'] }
  3758. // Info : Just using getters resolves dependencies..., dependencies : [ ()=>{ return target['reposerver'] } ]
  3759. }
  3760. , get username() { return { label : `Enter User Id for ${target.reposerver} ( <= ${target.username || 'chess'} ) : `
  3761. , choices : choices['username'], defaultchoice : 'chess', selectedchoice : target.username } }
  3762. , get password() { return { label : `Enter Password for ${target.username} @ ${target.reposerver} ( <= ${target.password || ''} ) : `
  3763. , choices : choices['password'], defaultchoice : '***', selectedchoice : target.password } }
  3764. , get email() { return { label : `Enter Email for ${target.username} @ ${target.reposerver} ( <= ${target.email || ''} ) : `
  3765. , choices : choices['email'], defaultchoice : 'guest@bbh.org.in', selectedchoice : target.email } }
  3766. }
  3767. function getPromptKeys() {
  3768. if(! (processedArgs.label || processedArgs._[0]) ) return Object.assign({}, interactionpoints);
  3769. return promptkeys
  3770. }
  3771. var eachPrompt = getBoundEachPrompt( target, getPromptKeys() , interactionpoints, choices, promptsfilter)
  3772. return Object.keys(promptsfilter || interactionpoints).reduce(eachPrompt, [])
  3773. }
  3774. var downloadsdir = '../Downloads';
  3775. var prerequisites = [
  3776. {
  3777. shellcmd: 'git',
  3778. name : 'git',
  3779. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  3780. , installer: 'Git-2.31.0-64-bit.exe'
  3781. , installcmd: ['cmd', ['/c', 'start',
  3782. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  3783. , '/VERYSILENT'
  3784. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  3785. ]]
  3786. , preinstallsteps: function() {
  3787. var steps = [
  3788. () => {
  3789. if (!existsSync(downloadsdir + '/' + this.installer)) {
  3790. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  3791. }
  3792. else return Promise.resolve(true)
  3793. }
  3794. ]
  3795. var prompts = this.getuser(null, ()=>{
  3796. // console.log('preinstallsteps')
  3797. // var gitUser = 'guest';
  3798. // var gitEmail = 'guest@bbh.org.in';
  3799. // var prompts = [];
  3800. // prompts.push( ()=>{ return cli.prompt(choices['username'], 'git user name').then(gituser => gitUser = gituser) } )
  3801. // prompts.push( ()=>{ return cli.prompt(choices['useremail'], 'git user email').then(gitemail => gitEmail = gitemail) } )
  3802. // console.log('prompting in preinstallsteps')
  3803. // return any(prompts).then(()=>{
  3804. // var steps = [
  3805. // ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  3806. // , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  3807. // ]
  3808. // return any(steps.map(getshelltask)).then(() => {
  3809. // })
  3810. // });
  3811. return Promise.resolve(true)
  3812. })
  3813. return any([any(steps), prompts])
  3814. }
  3815. , installsteps: function () {
  3816. return any([this.installcmd].map(getshelltask))
  3817. }
  3818. , postinstallsteps: function(err, users){
  3819. return this.getuser(null, (err, data)=>{
  3820. // ignore err and proceed with data as guest.
  3821. console.dir(data)
  3822. if(data && data.length === 1 && !shouldPrompt('username', promptkeys, selectedinstance) ) {
  3823. return username = data[0];
  3824. }
  3825. data = data || ['guest']
  3826. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  3827. console.log('prompting in postinstallsteps')
  3828. var username = 'guest';
  3829. var email = 'guest@bbh.org.in';
  3830. var password = '***';
  3831. return any( getInteractionPoints(selectedinstance, promptkeys, { username, password, email}) ).then(()=>{
  3832. if(!data.find(e => e === selectedinstance.username)) {
  3833. var steps = [
  3834. ['git', ['config', '--global', '--add', 'user.name', `${username}`]]
  3835. , ['git', ['config', '--global', '--add', 'user.email', `${email}`]]
  3836. ]
  3837. return any(steps.map(getshelltask)).then(() => {
  3838. })
  3839. }
  3840. else {
  3841. return Promise.resolve(true)
  3842. }
  3843. });
  3844. })
  3845. }
  3846. , install: function () {
  3847. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  3848. }
  3849. , verifyAndInstall : function(){
  3850. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  3851. if(exists) {
  3852. // return any(['git', ['config', '--global', '-l']].map(getshelltask))
  3853. return this.postinstallsteps.bind(this)()
  3854. }
  3855. return this.install();
  3856. });
  3857. }
  3858. , getuser : function(repo, onResult){
  3859. var __onResult = onResult || function(e, data){
  3860. data = data || []
  3861. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  3862. // console.dir(choices)
  3863. return data[0]
  3864. }
  3865. var globalOrLocal = '--global';
  3866. if(repo) globalOrLocal = '--local'
  3867. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(getshelltask)).then((result)=>{
  3868. // not yet configured.
  3869. if(!result.success) return __onResult(result)
  3870. else {
  3871. var users = result.messages[0].trim().split('\n');
  3872. if(users.length === 0 ||
  3873. users.length === 1 && users[0] === 'guest') {
  3874. return __onResult(result)
  3875. }
  3876. else {
  3877. return __onResult(null, Array.from( new Set( users ) ) ); }// PB : TODO == We should probably prompt with all the users available for selection !
  3878. }
  3879. })
  3880. .catch((e)=>{
  3881. console.log(e)
  3882. return __onResult(e)
  3883. })
  3884. }
  3885. }
  3886. ,
  3887. {
  3888. shellcmd: 'node',
  3889. name : 'node',
  3890. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  3891. , installer: 'node-v14.16.0-x64.msi'
  3892. , installcmd: ['MSIEXEC.exe', ['/i'
  3893. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  3894. , 'ACCEPT=YES', '/passive']]
  3895. , install : function() { return any([this.installcmd].map(getshelltask)).then(() => { }) }
  3896. }
  3897. ]
  3898. for(var i=0; i<prerequisites.length; i++) {
  3899. prerequisites[prerequisites[i].name] = prerequisites[i];
  3900. }
  3901. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  3902. function ensureDirectoryExistence(filePath) {
  3903. var dirname = path.dirname(filePath);
  3904. if (fs.existsSync(dirname)) {
  3905. return filePath;
  3906. }
  3907. ensureDirectoryExistence(dirname);
  3908. fs.mkdirSync(dirname);
  3909. return filePath;
  3910. }
  3911. var mainTasks = [];
  3912. function verifyAndInstallPrerequisites() {
  3913. var downloadtasks = [];
  3914. var installtasks = [];
  3915. prerequisites.forEach(preq => {
  3916. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  3917. if (exists) console.log(`${preq.shellcmd} exists`)
  3918. else {
  3919. console.log(`${preq.shellcmd} is not installed`)
  3920. return preq.preinstallsteps.call(preq).then(() => {
  3921. installtasks.push(preq.install.bind(preq))
  3922. })
  3923. }
  3924. }))
  3925. })
  3926. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  3927. }
  3928. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  3929. return {
  3930. get (){
  3931. return any( promptable.dependencies || [] ).then(()=>{
  3932. return cli.prompt( promptable.choices, promptable.label, promptable.defaultchoice, promptable.selectedchoice ).then(propValue => {
  3933. var asyncprop = Promise.resolve(propValue)
  3934. if(promptable.interpret){
  3935. asyncprop = promptable.interpret(propValue)
  3936. }
  3937. return asyncprop.then(
  3938. ()=>{
  3939. Object.defineProperty(this, propName, {
  3940. value: propValue,
  3941. writable: true,
  3942. configurable : true,
  3943. enumerable : true
  3944. });
  3945. return propValue
  3946. }
  3947. )
  3948. })
  3949. } )
  3950. }
  3951. // , set (propValue){
  3952. // Object.defineProperty(this, propName, {
  3953. // value: propValue,
  3954. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  3955. // configurable : true,
  3956. // enumerable : true
  3957. // })
  3958. // return propValue;
  3959. // }
  3960. , configurable : true
  3961. , enumerable : true
  3962. }
  3963. }
  3964. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  3965. var runconfig = null;
  3966. var chessinstances = { current_run : {} };
  3967. var promptkeys = {
  3968. cmd : processedArgs._[0] || 'pull'
  3969. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  3970. // 'instanceName' : true
  3971. // , 'node_env' : true
  3972. // , username : ''
  3973. // , runchoice : 'c'
  3974. }
  3975. // promptkeys.runchoice = promptkeys.cmd ? 'c' : undefined
  3976. function createLocalChessInstance( cfg ){
  3977. // return createInstance(cfg)
  3978. reconfirm = getReconfirmAll()
  3979. var inst = {};
  3980. var __new = Object.assign({}, __default, cfg)
  3981. inst[cfg.node_env] = __new; return inst;
  3982. }
  3983. var choices = {
  3984. 'instanceName' : []
  3985. , 'reposerver' : []
  3986. , 'upstream-remote' : []
  3987. , 'instanceType' : []
  3988. , username : ['guest', 'chessdemo', 'demo']
  3989. }
  3990. var getInteractionPoints = function(detectedinstanceoptions, possiblePrompts, promptsfilter){
  3991. var instances = []
  3992. var reposervers = [];
  3993. var remotes = [];
  3994. var instanceNames = []
  3995. var instanceTypes = ['development', 'production'];
  3996. Object.keys( chessinstances).forEach(instanceName => {
  3997. if(instanceName === 'current_run') return;
  3998. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  3999. var instance = chessinstances[instanceName][node_env];
  4000. reposervers = reposervers.concat(instance.reposervers)
  4001. if(instance.reposerver) reposervers.push(instance.reposerver)
  4002. instances.push(instance)
  4003. instanceTypes.push(instance.node_env)
  4004. instanceNames.push(instance.instanceName)
  4005. var otherremotes = instance?.reposerverinstances
  4006. if(otherremotes) otherremotes = otherremotes[instance?.reposerver]?.remotes
  4007. otherremotes = otherremotes || {}
  4008. Array.prototype.push.apply(remotes, Object.keys(otherremotes))
  4009. })
  4010. })
  4011. instances = instances.concat(detectedinstanceoptions)
  4012. if(selectedinstance['instanceName']) instanceNames.push(selectedinstance['instanceName'])
  4013. if(possiblePrompts['instanceName']) instanceNames.push(possiblePrompts['instanceName'])
  4014. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers'])
  4015. choices['instanceName'] = Array.from( new Set(instanceNames.concat(choices['instanceName'])) )
  4016. choices['reposerver'] = Array.from( new Set(reposervers.concat(choices['reposerver'])) )
  4017. // choices['upstream-remote'] = Array.from( new Set(remotes.concat(choices['upstream-remote'])) )
  4018. choices['instanceType'] = Array.from( new Set(instanceTypes.concat(choices['instanceType'])) )
  4019. return __interactive_prompts(selectedinstance, choices, promptsfilter)
  4020. }
  4021. var detection_state = {
  4022. localInstanceDetected : false
  4023. }
  4024. const https = require('https')
  4025. const http = require('http');
  4026. const { Console } = require('console');
  4027. const { env } = require('process');
  4028. const RESTAPI = (function(){
  4029. // Singleton
  4030. function RESTAPI(){}
  4031. // RESTAPI.create = RESTAPI; // Returns the one singe instance which is the class itself
  4032. // const httpsoptions = {
  4033. // hostname: 'whatever.com',
  4034. // port: 443,
  4035. // path: '/todos',
  4036. // method: 'POST',
  4037. // headers: {
  4038. // 'Content-Type': 'application/json',
  4039. // 'Content-Length': data.length
  4040. // }
  4041. // }
  4042. RESTAPI.method = function(options, resolve, reject){
  4043. options.headers = options.headers || { 'Content-Type': 'application/json' }
  4044. const data = options.payload ? new TextEncoder().encode( JSON.stringify(options.payload) ) : null
  4045. options.headers = options.payload ? (options.headers || {
  4046. 'Content-Type': 'application/json',
  4047. 'Content-Length': data.length
  4048. }) : (options.headers || {})
  4049. !options.headers.Authorization && usertokens[options.username] ? (()=>{
  4050. options.headers.Authorization = `token ${usertokens[options.username]}`
  4051. delete options.username
  4052. onauthenticated()
  4053. })() : (()=>{
  4054. if(!usertokens[options.username] && !options.isAuthCall) {
  4055. RESTAPI.authenticate( utils.assign( {isAuthCall : true}, options ) , onauthenticated, function(err){
  4056. // PB : TODO -- Retry without auth...
  4057. console.error('Auth failed or not accessible')
  4058. reject(err)
  4059. })
  4060. }
  4061. else onauthenticated()
  4062. })()
  4063. function onauthenticated(){
  4064. var acquirer = getHTTPorS(options)
  4065. const req = acquirer.request(options, res => {
  4066. if (res.statusCode < 200 || res.statusCode >= 300) {
  4067. // new Error('statusCode=' + res.statusCode)
  4068. return reject('statusCode = ' + res.statusCode);
  4069. }
  4070. var body = [];
  4071. // res.setEncoding('utf8');
  4072. res.on('data', (chunk)=>{ body.push(chunk); });
  4073. res.on('end', ()=>{
  4074. try {
  4075. if(res.headers['content-type'] && res.headers['content-type'].split(';').find( (i)=> i.trim() === 'application/json' )) body = JSON.parse(Buffer.concat(body).toString());
  4076. else body = Buffer.concat(body).toString();
  4077. } catch(e) { return reject(e); }
  4078. resolve(body);
  4079. });
  4080. });
  4081. req.on('error', error => { reject(error) })
  4082. if(options.payload) req.write(data)
  4083. req.end()
  4084. }
  4085. }
  4086. var usertokens = {}
  4087. RESTAPI.authenticate = function(options, resolve, reject){
  4088. options.headers = options.headers || { 'Content-Type': 'application/json' }
  4089. if(!usertokens[options.username]) {
  4090. // Authenticate and acquire token.
  4091. // https://git.bbh/api/v1/users/<username>/tokens
  4092. // curl -XPOST -H "Content-Type: application/json" -k -d '{"name":"demo"}' -u demo:demo123 http://git.bbh/api/v1/users/demo/tokens
  4093. var _options = Object.assign({}, options)
  4094. // _options.username = 'demo'
  4095. // _options.password = 'demo123'
  4096. _options.method = 'POST'
  4097. _options.headers.Authorization = `Basic ${Buffer.from(`${_options.username}:${_options.password}`).toString('base64')}`
  4098. _options.path = `/api/v1/users/${_options.username}/tokens`
  4099. var postoptions = { name : _options.username }
  4100. delete _options.username
  4101. delete _options.password
  4102. _options.payload = postoptions
  4103. RESTAPI.post( _options, function(tokenresp){
  4104. // tokenresp = JSON.parse(tokenresp)
  4105. usertokens[options.username] = tokenresp.sha1
  4106. resolve(tokenresp)
  4107. },
  4108. function(err){ reject(err) }
  4109. )
  4110. }
  4111. else resolve(tokenresp.sha1)
  4112. }
  4113. RESTAPI.put = RESTAPI.get = RESTAPI.post = RESTAPI.method
  4114. return RESTAPI
  4115. })();
  4116. var getHTTPorS = function(options){ return options.protocol.startsWith('https') ? https : http; }
  4117. const GITEA = (function(){
  4118. function GITEA(){}
  4119. GITEA.APIROOT = '/api/v1'
  4120. GITEA.repository = {
  4121. fork( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  4122. // forkoptions = { owner : httpoptions.username, repo : {{reoptoFork}} }
  4123. // giteaoptions = {
  4124. // organization string
  4125. // --- organization name, if forking into an organization
  4126. // }
  4127. // http://try.gitea.io/api/v1/repos/{owner}/{repo}/forks
  4128. httpoptions.path = `${GITEA.APIROOT}/repos/${cmdoptions.owner}/${cmdoptions.repo}/forks`
  4129. httpoptions.method = 'POST'
  4130. httpoptions.payload = giteaoptions;
  4131. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  4132. }
  4133. , updateattributes( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  4134. httpoptions.path = `${GITEA.APIROOT}/repos/${cmdoptions.owner}/${cmdoptions.repo}`
  4135. httpoptions.method = 'PATCH'
  4136. httpoptions.payload = giteaoptions;
  4137. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  4138. }
  4139. , exists( httpoptions, repo, owner ) {
  4140. // ​/users​/{username} // Get a user
  4141. httpoptions.path = `${GITEA.APIROOT}/repos/${owner}/${repo}`
  4142. httpoptions.method = 'GET'
  4143. return new Promise( (resolve, reject) => {
  4144. RESTAPI.get(httpoptions, function(o){
  4145. if(o.id) return resolve(true)
  4146. return resolve(false) }, reject || function(){ return false } )
  4147. })
  4148. }
  4149. , addcollaborator( httpoptions, repodef, owner, collaborator, permission ) {
  4150. permission = permission || 'Read'
  4151. httpoptions.payload = { permission }
  4152. httpoptions.path = `${GITEA.APIROOT}/repos/${owner}/${repodef.repo}/collaborators/${collaborator}`
  4153. httpoptions.method = 'PUT'
  4154. return new Promise( (resolve, reject) => {
  4155. RESTAPI.put(httpoptions, function(o){
  4156. //
  4157. if(o === "") return resolve(true)
  4158. return resolve(false) }, reject || function(){ return false } )
  4159. })
  4160. }
  4161. }
  4162. GITEA.user = {
  4163. getuser( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  4164. // ​/users​/{username} // Get a user
  4165. httpoptions.path = `${GITEA.APIROOT}/users/${httpoptions.username}`
  4166. httpoptions.method = 'GET'
  4167. return RESTAPI.get(httpoptions, giteaoptions, resolve || function(){}, reject || function(){} )
  4168. }
  4169. }
  4170. return GITEA
  4171. })();
  4172. // Wrapper for Git shell operations. Some meta operations will map to a bunch of GIT commands.
  4173. const GIT = (function(){
  4174. function GIT(){}
  4175. Object.assign(GIT, {
  4176. 'switch user'(username){
  4177. var httpoptions = new URL(selectedinstance.reposerver);
  4178. httpoptions.username = selectedinstance.username
  4179. httpoptions.password = selectedinstance.password
  4180. return GITEA.user.getuser(httpoptions).then(()=>{
  4181. return nodeShellExec('git', ['config', '--replace-all', 'user.name', username],
  4182. {
  4183. inherit: true, shell: true,
  4184. env: ENV
  4185. , cwd: instanceroot + '/' + repo
  4186. , runas: processedArgs.runas
  4187. , title: `'git', ${['config', '--replace-all', 'user.name', username].join(' ')}`
  4188. })
  4189. }
  4190. )
  4191. .catch(e => {
  4192. console.error(e + 'Could not switch. Probably no such user.')
  4193. })
  4194. }
  4195. })
  4196. return GIT
  4197. })();
  4198. function createInstanceData(target, source) {
  4199. var sourceinstance = source || target;
  4200. console.dir(sourceinstance)
  4201. var args = {
  4202. remotebase : sourceinstance.reposerver + '/chess/'
  4203. , sourcerepo : sourceinstance.repo || 'chess-data'
  4204. , targetrepo : `${target.instanceName}-data-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  4205. }
  4206. if(sourceinstance.local) {
  4207. var options = {
  4208. inherit: true, shell: true,
  4209. env: ENV
  4210. , cwd : instanceroot
  4211. , runas: processedArgs.runas
  4212. }
  4213. var cmdseq = [
  4214. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  4215. ]
  4216. return any(cmdseq.map(getshelltask)).then(() => { return true })
  4217. }
  4218. else {
  4219. // http://try.gitea.io/api/v1/org/{org}/repos
  4220. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  4221. throw 'createInstanceData is possible only within the same repository server.'
  4222. }
  4223. var server = new URL(target.reposerver);
  4224. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  4225. , username : target.username, password : target.password
  4226. }
  4227. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  4228. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  4229. return GITEA.repository.updateattributes( {
  4230. hostname : server.host, protocol : server.protocol
  4231. , username : target.username, password : target.password
  4232. }
  4233. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  4234. , { name : `${args.targetrepo}`}
  4235. )
  4236. }
  4237. )
  4238. }
  4239. // GITEA.repository.updateattributes( {
  4240. // hostname : server.host, protocol : server.protocol
  4241. // , username : selectedinstance.username, password : selectedinstance.password
  4242. // }
  4243. // , { repo : `chess-config`, owner : selectedinstance.username }
  4244. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  4245. // )
  4246. // return selectedinstance
  4247. }
  4248. function createInstance(target, source) {
  4249. var sourceinstance = source || target;
  4250. console.dir(sourceinstance)
  4251. var args = {
  4252. remotebase : sourceinstance.reposerver + '/chess/'
  4253. , sourcerepo : sourceinstance.repo || 'chess-config'
  4254. , targetrepo : `${target.instanceName}-config-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  4255. }
  4256. if(sourceinstance.local) {
  4257. var options = {
  4258. inherit: true, shell: true,
  4259. env: ENV
  4260. , cwd : instanceroot
  4261. , runas: processedArgs.runas
  4262. }
  4263. var cmdseq = [
  4264. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  4265. ]
  4266. return any(cmdseq.map(getshelltask)).then(() => { return true })
  4267. }
  4268. else {
  4269. // http://try.gitea.io/api/v1/org/{org}/repos
  4270. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  4271. throw 'createInstance is possible only within the same repository server.'
  4272. }
  4273. var server = new URL(target.reposerver);
  4274. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  4275. , username : target.username, password : target.password
  4276. }
  4277. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  4278. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  4279. return GITEA.repository.updateattributes( {
  4280. hostname : server.host, protocol : server.protocol
  4281. , username : target.username, password : target.password
  4282. }
  4283. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  4284. , { name : `${args.targetrepo}`}
  4285. )
  4286. }
  4287. )
  4288. }
  4289. // GITEA.repository.updateattributes( {
  4290. // hostname : server.host, protocol : server.protocol
  4291. // , username : selectedinstance.username, password : selectedinstance.password
  4292. // }
  4293. // , { repo : `chess-config`, owner : selectedinstance.username }
  4294. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  4295. // )
  4296. // return selectedinstance
  4297. }
  4298. var skipprerequisites = false;
  4299. function initinstances(selected_overrides) {
  4300. var root = selected_overrides.root // We should always have this coz we are running at some place which is fixed by detectLocalInstances.
  4301. var instanceName = selected_overrides.instanceName
  4302. || clioverrides.instanceName
  4303. // || processedArgs._[1]
  4304. || chessinstances.current_run.instanceName
  4305. var node_env = selected_overrides.node_env
  4306. || clioverrides.node_env
  4307. // || processedArgs.node_env
  4308. || chessinstances.current_run.node_env
  4309. var reposerver = selected_overrides.reposerver
  4310. || clioverrides.reposerver
  4311. // || processedArgs.node_env
  4312. || chessinstances.current_run.reposerver
  4313. if(!instanceName) {
  4314. promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  4315. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  4316. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  4317. }
  4318. if(!node_env) {
  4319. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  4320. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  4321. }
  4322. if(!reposerver) {
  4323. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  4324. }
  4325. chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
  4326. instanceName, node_env, root : selected_overrides.root, reposerver : selected_overrides.reposerver /* promptkeys['reposerver'] */ } );
  4327. chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root }
  4328. if(path.normalize(selected_overrides.root) !== path.normalize(chessinstances[instanceName][node_env].root)) {
  4329. 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
  4330. }
  4331. // Override sequence.
  4332. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  4333. // PB : TODO -- Undefined keys are overriding and deleting values. We should not allow that.
  4334. // This is ordinary utils.assign behavior. The key should not exist as undefined in the override.
  4335. // PB : TODO -- We now have options that can be passed into assign_core to control this behavior.
  4336. if(selected_overrides.node_env === undefined) delete selected_overrides.node_env
  4337. selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  4338. , __default
  4339. , chessinstances[instanceName][node_env]
  4340. , clioverrides
  4341. , selected_overrides
  4342. // , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
  4343. );
  4344. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  4345. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  4346. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  4347. // // Brand New.
  4348. // selectedinstance = Object.assign( __default, selectedinstance )
  4349. // }
  4350. if(selectedinstance?.repos && !selectedinstance?.repos[0]?.repo) {
  4351. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  4352. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  4353. }
  4354. if(selectedinstance?.elevated && !selectedinstance?.elevated[0]?.repo) {
  4355. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  4356. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  4357. }
  4358. // Config from server always override merges into selection except for the current selection.
  4359. // PB : TODO -- utils.assign Array merges are non-distinct...
  4360. chessinstances[instanceName][node_env] = selectedinstance;
  4361. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  4362. cacheWriteInstanceConfig(chessinstances, selectedinstance.root)
  4363. // PB : TODO -- We should probably write the new server config also...
  4364. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  4365. return chessinstances
  4366. }
  4367. var skipprereqs = {}
  4368. var maintask = () => {
  4369. // Default cmd to run !
  4370. processedArgs._[0] === processedArgs._[0] || 'pull';
  4371. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  4372. if(!noprerequisites[processedArgs._[0]]
  4373. && !skipprereqs[processedArgs._[0]]
  4374. ) {
  4375. return prerequisites.git.verifyAndInstall().then(()=>{
  4376. var e = { message : 'verifyAndInstall', success : true}
  4377. var inittasks = []
  4378. var commontask = () => { preworkerconfig(); return elxrworker(true) }
  4379. if(!detection_state.localInstanceDetected) {
  4380. var t1 = ()=>{ return createInstance(selectedinstance) };
  4381. t1.statuslog = statuslog
  4382. var specifictask = shell_verse.getNonElevatedTask(t1)
  4383. }
  4384. else {
  4385. var t2 = ()=>{ return acquireConfig(selectedinstance) };
  4386. t2.statuslog = statuslog
  4387. var specifictask = shell_verse.getNonElevatedTask(t2)
  4388. }
  4389. inittasks.push( specifictask().catch((err) => {
  4390. e = err;
  4391. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  4392. console.error(err)
  4393. }).then( commontask )
  4394. // .finally(()=>{
  4395. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  4396. // if(!e.success) fs.writeFileSync('run.done', 'error');
  4397. // // return process.exit()
  4398. // }))
  4399. )
  4400. return any(inittasks)
  4401. })
  4402. }
  4403. else {
  4404. console.log('cmd has no preqs or has been configured to skip preqs')
  4405. preworkerconfig()
  4406. return elxrworker()
  4407. }
  4408. }
  4409. function generateDependencies(){
  4410. // PB : TODO -- Keep only the last n runs...
  4411. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  4412. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
  4413. fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
  4414. // PB : TODO include and build from files... using rollup..
  4415. var downloadbatch =
  4416. `::**************************************************************************
  4417. :Download_ <url> <File>
  4418. Powershell.exe ^
  4419. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  4420. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  4421. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  4422. exit /b
  4423. ::**************************************************************************`
  4424. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch)
  4425. var windowselevate =
  4426. `
  4427. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  4428. <script language="vbscript">
  4429. document.title = "elxr control panel"
  4430. self.ResizeTo 200,600
  4431. Sub Window_Onload
  4432. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  4433. End Sub
  4434. Set objShell = CreateObject("WScript.Shell")
  4435. Set objENV = objShell.Environment("Process")
  4436. dim NODE_ENV
  4437. NODE_ENV = objENV("NODE_ENV")
  4438. </script>
  4439. <script language="javascript">
  4440. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  4441. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  4442. // alert(windowselevate.commandLine)
  4443. var args = windowselevate.commandLine.split('"').slice(3);
  4444. // alert(args)
  4445. var processedArgs = { _ : [] }
  4446. var namedArgs = [];
  4447. namedArgs.push('--wd=' + objENV('wd'))
  4448. // alert(namedArgs)
  4449. for(var item in args){
  4450. if(args[item].charAt(0) === '-'){
  4451. namedArgs.push(args[item])
  4452. var split = args[item].split('=');
  4453. processedArgs[split[0].slice(2)] = split[1] || true;
  4454. }
  4455. else processedArgs._.push(args[item]);
  4456. }
  4457. // args = args.forEach(function(item){ })
  4458. // alert('processedArgs._ : ' + processedArgs._);
  4459. // alert(processedArgs.runas);
  4460. // alert(objENV('wd'))
  4461. // PB : TODO -- Convert all the cli args back to string.
  4462. // __filename will sure we are launhed using the same entry point.
  4463. var cargs = (processedArgs.debug ? '--inspect-brk=9226' : '') + ' ${__filename.replace(/\\/g, '\\\\')} ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  4464. var shell = new ActiveXObject('shell.application');
  4465. // alert('launching node privilged. ' + processedArgs['nodepath'])
  4466. // shell.ShellExecute('cmd.exe', '/k where node', '', '', 10);
  4467. // shell.ShellExecute('cmd.exe', '/k notepad.exe', '', 'runas', 1);
  4468. // shell.ShellExecute('cmd.exe ', '/k node ', '', 'runas', 1);
  4469. // shell.ShellExecute('cmd.exe ', '/k node ' + cargs + '', '', 'runas', 1);
  4470. shell.ShellExecute('node', cargs, '', 'runas', 1);
  4471. // alert('/k node ' + cargs + '')
  4472. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  4473. var fso = new ActiveXObject('Scripting.FileSystemObject');
  4474. window.onload = function() {
  4475. document.body.style.backgroundColor = 'black';
  4476. document.body.style.fontFamily = 'arial';
  4477. var log = document.createElement('div');
  4478. log.innerHTML='Please Wait';
  4479. function l(msg){ log.innerHTML+= msg; };
  4480. log.style.color = 'blue';
  4481. log.style.width = '95%';
  4482. log.id = 'log';
  4483. document.body.appendChild(log);
  4484. l('<Br/>Current config : ')
  4485. l('<Br/>NODE_ENV = ' + NODE_ENV)
  4486. l('<Br/>cmd = ' + processedArgs._[0])
  4487. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  4488. l('<Br/><Br/>')
  4489. // alert(fso.GetAbsolutePathName("."))
  4490. var timer = function(){
  4491. l('.');
  4492. if(fso.FileExists("run.done")) {
  4493. fso.DeleteFile('run.done') // PB : TODO -- IPC through files is needed only for windows we need to do it per run...
  4494. close();
  4495. }
  4496. else window.setTimeout(timer, 1000);
  4497. };
  4498. window.setTimeout(timer, 3000);
  4499. };
  4500. </script>
  4501. </html>
  4502. `
  4503. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate)
  4504. }
  4505. var startElxr = function() {
  4506. const retaincount = 2
  4507. var min = runtimestamp;
  4508. var collect = []
  4509. if(reconfirmcmds[processedArgs.label || processedArgs._[0]]) {
  4510. reconfirm = getReconfirmAll()
  4511. }
  4512. return detectLocalInstances().then((detectedinstanceoptions)=>{
  4513. detectedinstanceoptions.splice(0,0, __default)
  4514. var cmdinstance = cmds[clioverrides.cmd]
  4515. var cmdprompts = cmdinstance.getPossiblePrompts()
  4516. selectedinstance.node_env ? selectedinstance.node_env : selectedinstance.node_env = clioverrides.node_env
  4517. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  4518. selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  4519. , ...detectedinstanceoptions.slice(-2), promptkeys )
  4520. // promptkeys = utils.assign(promptkeys, clioverrides)
  4521. // startElxr requires instance // Independent cmds should have already been bypassed.
  4522. // if(cmdprompts.instanceName) {
  4523. // not an instanceless cmd.
  4524. console.dir(selectedinstance)
  4525. try {
  4526. chessinstances = acquirelocalinstances(selectedinstance);
  4527. findlocalinstances(chessinstances, detectedinstanceoptions)
  4528. initinstances(selectedinstance) // use the local instances for defaults if at all possible.
  4529. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  4530. var inst = initinstances(selectedinstance)
  4531. detection_state.localInstanceDetected = true;
  4532. return inst;
  4533. })
  4534. }
  4535. catch (e) {
  4536. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  4537. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  4538. return initinstances(selectedinstance)
  4539. })
  4540. // if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  4541. // // Weve not been told what to do.
  4542. // todo = todo.then(() => { return acquireChoices(selectedinstance) })
  4543. // }
  4544. todo = todo.then(() => {
  4545. try {
  4546. chessinstances = acquirelocalinstances(selectedinstance)
  4547. findlocalinstances(chessinstances, detectedinstanceoptions)
  4548. detectedinstanceoptions.splice(0,0, __default)
  4549. initinstances(selectedinstance)
  4550. detection_state.localInstanceDetected = true;
  4551. }
  4552. catch (e) {
  4553. // console.error(e)
  4554. console.log('No local instances config found in current root = ' + selectedinstance.root);
  4555. console.log('A config will be createed with the instance and environment chosen...')
  4556. // return (async ()=>{return await __default.reposerver})().then(()=>{
  4557. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  4558. // return selectedinstance = Object.assign(__default, selectedinstance);
  4559. // })
  4560. detection_state.localInstanceDetected = false;
  4561. return selectedinstance
  4562. }
  4563. })
  4564. }
  4565. return todo.then( ()=>{
  4566. // PB : TODO -- Embed this in the build instead of inlining it.
  4567. // Also attepmt to load from ../chess-config/...
  4568. // PB : TODO -- OBSOLETEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
  4569. var __repo_manifest_elxr = (require(path.normalize(instanceroot + '/elxr/repo-manifest.js')))(
  4570. 'defaultmanifest' // name
  4571. , { utils, username : selectedinstance.username, instanceName : selectedinstance.instanceName
  4572. , node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver } // options
  4573. )
  4574. __default = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  4575. , __default, __repo_manifest_elxr, {
  4576. // Common baseline repos for all chess instances.
  4577. repos : (()=> {
  4578. var __repos = [
  4579. { repo : 'ember-masonry-grid' /*, branch : master*/ } // Default need not be specified.
  4580. , { repo : 'bbhverse' }
  4581. , { repo : 'clientverse' }
  4582. , { repo : 'serververse' }
  4583. , { repo : 'elxr' }
  4584. , { repo : 'ember-searchable-select' }
  4585. , { repo : 'loopback-component-jsonapi' }
  4586. , { repo : 'loopback-jsonapi-model-serializer' }
  4587. , { repo : 'loopback-connector-mysql' }
  4588. , { repo : 'loopback-connector-ds' }
  4589. , { repo : 'ember-service-worker' }
  4590. , { repo : 'ember-service-worker-asset-cache' }
  4591. , { repo : 'ember-service-worker-cache-fallback' }
  4592. , { repo : 'ember-service-worker-index' }
  4593. , { repo : 'ember-sw-client-route' }
  4594. , { repo : 'global-this' }
  4595. ]
  4596. Array.prototype.push.apply( __repos, __repo_manifest_elxr.repos)
  4597. return __repos;
  4598. })()
  4599. // Requires elevation only in windows
  4600. , elevated : [ { repo : 'chess-server-lib', requiresElevation : true } ]
  4601. , exludeMergeRepos : { }
  4602. }, )
  4603. initinstances(selectedinstance)
  4604. return selectedinstance
  4605. })
  4606. // }
  4607. // else return Promise.resolve(true)
  4608. })
  4609. .then(()=>{
  4610. runconfig = { NODE_ENV: selectedinstance.node_env }
  4611. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  4612. generateDependencies();
  4613. if(noprerequisites[processedArgs._[0]]
  4614. || skipprereqs[processedArgs._[0]]
  4615. ) {
  4616. return elxrworker()
  4617. }
  4618. var neTask = ()=>{
  4619. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`)
  4620. // collect garbage
  4621. return dirs( (dir)=>{
  4622. var matches = /run-(.*)/gm.exec(dir.name)
  4623. if(matches) {
  4624. if(+(matches[1]) < min) {
  4625. min = matches[1]
  4626. collect.splice( 0, 0, matches[1] )
  4627. }
  4628. else collect.push(matches[1])
  4629. }
  4630. return Promise.resolve(collect);
  4631. }, `${selectedinstance.root}/.elxr` )
  4632. .then(()=>{
  4633. // delete garbage
  4634. if(collect.length > retaincount) {
  4635. var asyncs = [];
  4636. while((collect.length - asyncs.length) > retaincount) {
  4637. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  4638. }
  4639. return Promise.all(asyncs)
  4640. }
  4641. else return true
  4642. })
  4643. .catch(e => {
  4644. console.error
  4645. })
  4646. }
  4647. neTask.statuslog = statuslog
  4648. shell_verse.getNonElevatedTask( neTask )()
  4649. var commonTask = ()=>{
  4650. verifyAndInstallPrerequisites.statuslog = statuslog
  4651. if((!skipprerequisites || processedArgs.forceprereqs)) mainTasks.push(verifyAndInstallPrerequisites);
  4652. mainTasks.push(maintask)
  4653. return any(mainTasks);
  4654. }
  4655. return commonTask()
  4656. })
  4657. }
  4658. // return detectInstanceRoot.then(()=>{
  4659. var cmdobj = cmds[selectedinstance.cmd]
  4660. return Promise.all((cmdobj.requires || []).map( (r) => utils.promisify(null, r) ) ).then(()=>{
  4661. if(cmdobj.independentcmd) {
  4662. if(cmdobj.requiresElevation) {
  4663. return cmdobj.cmdFn(cmdobj.toArgs(processedArgs))
  4664. }
  4665. else return cmdobj.cmdFn(cmdobj.toArgs(processedArgs))
  4666. }
  4667. else return startElxr()
  4668. })
  4669. .catch(e => {
  4670. if(typeof e === 'symbol') console.log('error : ' + 'symbol')
  4671. else console.log('error : ' + e)
  4672. })
  4673. // })
  4674. })
  4675. // .then( () => {
  4676. // console.log(process._getActiveHandles());
  4677. // console.log(process._getActiveRequests());
  4678. // })
  4679. // detect if alread installed -> Take no action.
  4680. // download if no installer avalable -> next()
  4681. // install
  4682. function checkandinstall(items) {
  4683. var tasks = []
  4684. items.forEach(item => {
  4685. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  4686. })
  4687. return Promise.all(tasks).then(existances => {
  4688. existances.forEach((exists, i) => {
  4689. if (!exists) {
  4690. return downloadandinstall([items[i]])
  4691. }
  4692. })
  4693. })
  4694. }
  4695. function downloadandinstall(items) {
  4696. var tasks = []
  4697. items.forEach(item => {
  4698. tasks.push(getTaskDownload(item))
  4699. })
  4700. return Promise.all(tasks)
  4701. }
  4702. // Sample instances config.
  4703. // var instances = {
  4704. // "elixir": {
  4705. // "production": {
  4706. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  4707. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  4708. // , "exludeMergeRepos": {
  4709. // "elixir-config-development": true, "elixir-config-test": true
  4710. // , "elixir-config-production": true, "elixir-data": true
  4711. // }
  4712. // , "instanceName": "elixir", "node_env": "production"
  4713. // }
  4714. // },
  4715. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  4716. // }
  4717. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...