Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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