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

index.js 223KB

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