您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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