Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

index.js 156KB

il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 2 ans
il y a 3 ans
il y a 2 ans
il y a 3 ans
il y a 3 ans
il y a 4 ans
il y a 3 ans
il y a 4 ans
il y a 3 ans
il y a 3 ans
il y a 5 ans
il y a 3 ans
il y a 6 ans
il y a 2 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 6 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 4 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 2 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 5 ans
il y a 3 ans
il y a 3 ans
il y a 2 ans
il y a 3 ans
il y a 3 ans
il y a 2 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 2 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 2 ans
il y a 2 ans
il y a 3 ans
il y a 2 ans
il y a 2 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 5 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 6 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128
  1. var path = require('path');
  2. var utils = require('bbhverse');
  3. var any = utils.any;
  4. var Tasq = utils.Tasq
  5. var statuslog = utils.Traq
  6. var Traq = utils.Traq
  7. Tasq.addlistener(statuslog.statuslog)
  8. var cli = require('./cliverse')
  9. var nodeShellExec = cli.nodeShellExec;
  10. var chalk = require('chalk')
  11. const homedir = require('os').homedir();
  12. var ENV = Object.assign({}, process.env); // Shallow clone it.
  13. function sysAddPathVar(path){
  14. // Object.assign({
  15. // inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  16. // }, options)
  17. var newpath = path.split(';');
  18. newpath = Array.from(new Set(newpath.push(path))).join(';')
  19. // path.split(';').forEach(pel => { var kv = pel.split('='); kv[0] === key ? null : newpath.push(pel); } )
  20. return nodeShellExec('setx', ['/m', 'PATH', newpath ]);
  21. }
  22. // singleton one time lazy
  23. var getCredentials = function(){
  24. // First call
  25. var creds = fs.readFileSync(path.normalize(`${homedir}/.elxrcredentials`), { encoding: 'utf8' });
  26. var creds = creds.split('\n').map( c => c.trim() && new URL(c));
  27. console.log(creds);
  28. creds.forEach(cred => {console.log( cred.hostname ); console.log( cred.username )} );
  29. // Subsequent calls
  30. getCredentials = ()=>{ return creds }
  31. return getCredentials();
  32. }
  33. function getCurrentFolder(){
  34. var tasks = [
  35. // () => {
  36. // // Use junctions to avoid npm package issues
  37. // var p = nodeShellExec('cd').then((result)=>{
  38. // console.dir(result)
  39. // }).catch((e) => { console.error(e) })
  40. // return p;
  41. // }
  42. ()=>{
  43. return Promise.resolve(process.cwd())
  44. }
  45. ];
  46. return any(tasks);
  47. }
  48. const __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b'
  49. const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  50. const runtimestamp = (new Date()).getTime();
  51. function getVersion() { return BUILD_VERSION; }
  52. console.log(getVersion());
  53. // 'use strict';
  54. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  55. // PB : TODO --
  56. // runas bypass non elevated tasks when we request privelege
  57. // runas message is always error needs to be fixed.
  58. // runas wait needs to be parallelized.
  59. // suppress elevation check error messages
  60. // support runas lauched directly from shell.
  61. // pass in environment in hta to shellexecute.
  62. // PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
  63. (function () {
  64. "use strict";
  65. if (!Array.prototype.earlyreduce) {
  66. Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
  67. var iterable = this;
  68. var donecallback = donecallback || (a=>a)
  69. var result = { value : initialValue === undefined ? iterable[0] : initialValue };
  70. initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
  71. // function *earlyReduceGenerator(acc, v, i, a) {
  72. for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
  73. var element = iterable[i]
  74. result = eachcallback(result, element, i, iterable)
  75. if(result.done) return donecallback(result)
  76. }
  77. // }
  78. return donecallback(result)
  79. }
  80. }
  81. }());
  82. const { existsSync } = require('fs');
  83. const existslink = function(name, cb){
  84. fs.lstat(name, (error, stats) => {
  85. if (error) {
  86. console.log(error);
  87. cb(error)
  88. }
  89. else {
  90. console.log("Stats object for: example_directory.txt");
  91. console.log(stats);
  92. // Using methods of the Stats object
  93. console.log("Path is file:", stats.isFile());
  94. console.log("Path is directory:", stats.isDirectory());
  95. cb(null, true)
  96. }
  97. });
  98. }
  99. const existsFolderSync = existsSync;
  100. const fs = require('fs')
  101. const cliargs = utils.cliargs;
  102. const processedArgs = cliargs(process.argv.slice(2));
  103. console.dir(processedArgs)
  104. // PB : TODO -- defaults for valuless arguments if passed.
  105. // Object.keys(processedArgs).forEach(a=>{
  106. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  107. // }
  108. // })
  109. //
  110. // Object.keys(clioverrides).forEach( prop => { })
  111. var globSync = require('glob').sync;
  112. const { readdir } = require("fs").promises
  113. // Directory shallow walk and do perform on each dir.
  114. const dirs = async (perform, path) => {
  115. for (const dir of await readdir(path || selectedinstance.root, { withFileTypes: true })) {
  116. if (dir.isDirectory()) perform(dir)
  117. }
  118. }
  119. var templateprocess = function(str, substitutes){
  120. const regex = /__(.*?)__/gm;
  121. // const str = `__link____instance__server-lib__name__`;
  122. let m;
  123. return str.replace(regex, function(match, key) {
  124. console.log(`Found match, group ${match}: ${key}`);
  125. return substitutes[key] || match;
  126. })
  127. // while ((m = regex.exec(str)) !== null) {
  128. // // This is necessary to avoid infinite loops with zero-width matches
  129. // if (m.index === regex.lastIndex) {
  130. // regex.lastIndex++;
  131. // }
  132. // var rstr = str;
  133. // // The result can be accessed through the `m`-variable.
  134. // m.forEach((match, groupIndex) => {
  135. // // rstr = rstr.replace( groupIndex
  136. // console.log(`Found match, group ${groupIndex}: ${match}`);
  137. // if(groupIndex === 0) return
  138. // });
  139. // }
  140. }
  141. function copyFileSync( source, target , options) {
  142. var targetFile = target;
  143. // If target is a directory, a new file with the same name will be created
  144. if ( fs.existsSync( target ) ) {
  145. if ( fs.lstatSync( target ).isDirectory() ) {
  146. targetFile = path.join( target, path.basename( source ) );
  147. }
  148. }
  149. fs.writeFileSync(targetFile, fs.readFileSync(source));
  150. }
  151. function copyFolderRecursiveSync( source, target, options ) {
  152. var files = [];
  153. // Check if folder needs to be created or integrated
  154. var targetFolder = path.join( target, path.basename( source ) );
  155. if ( !fs.existsSync( targetFolder ) ) {
  156. fs.mkdirSync( targetFolder );
  157. }
  158. // Copy
  159. if ( fs.lstatSync( source ).isDirectory() ) {
  160. files = fs.readdirSync( source );
  161. files.forEach( function ( file ) {
  162. var curSource = path.join( source, file );
  163. if ( fs.lstatSync( curSource ).isDirectory() ) {
  164. copyFolderRecursiveSync( curSource, targetFolder );
  165. } else {
  166. copyFileSync( curSource, targetFolder );
  167. }
  168. } );
  169. }
  170. }
  171. var getShellTask = (command, args, options) => {
  172. options = options || {}
  173. var callshell = command === 'rm' ? getgitbashtask : getshelltask;
  174. return () => {
  175. var p = callshell( [command, args, Object.assign({
  176. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  177. }, options)
  178. ])()
  179. if (options.ignorefailures) {
  180. return p.catch(e => {
  181. // Ignore. Not a major error.
  182. })
  183. }
  184. else return p;
  185. }
  186. }
  187. var callshelltask = (args) => {
  188. // console.dir(args)
  189. if( Object.prototype.toString.call(args) === '[object Function]' ) {
  190. return args;
  191. }
  192. return getshelltask(args)()
  193. }
  194. var getshelltask = (args) => {
  195. return args[0] === 'rm' ? getgitbashtask(args) : () => { return nodeShellExec.apply(null, args) } }
  196. var getgitbashtask = (args) => { return () => {
  197. return nodeShellExec( `"${gitbash}"`, ['-c', `"${args[0]} ${args[1].join(' ')}"`], args[2]) }
  198. }
  199. var getTaskCheckExists = (command, options) => {
  200. options = options || {}
  201. return () => {
  202. var p = nodeShellExec.apply(null, ['where', [command]])
  203. if (options.ignorefailures) {
  204. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  205. return false;
  206. })
  207. }
  208. else return p.then(() => { return true });
  209. }
  210. }
  211. var getTaskWithElevation = function(tasdef){
  212. return ()=>{
  213. if (__isElevated) {
  214. return tasdef.elevatedpulltasks().then(()=>{
  215. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  216. fs.writeFileSync('run.done', 'success')
  217. }).catch(e=>{
  218. fs.writeFileSync('run.done', 'failure')
  219. });
  220. }
  221. else {
  222. // PB : TODO -- Rename op['runas'] to 'elevate'
  223. var __runasresult = null;
  224. return op['runas']().then((r) => { return __runasresult = r; })
  225. .catch((e) => {
  226. console.error(e)
  227. })
  228. .finally(() => {
  229. if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done')
  230. if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
  231. })
  232. }
  233. }
  234. }
  235. var getTaskWithoutElevation = function(tasdef){
  236. return ()=>{
  237. if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  238. else Promise.resolve(true)
  239. }
  240. }
  241. var gitops = {
  242. getdiscoverbranchcmd : function(repo){
  243. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  244. var cmd = [gitbash
  245. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  246. , { cwd: instanceroot + '/' + repo, title: 'discoverbranch for ' + repo + ' ' + parameters.join(' ') }]
  247. return cmd
  248. }
  249. }
  250. var getPullCmd = (repo, branch) => {
  251. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  252. // console.log(useGitPull)
  253. var pullCmd = []
  254. if(!branch) {
  255. // console.warn('No branch was specified detecting from working client.')
  256. // First check if working client exists.
  257. // if (existsSync(instanceroot + '/' + repo)) {
  258. pullCmd= gitops.getdiscoverbranchcmd(repo)
  259. // }
  260. // else performpull
  261. }
  262. // var pullCmd = [gitInstallDir
  263. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  264. // , { cwd: instanceroot + '/' + repo, title: 'pull all remotes for ' + repo }]
  265. if(branch) {
  266. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  267. var pullCmd = [ gitbash
  268. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  269. , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  270. }
  271. // var pullCmd = ['pullall', [], { cwd : repo }]
  272. if (useGitPull) pullCmd = ['git', ['pull'], {
  273. inherit: true, shell: true,
  274. cwd: instanceroot + '/' + repo
  275. // , env: process.env
  276. , runas: processedArgs.runas
  277. , title: `git pull ${repo}`
  278. }]
  279. return pullCmd
  280. }
  281. var performPull = (repo, branch, repoowner, errHandler) => {
  282. // PB : TODO -- Handle no branch passed in case.
  283. // if(!branch) { throw 'No branch specified' }
  284. try{
  285. var exists = existsSync(instanceroot + '/' + repo)
  286. }
  287. catch(e){
  288. exists = false
  289. console.log(e)
  290. }
  291. if (exists) {
  292. var branchprint = branch ? ' branch :' + branch : '';
  293. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  294. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  295. if (__isElevated) {
  296. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  297. }
  298. else statuslog.statuslog(null, repo)
  299. return true;
  300. })
  301. .catch((e) => {
  302. e.repo = repo;
  303. if(errHandler) throw errHandler(e)
  304. if (__isElevated) {
  305. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  306. }
  307. else statuslog.statuslog(e);
  308. // console.error(e)
  309. throw e;
  310. })
  311. }
  312. else {
  313. console.log('cloning ' + repo)
  314. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  315. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${repoowner || defaultRepoOwner}/` + repo + '.git'],
  316. {
  317. inherit: true, shell: true,
  318. env: process.env
  319. , cwd : instanceroot
  320. , runas: processedArgs.runas
  321. }).then(() => {
  322. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  323. {
  324. inherit: true, shell: true,
  325. env: process.env
  326. , cwd: instanceroot + '/' + repo
  327. , runas: processedArgs.runas
  328. , title: `'git', ${['config', '--replace-all', 'core.symlinks', selectedinstance.username].join(' ')}`
  329. })
  330. .then(() => {
  331. if (__isElevated) {
  332. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  333. }
  334. else statuslog.statuslog(null, repo)
  335. })
  336. .catch((e) => {
  337. e.repo = repo;
  338. if (__isElevated) {
  339. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  340. }
  341. else statuslog.statuslog(e);
  342. })
  343. })
  344. .catch(e => {
  345. e.repo = repo;
  346. if(errHandler) throw errHandler(e)
  347. if (__isElevated) {
  348. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  349. }
  350. else statuslog.statuslog(e);
  351. throw e
  352. })
  353. }
  354. }
  355. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  356. // -- Currently workaround is to always run from a non-elevated shell.
  357. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  358. var acquireElevationState = () => {
  359. if (__isElevated === null) {
  360. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  361. inherit: true
  362. // , shell: true
  363. , stdio: 'ignore'
  364. , env: process.env
  365. , title: `check privileged execution mode using "fsutil dirty query C:"`
  366. }).then((exitcode) => {
  367. console.log('Elevated')
  368. __isElevated = true;
  369. return true;
  370. }).catch(() => {
  371. __isElevated = false;
  372. console.log('Not Elevated');
  373. return false;
  374. });
  375. }
  376. else return Promise.resolve(__isElevated);
  377. }
  378. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current GITEA username
  379. var defaultRepoOwner = 'chess';
  380. var elevatedRunasRepos = null
  381. var gitRepos = null
  382. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  383. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  384. var dbForLabel = function (label) {
  385. var dbsForLabel = {
  386. devmysql: 'mysql'
  387. , development: 'mssql'
  388. , production: 'mssql'
  389. }
  390. return dbsForLabel[label] || 'mysql'
  391. }
  392. // SAM : TODO Use nodeshellexec where to detect git installation dir
  393. var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe"
  394. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  395. // Relevant git repos
  396. var exludeMergeRepos = [];
  397. var useGitPull = processedArgs.useGitPull || false;
  398. var configPromise = null
  399. var op = {
  400. 'h': () => { console.log(elxr.help()); return '-h' }
  401. , 'clean' : () => {
  402. // delete all node_module folders and links.
  403. var tasklist = [];
  404. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot )
  405. return Promise.all(tasklist)
  406. }
  407. // , 'undefined': () => { return acquireChoices( {} ); }
  408. , 'reset': () => {
  409. // Reset NPM packages semver so major versions can be updated.
  410. const fs = require('fs')
  411. const wipeDependencies = (__package) => {
  412. const file = fs.readFileSync(__package + '/package.json')
  413. const content = JSON.parse(file)
  414. for (var devDep in content.devDependencies) {
  415. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  416. content.devDependencies[devDep] = '*';
  417. }
  418. }
  419. for (var dep in content.dependencies) {
  420. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  421. content.dependencies[dep] = '*';
  422. }
  423. }
  424. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  425. }
  426. var repos = ['client'];
  427. // repos = gitRepos;
  428. repos.forEach(wipeDependencies)
  429. // if (require.main === module) {
  430. // } else {
  431. // module.exports = wipeDependencies
  432. // }
  433. }
  434. , 'upgrade': () => {
  435. console.log('upgrade.......')
  436. var tasks = [
  437. () => {
  438. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  439. inherit: true, shell: true
  440. , env: process.env
  441. }).catch((e) => { console.error(e) })
  442. p.position = 1;
  443. console.log('One')
  444. return p;
  445. }
  446. , () => {
  447. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  448. inherit: true, shell: true
  449. , env: process.env
  450. }).catch((e) => { console.error(e) })
  451. p.position = 2;
  452. console.log('Two')
  453. return p;
  454. }
  455. , () => {
  456. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  457. inherit: true, shell: true
  458. , env: process.env
  459. }).catch((e) => { console.error(e) })
  460. p.position = 3;
  461. console.log('Three')
  462. return p;
  463. }
  464. , () => {
  465. var p = nodeShellExec('n', ['latest'], {
  466. inherit: true, shell: true
  467. , env: process.env
  468. }).catch((e) => { console.error(e) })
  469. p.position = 4;
  470. console.log('Four')
  471. return p;
  472. }
  473. ]
  474. any(tasks)
  475. console.log('.......done')
  476. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  477. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  478. console.info('Uninstalling existing ember globally');
  479. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  480. stdio: ['pipe', process.stdout, process.stderr],
  481. inherit: true,
  482. shell: true,
  483. cwd: path.dirname(__dirname),
  484. env: env
  485. })
  486. step1.on('close', () => {
  487. console.info('Installing ember globally');
  488. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  489. stdio: ['pipe', process.stdout, process.stderr],
  490. inherit: true,
  491. shell: true,
  492. cwd: path.dirname(__dirname),
  493. env: env
  494. })
  495. step2.on('close', () => {
  496. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  497. stdio: ['pipe', process.stdout, process.stderr],
  498. inherit: true,
  499. shell: true,
  500. cwd: path.dirname(__dirname),
  501. env: env
  502. })
  503. })
  504. })
  505. }
  506. , 'runas': () => {
  507. if(processedArgs.skipelevated) return Promise.resolve({ skipped : true });
  508. console.log('Testing Elevation')
  509. if (__isElevated) {
  510. try {
  511. op[processedArgs.label || processedArgs._[0] || 'undefined']()
  512. }
  513. catch (e) {
  514. console.error('Error Invalid command : ' + e)
  515. fs.writeFileSync('run.done', 'error')
  516. }
  517. finally {
  518. }
  519. }
  520. else {
  521. console.log('Requesting Elevated Privileges');
  522. // Wait for the runas to complete before we read it.
  523. try {
  524. fs.unlinkSync('run.done')
  525. fs.unlinkSync('run.log')
  526. }
  527. catch (e) { } //Ignore
  528. // Find node path to send to hta.
  529. return nodeShellExec('where', ['node']).then(r => {
  530. var namedArgs = [];
  531. console.log('result : ' + JSON.stringify(r))
  532. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; })
  533. // PB : TODO -- Convert all the cli args back to string.
  534. var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  535. // args.push('--nodepath=' + r.messages[r.messages.length - 1])
  536. // if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
  537. // if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
  538. console.dir(processedArgs)
  539. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  540. , {
  541. inherit: true
  542. , shell: true
  543. , env: ENV
  544. , runas: 'self'
  545. , title: `runas`
  546. }
  547. ).then(() => {
  548. // runas returned.
  549. try {
  550. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  551. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  552. runaslog.forEach((logEntry) => {
  553. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry)
  554. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  555. })
  556. }
  557. catch (e) {
  558. // We must have a runas log
  559. statuslog.statuslog(e)
  560. console.error('Run log error probably was not created by runas : ' + e)
  561. }
  562. })
  563. .catch(err => console.error('Elevation failed : ' + err));
  564. })
  565. }
  566. }
  567. , 'push': () => {
  568. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  569. // init remote bare from local
  570. // pushandinitremotebare
  571. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  572. // connect to repo server -- net use 172.16.0.27
  573. // cd 172.16.0.27/repos/
  574. // mkdir repo.git
  575. // cd repo.git
  576. // git init --bare
  577. // cd localrepo
  578. // git remote rename origin githubclone
  579. // git remote add origin //172.16.0.27/repos/repo.git
  580. // git push origin master
  581. var repo = processedArgs._[1];
  582. var sequentialTaskShellCommands = [];
  583. if (!existsSync(`Z:/${repo}.git`)) {
  584. sequentialTaskShellCommands = [
  585. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  586. // inherit : true, shell: true
  587. // , env: process.env
  588. // }]
  589. ['pwd', { cwd: 'Z:', inherit: true }]
  590. , ['mkdir', [`${repo}.git`], {
  591. cwd: `Z:`
  592. , inherit: true, shell: true
  593. , env: process.env
  594. }]
  595. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  596. , ['git', ['init', '--bare'], {
  597. cwd: `Z:/${repo}.git`
  598. , inherit: true, shell: true
  599. , env: process.env
  600. }]
  601. // PB : TODO -- Do this conditionally only...
  602. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  603. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  604. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  605. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  606. // PB : TODO -- If threre is a gitbubclone origin
  607. // Set the master to pull from the local repo.
  608. ]
  609. if (!existsSync(`Z:`)) {
  610. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  611. inherit: true, shell: true
  612. , env: process.env
  613. }])
  614. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  615. // throw 'done'
  616. }
  617. }
  618. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }])
  619. // console.dir(sequentialTaskShellCommands);
  620. var tasks = [];
  621. sequentialTaskShellCommands.forEach(shellcmd => {
  622. // console.log(shellcmd)
  623. tasks.push(() => {
  624. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
  625. return p;
  626. })
  627. })
  628. any(tasks);
  629. }
  630. , 'is-git-repo': (dir) => {
  631. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  632. }
  633. // git remote equivalents...
  634. // git branch --set-upstream-to=elixir-unc/master master
  635. // git push --set-upstream elixir-unc branch..
  636. , 'remote': (args) => {
  637. // Subcommands!
  638. // PB : TODO -- we can now pass in hypehnated args...
  639. if(!processedArgs.v) return false; // Only -v is supported presently..
  640. var serial_perform = (repo) => {
  641. var options = { cwd: instanceroot + '/' + repo }
  642. return [
  643. ['git', ['remote', '-v'], options]
  644. ]
  645. }
  646. var x = (args) => {
  647. var tasq = () => {
  648. // console.log(args)
  649. return nodeShellExec.apply(null, args).catch(e => {
  650. // We continue on failure.
  651. console.error(tasq.toString())
  652. })
  653. }
  654. tasq.toString = function(){
  655. return JSON.stringify(args)
  656. }
  657. return tasq;
  658. }
  659. var perform = (dir) => {
  660. return any(serial_perform(dir.name).map(x))
  661. }
  662. dirs(perform)
  663. }
  664. , 'remote set-url': (args) => {
  665. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  666. var __args = {
  667. remotename : args.remotename || processedArgs._[2]
  668. , url : args.url || processedArgs._[3]
  669. }
  670. // pushable doesn't mean the remote doesn't support being pushed to.
  671. // 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.
  672. // PB : TODO -- change this to enablepushing.
  673. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  674. var pushable = processedArgs.pushable || false;
  675. remotename = __args.remotename
  676. url = __args.url
  677. var serial_perform_git_seturl = (repo) => {
  678. var options = { cwd: instanceroot + '/' + repo }
  679. // console.log(repo)
  680. if (pushable) {
  681. return [
  682. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  683. , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  684. ]
  685. }
  686. else {
  687. return [
  688. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  689. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  690. ]
  691. }
  692. }
  693. var x = (args) => {
  694. var tasq = () => {
  695. // console.log(args)
  696. return nodeShellExec.apply(null, args).catch(e => {
  697. // We continue on failure.
  698. console.error(tasq.toString())
  699. })
  700. }
  701. tasq.toString = function(){
  702. return JSON.stringify(args)
  703. }
  704. return tasq;
  705. }
  706. var perform_git_seturl = (dir) => {
  707. op['is-git-repo'](dir).then((logEntry) => {
  708. return any(serial_perform_git_seturl(dir.name).map(x))
  709. }).catch((e) => {
  710. // console.log('Failed : ' + dir.name)
  711. })
  712. }
  713. dirs(perform_git_seturl)
  714. }
  715. // , 'reset' : ()=>{
  716. // PB : TODO -- Cant have 2 resets !! | There is an npm reset that should be bundled.
  717. // // Reset the whole installation pertaining to this elxr folder.
  718. // }
  719. , 'remote exists': (args) => {
  720. var __args = {
  721. remotename : args.remotename|| processedArgs._[2]
  722. , url : args.url || processedArgs._[3]
  723. , branch : args.branch || processedArgs._[4]
  724. }
  725. var options = args.repo ? { cwd: instanceroot + '/' + args.repo } : {}
  726. // PB : TODO -- We should evaluate a whole list of remotes passed in from args instead of just one.
  727. var commands = [
  728. // git remote -v| while read remote; do "${remote#origin/}" "$remote"; done
  729. // ['git', ['remote', '-v', '| while read remote; do "${remote#origin/}" "$remote"; done'], utils.assign( {
  730. ['git', ['remote', '-v'], utils.assign( {
  731. evaluateResult : function(err, result){
  732. // var found = result.messages.find( (r)=> { return r.includes( __args.remotename ) })
  733. var remotes = []
  734. var found = false;
  735. console.dir(result.messages)
  736. console.log(result + '---------------')
  737. result.messages.forEach( (line)=> {
  738. console.log(line + '$$$$$$$$$$$$$$$$$$$$')
  739. var matches = line.match(/(.*)?\s\s([^\(]*)?\s?\(?([^\)]*)\)?/);
  740. if(matches) {
  741. var remote = {};
  742. remote[matches[1]] = matches[2];
  743. if( (!matches[3].trim() || matches[3].trim() === 'fetch') && matches[1].trim() === remotename.trim()) {
  744. found = true;
  745. result.url = remote[remotename];
  746. }
  747. }
  748. })
  749. console.dir(remotes)
  750. return [
  751. found
  752. , result
  753. ]
  754. }
  755. } , options) ]
  756. , function(prevserialtaskresult) {
  757. console.log('================================')
  758. var url = __args || prevserialtaskresult.url;
  759. console.dir(prevserialtaskresult)
  760. return getshelltask(['git', ['ls-remote', url], utils.assign( {
  761. evaluateResult : function(err, result){
  762. // fatal: unable to access '${__args.url}/': Failed to connect to git.bbh port 80 after 21025 ms: Timed out
  763. // `fatal: repository '${__args.url}/' not found`
  764. var hasfailed = /^fatal: .*/.test(result.messages.join(' '))
  765. return [
  766. !hasfailed, result
  767. ]
  768. }
  769. } , options) ])()
  770. }
  771. ]
  772. var mapped = commands.map(callshelltask) //.map( p => p.catch(e => e)) // Handle errors later.
  773. return any(mapped).then( allresolved =>{
  774. console.dir(allresolved)
  775. !allresolved[0][0] && !allresolved[1][0] ? console.log('was not added as a remote and url is currently inaccessible.')
  776. : allresolved[0][0] && allresolved[1][0] ? console.log('was added as a remote and url is accessible.')
  777. : allresolved[0][0] && !allresolved[1][0] ? console.log('was added as a remote but url is currently inaccessible.')
  778. : console.log('was not added as a remote but url is currently accessible.')
  779. return !allresolved[0][0] && !allresolved[1][0] ? [0, 0]
  780. : allresolved[0][0] && allresolved[1][0] ? [1, 1] // => was added as a remote and url is accessible.
  781. : allresolved[0][0] && !allresolved[1][0] ? [1, 0] // => was added as a remote but url is currently inaccessible.
  782. : [0, 1] // => was not added and remote and url is accessible.
  783. })
  784. }
  785. , 'remote refresh': (args) => {
  786. var __args = {
  787. remotename : args.remotename|| processedArgs._[2]
  788. , url : args.url || processedArgs._[3]
  789. , branch : args.branch || processedArgs._[4]
  790. }
  791. // use the repo manifest to create missing remotes.
  792. function perform_remote_refresh(dir){
  793. var repo = dir.name
  794. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  795. try {
  796. var remotes = require(`${selectedinstance.root}/${dir.name}/repo-manifest.js`)( null, selectedinstance).remotes || [];
  797. }
  798. catch(e){
  799. var remotes = []
  800. }
  801. // console.log(`${dir.name}/repo-manifest.js` + '---------------------------')
  802. // console.dir(remotes)
  803. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  804. console.log('Processing : ' + dir.name)
  805. var branch = __branch
  806. __args.repo = repo
  807. __args.branch = __branch
  808. var promises = []
  809. remotes.forEach(remote =>{
  810. Object.keys(remote).forEach(remotename => {
  811. __args.remotename = remotename
  812. __args.url = remote[remotename]
  813. promises.push( op['remote exists']( __args ).then( exists => {
  814. if(!exists[0]) {
  815. if(!exists[1]) { console.error( `Skipping inaccessible remote url ${__args.url}` ) }
  816. else return op['remote add']( { remotename,
  817. // PB : TODO -- use the most accessible remote instead of the first available.
  818. url : (utils.js.isArray(remote[remotename]) ? remote[remotename][0] : remote[remotename]), branch
  819. } )
  820. }
  821. })
  822. )
  823. })
  824. })
  825. return Promise.all(promises)
  826. })
  827. .catch((e) => { console.log('Processing Error : ' + dir.name); console.error(e); return { error: true, message: repo } })
  828. }
  829. return dirs(perform_remote_refresh)
  830. }
  831. , 'remote add': (args) => {
  832. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  833. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  834. // That explicitly has a remote name prefix.
  835. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  836. // git branch branch_name -u your_new_remote/branch_name -- older versions
  837. // git branch -vv -- Detect which branch are we tracking.
  838. // default upstream should be users own fork.
  839. // Also need alias branches to
  840. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  841. // probably git merge from all remotes... and relevant branches...
  842. // alias pushall='for i in `git remote`; do git push $i; done;'
  843. // alias pullall='for i in `git remote`; do git pull $i; done;'
  844. // args === processedArgs ? args = {} : null;
  845. var __args = {
  846. remotename : args.remotename|| processedArgs._[2]
  847. , url : args.url || processedArgs._[3]
  848. , branch : args.branch || processedArgs._[4]
  849. }
  850. var remotename = __args.remotename
  851. var url = __args.url
  852. var branch = __args.branch
  853. var pushable = processedArgs.pushable || false;
  854. var serial_perform_git_add = (repo) => {
  855. var options = { cwd: instanceroot + '/' + repo }
  856. // console.log(repo)
  857. if (pushable) {
  858. return [
  859. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  860. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  861. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  862. ]
  863. }
  864. else {
  865. return [
  866. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  867. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  868. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  869. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  870. ]
  871. }
  872. }
  873. var x = (args) => {
  874. return () => {
  875. // console.log(args)
  876. return nodeShellExec.apply(null, args)
  877. }
  878. // return Promise.resolve(true)
  879. }
  880. var perform_git_add = (dir) => {
  881. op['is-git-repo'](dir).then((logEntry) => {
  882. // console.log(code)
  883. if (logEntry.success) {
  884. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  885. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  886. })
  887. .catch((e) => {
  888. any(serial_perform_git_add(dir.name).map(x))
  889. })
  890. }
  891. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  892. }).catch((e) => {
  893. console.log('Failed : ' + dir.name)
  894. })
  895. }
  896. const { readdir } = require("fs").promises
  897. dirs(perform_git_add)
  898. }
  899. , 'remote remove': (args) => {
  900. var __args = {
  901. remotename : args.remotename|| processedArgs._[2]
  902. }
  903. var remotename = __args.remotename
  904. var serial_perform_git_remove = (repo) => {
  905. var options = { cwd: instanceroot + '/' + repo }
  906. // console.log(repo)
  907. return [
  908. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  909. ]
  910. }
  911. var x = (args) => {
  912. return () => {
  913. // console.log(args)
  914. return nodeShellExec.apply(null, args)
  915. }
  916. // return Promise.resolve(true)
  917. }
  918. var perform_git_remove = (dir) => {
  919. op['is-git-repo'](dir).then((logEntry) => {
  920. // console.log(code)
  921. if (logEntry.success) {
  922. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  923. any(serial_perform_git_remove(dir.name).map(x))
  924. })
  925. .catch((e) => {
  926. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`)
  927. })
  928. }
  929. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  930. }).catch((e) => {
  931. // console.log('Failed : ' + dir.name)
  932. })
  933. }
  934. const { readdir } = require("fs").promises
  935. dirs(perform_git_remove)
  936. }
  937. , 'init-gitea': (user) => {
  938. user = user || processedArgs._[1]
  939. if (!user) throw 'User name required'
  940. var serial_perform_init_gitea = (repo) => {
  941. var options = { cwd: instanceroot + '/' + repo }
  942. // console.log(repo)
  943. return [
  944. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  945. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  946. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  947. ]
  948. }
  949. var x = (args) => {
  950. return () => {
  951. // console.log(args)
  952. return nodeShellExec.apply(null, args)
  953. }
  954. // return Promise.resolve(true)
  955. }
  956. var perform_init_gitea = (dir) => {
  957. op['is-git-repo'](dir).then((logEntry) => {
  958. // console.log(code)
  959. if (logEntry.success) {
  960. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  961. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  962. })
  963. .catch((e) => {
  964. any(serial_perform_init_gitea(dir.name).map(x))
  965. })
  966. }
  967. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  968. }).catch((e) => {
  969. // console.log('Failed : ' + dir.name)
  970. })
  971. }
  972. const { readdir } = require("fs").promises
  973. dirs(perform_init_gitea)
  974. }
  975. , 'syncmaster': (label) => {
  976. // Usage :
  977. // elxr pull -- Defaults to run config
  978. var env = Object.assign({}, process.env); // Shallow clone it.
  979. // console.dir(env)
  980. console.log('Running exlr pull : ' + path.dirname(__dirname))
  981. if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'))
  982. if (__isElevated) {
  983. return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
  984. fs.writeFileSync('run.done', 'success')
  985. }).catch(() => {
  986. fs.writeFileSync('run.done', 'error')
  987. })
  988. }
  989. else return op['runas']()
  990. }
  991. , 'repo-relocate' : function(args){
  992. // relocate a subfolder in source repo to same subfolder in target repo with history.
  993. var args = args || {
  994. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  995. , folder : processedArgs._[3] || 'server'
  996. , sourcerepo : processedArgs._[2] || 'client'
  997. , targetrepo : processedArgs._[1] || 'elixir-server'
  998. }
  999. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  1000. // , stdio: ['pipe', process.stdout, process.stderr]
  1001. , inherit: true,
  1002. shell: true,
  1003. env: process.env
  1004. , runas: processedArgs.runas
  1005. }
  1006. return op['repo-split'](args).then(()=>{
  1007. return op['repo-merge'](args).then(()=>{
  1008. // cleanup folder from source.
  1009. var cmdseq = [
  1010. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  1011. // commits have to intentional...
  1012. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  1013. ]
  1014. return any(cmdseq.map(getshelltask))
  1015. })
  1016. }).catch(e=>{console.error(e)})
  1017. }
  1018. , 'repo-split' : function(args) {
  1019. // https://gist.github.com/smdabdoub/17065c348289158277b5
  1020. /**
  1021. * Eg : folder, remotebase, sourcerepo, targetrepo
  1022. * args.folder = 'server'
  1023. * args.remotebase = 'https://git.bbh/chess/'
  1024. * args.sourcerepo = 'client'
  1025. * args.targetrepo = 'elixir-server'
  1026. */
  1027. var args = args || {
  1028. folder : 'server'
  1029. , remotebase : 'http://git.bbh/chess/'
  1030. , sourcerepo : 'client'
  1031. , targetrepo : 'elixir-server'
  1032. }
  1033. var options = { cwd: `${instanceroot}/relocate`
  1034. // , stdio: ['pipe', process.stdout, process.stderr]
  1035. , inherit: true,
  1036. shell: true,
  1037. env: process.env
  1038. , runas: processedArgs.runas
  1039. }
  1040. var cmdseq = [
  1041. // create a temporary working dir in current folder where we started execution.
  1042. ['mkdir', [ '-p', `${instanceroot}/relocate`]]
  1043. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  1044. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  1045. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  1046. ]
  1047. return any(cmdseq.map(getshelltask)).then(() => {
  1048. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  1049. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  1050. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  1051. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  1052. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  1053. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  1054. // subtree split and filter-branch are options. We currently use repo-filter.
  1055. return op['filter-repo'](args)
  1056. }).catch(e=>{console.error(e); throw 'failed'})
  1057. }
  1058. , 'repo-merge' : function(args) {
  1059. // Merge source repo into target repo
  1060. var args = args || {
  1061. folder : 'server'
  1062. , remotebase : 'http://git.bbh/chess/'
  1063. , sourcerepo : 'client'
  1064. , targetrepo : 'elixir-server'
  1065. }
  1066. var sourcerepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  1067. // , stdio: ['pipe', process.stdout, process.stderr]
  1068. , inherit: true,
  1069. shell: true,
  1070. env: process.env
  1071. , runas: processedArgs.runas
  1072. }
  1073. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  1074. // , stdio: ['pipe', process.stdout, process.stderr]
  1075. , inherit: true,
  1076. shell: true,
  1077. env: process.env
  1078. , runas: processedArgs.runas
  1079. }
  1080. var cmdseq = [
  1081. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  1082. , targetrepooptions ]
  1083. // , ['git', ['push', targetrepooptions ] // manual push for now..
  1084. ]
  1085. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e)})
  1086. }
  1087. , 'filter-repo' : function(args){
  1088. // Merge source repo into target repo
  1089. var args = args || {
  1090. folder : 'server'
  1091. , remotebase : 'http://git.bbh/chess/'
  1092. , targetrepo : 'elixir-server'
  1093. }
  1094. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  1095. , inherit: true, shell: true
  1096. , env: process.env
  1097. , runas: processedArgs.runas
  1098. }
  1099. var cmdseq = [
  1100. // git checkout -b feature/merge-old-project
  1101. // git remote add src-project ../src-project
  1102. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  1103. ]
  1104. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e); throw 'failed' })
  1105. }
  1106. , 'filter-branch' : function(preservefolder, repo){
  1107. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  1108. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  1109. // Preserve a specific folder.
  1110. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  1111. /*
  1112. git clone repo reposplit
  1113. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  1114. git remote rm origin
  1115. */
  1116. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  1117. }
  1118. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  1119. // // Merge repo2 into a subfolder in repo1
  1120. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  1121. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  1122. // /*
  1123. // cd repo1
  1124. // git remote add -f tempmergesource ../{{mergesource}}/.git
  1125. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  1126. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  1127. // git commit
  1128. // // Repair History
  1129. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  1130. // #!/usr/bin/env bash
  1131. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  1132. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  1133. // subdir=server
  1134. // git filter-branch --tree-filter '
  1135. // first='"$first"'
  1136. // last='"$last"'
  1137. // subdir='"$subdir"'
  1138. // log_file=/tmp/filter.log
  1139. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  1140. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  1141. // echo "=== $GIT_COMMIT: making changes"
  1142. // files=$(git ls-tree --name-only $GIT_COMMIT)
  1143. // mkdir -p $subdir
  1144. // for i in $files; do
  1145. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  1146. // done
  1147. // else
  1148. // echo "=== $GIT_COMMIT: ignoring"
  1149. // fi \
  1150. // >> $log_file
  1151. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  1152. // status=0 # tell tree-filter never to fail
  1153. // '
  1154. // git remote rm tempmergesource
  1155. // */
  1156. // // better alternative for history
  1157. // /**
  1158. // *
  1159. // git clone git@server.com:old-project.git
  1160. // git clone git@server.com:new-project.git
  1161. // cd old-project
  1162. // mkdir old-project
  1163. // git mv !(old-project) old-project
  1164. // ls -la and gt mv hidden files ....
  1165. // git commit -a -S -m “Moving old project into its own subdirectory”
  1166. // cd ../new-project
  1167. // git remote add old-project ../old-project
  1168. // git fetch old-project
  1169. // git checkout -b feature/merge-old-project
  1170. // git merge -S --allow-unrelated-histories old-project/master
  1171. // git push origin feature/merge-old-project
  1172. // git remote rm old-project
  1173. // */
  1174. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  1175. // }
  1176. , 'pull' : (label) => {
  1177. // Usage :
  1178. // elxr pull -- Defaults to run config
  1179. return elxr.getpulltask(selectedinstance)()
  1180. }
  1181. , 'isInstalled': () => {
  1182. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  1183. console.log(processedArgs._[1] + ' exists.')
  1184. return true;
  1185. });
  1186. }
  1187. , 'c' : ()=>{
  1188. }
  1189. , 'i' : () => {
  1190. var tasks = []
  1191. // tasks.push(op['pull']);
  1192. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
  1193. tasks.push(op['use'])
  1194. if (!__isElevated) {
  1195. tasks.push(op['npmi'])
  1196. }
  1197. // var tasksdefs = [
  1198. // ['elxr', ['pull']]
  1199. // , ['elxr', ['use', 'elixir']]
  1200. // , ['elxr', ['npmi']]
  1201. // ]
  1202. // tasksdefs.forEach(tasksdef=>{
  1203. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  1204. // })
  1205. return any(tasks);
  1206. }
  1207. , 'npmi': () => {
  1208. var tasks = [];
  1209. // Build fails without babel...
  1210. tasks.push(getShellTask(
  1211. 'npm',[ 'i', '-g', 'babel-cli' ]
  1212. ) )
  1213. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  1214. // npmbuildrepos = []
  1215. npmbuildrepos.forEach(repo => {
  1216. tasks.push(() => {
  1217. return nodeShellExec('npm', ['i --force'], {
  1218. inherit: true, shell: true
  1219. , cwd: instanceroot + '/' + repo
  1220. , env: process.env
  1221. , title: `npm i for ${repo}`
  1222. }).catch((e) => {
  1223. console.error('Ignoring Benign Error'); console.error(e);
  1224. }).then(() => {
  1225. console.log(`--npm run build for ${repo}--------------------`)
  1226. return nodeShellExec('npm', ['run build'], {
  1227. inherit: true, shell: true
  1228. , cwd: instanceroot + '/' + repo
  1229. , env: process.env
  1230. , title: `npm run build for ${repo}`
  1231. }).then(Tasq.then).catch(Tasq.catch)
  1232. })
  1233. })
  1234. })
  1235. return any(tasks).then(() => {
  1236. gitRepos.push({ repo : 'chess-server-lib/server'});
  1237. gitRepos = gitRepos.concat(elevatedRunasRepos);
  1238. // console.dir(gitRepos)
  1239. // throw ""
  1240. // gitRepos = [
  1241. // // 'bbhverse', 'serververse', 'elixir-server',
  1242. // // 'clientverse',
  1243. // 'client'
  1244. // ];
  1245. var rmtasks = []
  1246. var repotasks = []
  1247. var env = Object.assign({}, process.env)
  1248. delete env.NODE_ENV
  1249. gitRepos.forEach(repodef => {
  1250. rmtasks.push(
  1251. // () => {
  1252. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1253. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  1254. callshelltask(['rm', ['package-lock.json'], {
  1255. inherit: true, shell: true
  1256. , cwd: instanceroot + '/' + repodef.repo
  1257. , env: process.env
  1258. , title: `rm 'package-lock.json' for ${repodef.repo}`
  1259. }])
  1260. .then(()=>{
  1261. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1262. }).catch((e) => { console.error(e) })
  1263. // }
  1264. )
  1265. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  1266. repotasks.push(
  1267. () => {
  1268. console.log(`--npm i for ${repodef.repo}--------------------`)
  1269. var p = nodeShellExec('npm', ['i', '--force'], {
  1270. inherit: true, shell: true
  1271. , cwd: instanceroot + '/' + repodef.repo
  1272. , env
  1273. , title: `npm i for ${repodef.repo}`
  1274. }).then(Tasq.then).catch(Tasq.catch)
  1275. return p;
  1276. })
  1277. }
  1278. })
  1279. // NODE_ENV=development DEBUG=loopback:connector:mssql node --tls-min-v1.0 --inspect elixir/server.js
  1280. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  1281. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  1282. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  1283. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  1284. // Second time try also doesnt work.
  1285. // repotasks.push(
  1286. // () => {
  1287. // var env = Object.assign({}, process.env)
  1288. // delete env.NODE_ENV
  1289. // console.log(`--------------------second time npm i for client--------------------`)
  1290. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  1291. // // return nodeShellExec('npm', ['i --force'], {
  1292. // inherit: true, shell: true
  1293. // , cwd: instanceroot + '/' + 'client'
  1294. // , env
  1295. // , title: `npm i for client`
  1296. // }).then(Tasq.then).catch(Tasq.catch)
  1297. // })
  1298. var bowerRepos = [{ repo : 'client'}]
  1299. var bowertasks = []
  1300. bowerRepos.forEach(repodef => {
  1301. bowertasks.push(() => {
  1302. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
  1303. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  1304. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  1305. inherit: true, shell: true
  1306. , cwd: instanceroot + '/' + repodef.repo
  1307. , env: process.env
  1308. , title: `bower i for ${repodef.repo}`
  1309. }).then(Tasq.then).catch(Tasq.catch)
  1310. return p;
  1311. })
  1312. })
  1313. // console.log('rmtasks.length : ' + rmtasks.length)
  1314. return Promise.all(rmtasks).then(() => any(repotasks)).then(()=>any(bowertasks));
  1315. }).catch(e => {
  1316. console.error(e)
  1317. }).finally(statuslog.finally)
  1318. }
  1319. , 'start': (label) => {
  1320. console.log('Starting Elixir Server.');
  1321. var env = Object.assign({}, process.env); // Shallow clone it.
  1322. // console.dir(env)
  1323. env.NODE_ENV = process.env.NODE_ENV || 'development';
  1324. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  1325. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  1326. // cmd = 'node'
  1327. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
  1328. var childPromise = nodeShellExec(...cmd, {
  1329. // inherit : true,
  1330. shell: true,
  1331. detached: true,
  1332. stdio: 'ignore',
  1333. cwd: instanceroot + '/' + 'elixir-server'
  1334. , env: env
  1335. })
  1336. var child = childPromise.process;
  1337. if (typeof child.pid !== 'undefined') {
  1338. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1339. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  1340. encoding: 'utf8'
  1341. })
  1342. }
  1343. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  1344. // inherit : true,
  1345. // shell: true, detached: true,
  1346. // cwd : 'qms/server',
  1347. // env: env,
  1348. // shell : true
  1349. // })
  1350. // nodeShellExec('ember', ['s'], {
  1351. // // inherit : true,
  1352. // shell: true, detached: true,
  1353. // cwd : 'client/',
  1354. // env: env
  1355. // })
  1356. console.log('Starting Elixir Client Host.');
  1357. var cmd = ['ember', ['s']]
  1358. var childPromise = nodeShellExec(...cmd, {
  1359. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  1360. // PB : TODO -- ember debugging.
  1361. // inherit : true,
  1362. shell: true,
  1363. detached: true,
  1364. stdio: 'ignore',
  1365. cwd: instanceroot + '/' + 'client'
  1366. , env: env
  1367. })
  1368. // .catch(e=>console.error(e))
  1369. child = childPromise.process;
  1370. if (typeof child.pid !== 'undefined') {
  1371. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1372. fs.writeFileSync('.client.server.pid', child.pid, {
  1373. encoding: 'utf8'
  1374. })
  1375. }
  1376. }
  1377. , 'stop': (label) => {
  1378. const kill = require('tree-kill');
  1379. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  1380. encoding: 'utf8'
  1381. })
  1382. fs.unlinkSync('.elixir-server.elixir.server.pid')
  1383. console.log(serverPid)
  1384. kill(serverPid)
  1385. serverPid = fs.readFileSync('.client.server.pid', {
  1386. encoding: 'utf8'
  1387. })
  1388. fs.unlinkSync('.client.server.pid')
  1389. console.log(serverPid)
  1390. kill(serverPid)
  1391. }
  1392. , 'model' : () => {
  1393. if (__isElevated) {
  1394. var tasks = [
  1395. () => {
  1396. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  1397. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  1398. inherit: true, shell: true
  1399. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  1400. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  1401. , env: process.env
  1402. }).catch((e) => { console.error(e) })
  1403. return p;
  1404. }
  1405. ];
  1406. return any(tasks).then(() => {
  1407. fs.writeFileSync('run.done', 'success')
  1408. }).catch(() => {
  1409. fs.writeFileSync('run.done', 'error')
  1410. })
  1411. }
  1412. else return op['runas']()
  1413. }
  1414. , 'use' : () => {
  1415. // use a certain named instance.
  1416. // Eg :
  1417. // 1) elxr use elixir
  1418. // 2) elxr use cihsr
  1419. // If environment is not specified defaults to development.
  1420. // 1) NODE=test elxr use elixir
  1421. /*// Steps
  1422. 1) Delete Config and Data symlinks
  1423. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  1424. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  1425. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1426. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  1427. */
  1428. var runconfig = { NODE_ENV: selectedinstance.node_env }
  1429. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  1430. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  1431. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  1432. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  1433. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  1434. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  1435. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  1436. if (existsSync('config') && existsSync('data')){
  1437. return
  1438. }
  1439. }
  1440. var tasks = [
  1441. () => {
  1442. var promise = new Promise((resolve, reject)=>{
  1443. existslink('config', function(err, data){
  1444. if(data) {
  1445. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env })
  1446. .then(()=>{resolve(true)})
  1447. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
  1448. }
  1449. else resolve(false)
  1450. })
  1451. })
  1452. return promise;
  1453. },
  1454. () => {
  1455. var promise = new Promise((resolve, reject)=>{
  1456. existslink('data', function(err, data){
  1457. if(data) {
  1458. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env })
  1459. .then(()=>{resolve(true)})
  1460. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
  1461. }
  1462. else resolve(false)
  1463. })
  1464. })
  1465. return promise;
  1466. },
  1467. ];
  1468. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  1469. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  1470. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  1471. // console.log(process.env.cwd)
  1472. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  1473. // Maps an environment to a branch. Not required if the branch is appropriately named.
  1474. var checkoutMap = { 'development': 'master' }
  1475. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  1476. var performPullOrCloneForBranch = (def)=>{
  1477. var promise = Promise.resolve(true)
  1478. if (!branch) {
  1479. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1480. promise = nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{ branch = __branch})
  1481. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1482. }
  1483. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e )})
  1484. }
  1485. var performCloneAndCheckout = null;
  1486. // cant use git checkout -b it fails when branch already exists.
  1487. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1488. return performPullOrCloneForBranch(def).then(()=>{
  1489. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1490. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1491. // inherit : true, shell: true,
  1492. cwd: instanceroot + '/' + def.repo
  1493. // , stdio : ignore // Use when we want to silence output completely.
  1494. , runas: processedArgs.runas
  1495. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  1496. }).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 } })
  1497. })
  1498. }
  1499. // var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  1500. // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  1501. var elevatedqueue = [];
  1502. var enqueueOnce = (queue, task, def) => {
  1503. var found = queue.find(element => {
  1504. var keys = Object.keys( element )
  1505. for(var k=0; k < keys.length; k++) {
  1506. if(element[keys[k]] !== def[k]) return false;
  1507. }
  1508. })
  1509. queue.push(function(){ return task(this)}.bind(def));
  1510. }
  1511. var enqueue = (queue, task, def) => {
  1512. queue.push(function(){ return task(def)}.bind(def));
  1513. }
  1514. var mergeSources = {
  1515. 'development': null,
  1516. 'test': 'master',
  1517. 'production': 'master'
  1518. }
  1519. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1520. // Checkout is reduced to pull provided the current branch is the targetbranch
  1521. if(branch === mergesource) performCheckout = (def) => {
  1522. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1523. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  1524. if(branch === __branch) return performCloneAndCheckout(def)
  1525. return performPullOrCloneForBranch(def)
  1526. })
  1527. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1528. }
  1529. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  1530. var performPullAll = (def) => {
  1531. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1532. return nodeShellExec('git', ['pull', '--all'], {
  1533. // inherit : true, shell: true,
  1534. cwd: instanceroot + '/' + def.repo
  1535. , runas: processedArgs.runas
  1536. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  1537. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  1538. }
  1539. var excludeCheckouts = Object.assign(exludeMergeRepos)
  1540. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  1541. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  1542. var performMerge = (def) => {
  1543. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  1544. return nodeShellExec('git', ['merge', mergesource], {
  1545. inherit: true, shell: true,
  1546. cwd: instanceroot + '/' + def.repo
  1547. , runas: processedArgs.runas
  1548. }).catch((e) => { console.error(e) })
  1549. }
  1550. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
  1551. // var performRepoOperation = function(def) {
  1552. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  1553. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  1554. // }
  1555. return any(tasks).then(() => {
  1556. var pr = Promise.resolve(true)
  1557. if (!__isElevated) {
  1558. pr = op['runas']()
  1559. return pr.then(()=>{
  1560. //target is the env is we specify in elxr use command. Default is dev
  1561. //Switch to target branch
  1562. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  1563. // pull or clone target branch
  1564. .then(() => {
  1565. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1566. return any(gitRepos.map((repo) => performPullAll(repo)))
  1567. })
  1568. // switch to source branch
  1569. .then( () => {
  1570. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  1571. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  1572. })
  1573. //Pull on merge source branch
  1574. .then( () => {
  1575. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1576. return any(gitRepos.map((repo) => performPullAll(repo)))
  1577. })
  1578. //Switch to target branch
  1579. .then( () => {
  1580. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1581. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  1582. })
  1583. .then( //Merge source branch to target branch
  1584. () => {
  1585. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1586. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
  1587. })
  1588. })
  1589. }
  1590. else {
  1591. tasks = [
  1592. () => {
  1593. // Use junctions to avoid npm package issues
  1594. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  1595. inherit: true, shell: true
  1596. , cwd : instanceroot
  1597. , env: process.env
  1598. }).catch((e) => { console.error(e) })
  1599. return p;
  1600. }
  1601. ];
  1602. if (processedArgs._[1]) {
  1603. tasks = tasks.concat(
  1604. [
  1605. () => {
  1606. var dataToLink = runconfig.use + '-data' + '-' + process.env.NODE_ENV
  1607. if(!existsSync(dataToLink)) dataToLink = runconfig.use + '-data';
  1608. var p = nodeShellExec('mklink', ['/J', 'data', dataToLink], {
  1609. inherit: true, shell: true
  1610. , cwd : instanceroot
  1611. , env: process.env
  1612. }).catch((e) => { console.error(e) })
  1613. return p;
  1614. }
  1615. ]
  1616. )
  1617. }
  1618. return any(tasks).then(()=>{
  1619. // checkout target branch
  1620. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1621. // pull or clone target branch
  1622. .then(() => {
  1623. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1624. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  1625. })
  1626. // switch to source branch
  1627. .then( () => {
  1628. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1629. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  1630. })
  1631. //Pull on merge source branch
  1632. .then( () => {
  1633. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1634. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  1635. })
  1636. //Switch to target branch
  1637. .then( () => {
  1638. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1639. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1640. })
  1641. .then( //Merge source branch to target branch
  1642. () => {
  1643. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1644. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
  1645. })
  1646. .then(() => {
  1647. fs.writeFileSync('run.done', 'success')
  1648. }).catch(() => {
  1649. fs.writeFileSync('run.done', 'error')
  1650. })
  1651. })
  1652. }
  1653. }).catch(() => {
  1654. fs.writeFileSync('run.done', 'error')
  1655. })
  1656. // Antibiotic stewardship program.
  1657. // 1st use is fine.
  1658. // Max vials dispense
  1659. // 2nd use Pharmacy needs justification Form.
  1660. // Approval after a certain period of time.
  1661. }
  1662. , 'g' : () => {
  1663. if (processedArgs.h) {
  1664. console.log('elxr g model [modelname] => generate a model named [modelname]');
  1665. console.log('elxr g vmodel [modelname] => generate a model named [modelname]');
  1666. console.log('elxr g => regenerate all known models');
  1667. return
  1668. }
  1669. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1670. // console.log('Starting directory: ' + process.cwd());
  1671. // try {
  1672. // child = child.on('close', () => { process.chdir(label) } );
  1673. // console.log('New directory: ' + process.cwd());
  1674. // }
  1675. // catch (err) {
  1676. // console.log('chdir: ' + err);
  1677. // }
  1678. // child.on('close', function(){
  1679. // var options = {
  1680. // shell : true
  1681. // , inherit : true
  1682. // // , cwd : '' + process.cwd
  1683. // // , env : process.env
  1684. // };
  1685. // nodeShellExec('git', ['init'], { inherit : true});
  1686. if (0) {
  1687. // PB : TODO -- Special google chrome profile for tests etc.
  1688. nodeShellExec('pwd', { inherit: true });
  1689. // /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"
  1690. // "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
  1691. // "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
  1692. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1693. "--profile-directory=Profile 1"
  1694. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1695. }
  1696. // nodeShellExec('npm', ['init', '-y'], options);
  1697. // nodeShellExec('npm', ['init', '-y'], options);
  1698. // })
  1699. var g = {
  1700. 'client': () => {
  1701. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  1702. console.info('Creating new ember client named : ' + processedArgs._[2]);
  1703. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1704. stdio: ['pipe', process.stdout, process.stderr],
  1705. inherit: true,
  1706. shell: true,
  1707. cwd: path.dirname(__dirname),
  1708. env: env
  1709. })
  1710. },
  1711. 'modelr': () => {
  1712. var tasks = [
  1713. () => {
  1714. var p = nodeShellExec('"ember"', [
  1715. 'g'
  1716. , 'modelr'
  1717. , processedArgs._[2]], {
  1718. inherit: true, shell: true, env: process.env
  1719. }).then(() => {
  1720. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  1721. return true;
  1722. }).catch((e) => { console.error(e) })
  1723. return p;
  1724. },
  1725. () => {
  1726. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1727. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  1728. chromeprefs = JSON.parse(chromeprefs)
  1729. var previous = chromeprefs.download.default_directory;
  1730. var parentDir = path.dirname(__dirname);
  1731. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1732. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1733. // PB : TODO -- detect where chrome is installed.
  1734. // PB : TODO -- set the download dir to the place where files are needed.
  1735. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1736. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1737. , '--profile-directory="chess"'
  1738. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1739. inherit: true, shell: true
  1740. , env: process.env
  1741. }).then(() => {
  1742. chromeprefs.download.default_directory = previous;
  1743. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1744. return true;
  1745. }).catch((e) => { console.error(e) })
  1746. return p;
  1747. }
  1748. ,
  1749. () => {
  1750. console.log('Browser process should have closed here....')
  1751. return true;
  1752. }
  1753. ]
  1754. any(tasks)
  1755. }
  1756. , 'undefined' : ()=>{
  1757. console.warn('Are you sure you want to refresh all the models.');
  1758. throw 'NOT YET IMPLMENTED'
  1759. }
  1760. , 'vmodel' : ()=>{
  1761. var verse = [ '__universe__/vmodel' ]
  1762. // console.dir(templateprocess(`__link____instance__server-lib__name__`, { link( ){
  1763. // return processed }, instance : 'elixir-', name : 'newmodel' } )
  1764. // )
  1765. }
  1766. }
  1767. g[processedArgs._[1]]();
  1768. }
  1769. , 'create' : () => { return createInstance(selectedinstance) }
  1770. , 'httpget' : () => {
  1771. // RESTAPI.get({
  1772. // hostname: 'git.bbh',
  1773. // // port: 443,
  1774. // protocol : 'http:',
  1775. // path: '/',
  1776. // method: 'GET'
  1777. // }, function(data){ console.log(data)}, function(error){ console.log(error)} )
  1778. return createInstance(selectedinstance)
  1779. }
  1780. , 'getuser' : ()=>{ return prerequisites.git.getuser().then(u=>{ console.log(u)}) }
  1781. , 'switch user' : (tousername)=>{ return GIT['switch user'](tousername) }
  1782. }
  1783. // elxr cli operations
  1784. var noprerequisites = {
  1785. add : true, 'set-url' : true, 'repo-relocate' : true
  1786. , remote : true, 'c' : true, 'h' : true
  1787. , httpget : true, getuser : true
  1788. , 'switch user' : true
  1789. , 'switch' : true
  1790. // , 'undefined' : true
  1791. }
  1792. var reconfirmcmds = { create : true }
  1793. var subcommandlabels = {
  1794. remote : (`remote ${processedArgs._[1] || ''}`).trim()
  1795. , switch : (`switch ${processedArgs._[1] || ''}`).trim()
  1796. }
  1797. var cmds = {
  1798. remote : {
  1799. // return a interpreted set of arguments for this comd run context.
  1800. interpret() {
  1801. return { cmd : subcommandlabels['remote'], runchoice : 'c' }
  1802. }
  1803. }
  1804. , switch : {
  1805. interpret() {
  1806. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2]
  1807. , reposerver : __default.reposerver
  1808. }
  1809. }
  1810. , getPossiblePrompts(){ return { username : true, reposerver : 'http://git.bbh' } } // Requires only one argument...
  1811. }
  1812. , 'switch user' : {
  1813. interpret() {
  1814. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2] }
  1815. }
  1816. , getPossiblePrompts(){ return { username : true } } // Requires only one argument...
  1817. }
  1818. // Flat linear structure. Every subcommand should have a top level 'label'
  1819. , 'users' : {
  1820. // default to the users list
  1821. subcommands : { list : {} }
  1822. , cmdFn : ()=>getCredentials() // default
  1823. , cmd : 'users'
  1824. , noprerequisites : true
  1825. }
  1826. , 'users list' : {
  1827. cmdFn : ()=>getCredentials()
  1828. , cmd : 'users list'
  1829. , noprerequisites : true
  1830. }
  1831. , 'g' : {
  1832. cmdFn : op['g'] // default
  1833. , cmd : 'g'
  1834. , noprerequisites : true
  1835. , getPossiblePrompts(){ return {} }
  1836. }
  1837. , 'link' : {
  1838. 'cmd' : 'link'
  1839. // , cmdFn : function( sourecpath, filename, dir ){
  1840. // var afterTargetPath = (dir)=>{
  1841. // console.dir(dir);
  1842. // // var tasks = [
  1843. // // () => {
  1844. // // // Use junctions to avoid npm package issues
  1845. // // var p = nodeShellExec('mklink', ['/J', filename, sourecpath], {
  1846. // // inherit: true, shell: true
  1847. // // , cwd : dir || instanceroot
  1848. // // , env: process.env
  1849. // // }).catch((e) => { console.error(e) })
  1850. // // return p;
  1851. // // }
  1852. // // ];
  1853. // }
  1854. // // console.dir(process.env)
  1855. // if(!dir) getCurrentFolder().then(afterTargetPath);
  1856. // else afterTargetPath(dir)
  1857. // }
  1858. , cmdFn : function( cmdopts ){
  1859. // sourecpathandfile should include name of file name
  1860. targetfilename = cmdopts.targetfilename || processedArgs._[1]
  1861. // console.log(processedArgs)
  1862. if(!targetfilename) Promise.reject('error no file provided for linking')
  1863. targetdir = cmdopts.targetdir || process.env.wd
  1864. sourecpathandfile = cmdopts.sourecpathandfile || path.normalize(`../../node_modules/chess-server-lib/common/models/${targetfilename}`)
  1865. var tasks = [
  1866. () => {
  1867. // Use junctions to avoid npm package issues
  1868. var p = nodeShellExec('mklink', [path.normalize(`${targetdir + '/' + targetfilename}`), sourecpathandfile], {
  1869. inherit: true, shell: true
  1870. , cwd : targetdir
  1871. , env: process.env
  1872. }).catch((e) => { console.error(e) })
  1873. return p;
  1874. }
  1875. ];
  1876. if (__isElevated) {
  1877. return any(tasks).then(() => {
  1878. fs.writeFileSync('run.done', 'success')
  1879. }).catch(() => {
  1880. fs.writeFileSync('run.done', 'error')
  1881. })
  1882. }
  1883. else return op['runas']()
  1884. }
  1885. , noprerequisites : true
  1886. , privileged : true
  1887. }
  1888. }
  1889. var elxrcmd = (function(){
  1890. var __cmdprototype = function(){}
  1891. function subcommandlabelFor(cmd, sub){ return (`${cmd} ${sub || ''}`).trim() }
  1892. var __cmd = {
  1893. interpret() { return { cmd : this.cmd } }
  1894. , getPossiblePrompts(){ return {} } // Requires only one argument...
  1895. , cmdFn : ()=>{ throw "Elxr Unknown command."}
  1896. , finalized : true
  1897. }
  1898. function __createO(o){
  1899. if(o.finalized) return o;
  1900. var subs = Object.keys(cmds[o.cmd].subcommands || {})
  1901. console.log(subs)
  1902. console.log(o)
  1903. subs.forEach(sub=>elxrcmd.create( cmds[subcommandlabelFor(o.cmd, sub)] ))
  1904. var created = utils.assign_strict({}, __cmd, cmds[o.cmd], o)
  1905. cmds[o.cmd] = created;
  1906. op[o.cmd] = created.cmdFn;
  1907. noprerequisites[o.cmd] = created.noprerequisites
  1908. return created.cmdFn;
  1909. }
  1910. function create(o){ return __createO(o) }
  1911. __cmdprototype.create = create;
  1912. return __cmdprototype;
  1913. })()
  1914. elxrcmd.create(cmds['users'])
  1915. elxrcmd.create(cmds['g'])
  1916. elxrcmd.create(cmds['link'])
  1917. var interpretrun = function(){
  1918. var cmd = processedArgs._[0];
  1919. var clioverrides = { cmd }
  1920. processedArgs.node_env ? clioverrides.node_env = processedArgs.node_env
  1921. : (process.env.NODE_ENV && process.env.NODE_ENV.trim())
  1922. ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) : null;
  1923. return cmds[cmd] ? cmds[cmd].interpret() : (function(){
  1924. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  1925. // return clioverrides
  1926. cmds[cmd] = {
  1927. interpret() {
  1928. return Object.assign(clioverrides, { cmd, runchoice : 'c' })
  1929. }
  1930. , getPossiblePrompts(){ return { cmd, username : true, password : true,
  1931. instanceName : true, instanceType : true, reposerver : true } }
  1932. }
  1933. return cmds[cmd].interpret()
  1934. })()
  1935. }
  1936. var clioverrides = interpretrun()
  1937. console.dir(clioverrides)
  1938. var util = require('util');
  1939. var cliname = 'elxr';
  1940. var ver = '1.1';
  1941. var readme = `
  1942. Command syntax examples
  1943. elxr
  1944. Displays help. Same as elxr h
  1945. elxr i
  1946. Runs interactive propmts to help choose installation options.
  1947. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  1948. General command syntax.
  1949. Eg: NODE_ENV=development elxr pull elixir
  1950. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  1951. The specific cmd defines what the value is interpreted as.
  1952. There are several cmds that do not require an {{instancename}} parameter.
  1953. Eg: elxr remote remove origin
  1954. Git operations or passthrough external commands on all repository folders in you working directory.
  1955. Main objectives.
  1956. elxr cli is a wrapper around other shell commands and api based operations.
  1957. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  1958. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  1959. `;
  1960. var help = `
  1961. ${readme}
  1962. # list of commands... please refer dveloper documentation for ${cliname}
  1963. \r\n\t${
  1964. Object.keys(op).join('\r\n\t')
  1965. }
  1966. `;
  1967. var elxr = {
  1968. help() {
  1969. return chalk.cyanBright(`
  1970. -------------------------------------------------------------------------------
  1971. *** BBH Elixir ***
  1972. -------------------------------------------------------------------------------
  1973. elxr ${ver}
  1974. A cli tool for chess
  1975. ${help}
  1976. -------------------------------------------------------------------------------
  1977. `)
  1978. }
  1979. , info() {
  1980. return chalk.cyanBright(`
  1981. -------------------------------------------------------------------------------
  1982. *** BBH Elixir ***
  1983. -------------------------------------------------------------------------------
  1984. elxr ${ver}
  1985. A cli tool for chess
  1986. -------------------------------------------------------------------------------
  1987. `)
  1988. }
  1989. , getpulltask(args){
  1990. // def can be an instance config
  1991. // Or an object with many repos and elevated repos
  1992. // Or a single repo ( Either Elevated or normal. )
  1993. // USAGE
  1994. // elxr pull elixir origin master
  1995. // elxr pull
  1996. // not all remote branches are setup to be tracked locally (respective remotes and branches).
  1997. // pull --all is useless. As it fetches all remotes and branches but only merges current branch.
  1998. // apart from remote tracking branches We are interested in pulling from all remotes and relavant branches.
  1999. // The branch pipline should feed back to master
  2000. // master -> test -> stage -> release[nnnn] -> production
  2001. // (master) <= git merge [all remotes] production && git merge [all remotes] release[nnnn]
  2002. // git merge [all remotes] stage && git merge [all remotes] test && git merge [all remotes] master
  2003. var __args = {
  2004. remotename : args.remotename|| processedArgs._[2]
  2005. , url : args.url || processedArgs._[3]
  2006. , branch : args.branch || processedArgs._[4] // If branch not specified opearte on the current branch of each working directorys
  2007. }
  2008. // var commands = [
  2009. // // ['git', ['checkout', __args.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]]
  2010. // ,
  2011. // ]
  2012. // var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  2013. // var pullCmd = [ gitbash
  2014. // , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  2015. // , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  2016. var def = args || {
  2017. repos : selectedinstance.repos,
  2018. elevated : selectedinstance.elevated
  2019. }
  2020. var elevatedpulltasks = null;
  2021. if(def.repo) {
  2022. // Single repo case.
  2023. if(def.repo.requiresElevation) {
  2024. elevatedpulltasks = function() {
  2025. return performPull(def.repo).then(() => {
  2026. return true;
  2027. }).catch((e) => {
  2028. console.error(e)
  2029. })
  2030. }
  2031. return
  2032. }
  2033. else {
  2034. var regularpulltasks = function(){
  2035. var pendingpulls = [];
  2036. pendingpulls.push(performPull(def.repo))
  2037. return Promise.all(pendingpulls).finally(Traq.finally)
  2038. }
  2039. }
  2040. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  2041. else return getTaskWithoutElevation({ regularpulltasks})
  2042. }
  2043. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  2044. console.dir(def)
  2045. var env = Object.assign({}, process.env); // Shallow clone it.
  2046. console.log('Running exlr pull : ' + path.dirname(__dirname))
  2047. var useGitPull = processedArgs.useGitPull || false;
  2048. if(def.elevated || def.repos) {
  2049. if(def.elevated) def.requiresElevation = true;
  2050. else delete def.requiresElevation;
  2051. }
  2052. else {
  2053. if(def.requiresElevation) def.elevated = [def]
  2054. else def.repos = [def]
  2055. }
  2056. var regularpulltasks = function(){ return Promise.resolve(true) }
  2057. if(def.elevated){
  2058. elevatedpulltasks = function() {
  2059. return any(def.elevated.map((def) => performPull(def.repo))).then(() => {
  2060. return true;
  2061. }).catch((e) => {
  2062. console.error(e)
  2063. })
  2064. }
  2065. }
  2066. if(def.repos) {
  2067. var regularpulltasks = function(){
  2068. var pendingpulls = [];
  2069. def.repos.forEach((def) => { pendingpulls.push(performPull(def.repo)) })
  2070. return Promise.all(pendingpulls).finally(Traq.finally)
  2071. }
  2072. }
  2073. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  2074. else return getTaskWithoutElevation({ regularpulltasks})
  2075. }
  2076. }
  2077. function preworkerconfig(){
  2078. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  2079. gitRepos = selectedinstance.repos
  2080. // gitRepos = ['chess-server-lib'];
  2081. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  2082. elevatedRunasRepos = selectedinstance.elevated
  2083. // Repos that should excluded from merge for releases...
  2084. exludeMergeRepos = selectedinstance.exludeMergeRepos
  2085. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  2086. // mysql -u root -p db_name < drop_all_tables.sql
  2087. var mysql = '../xampp/mysql/bin/mysql'
  2088. var mysqldump = '../xampp/mysql/bin/mysqldump'
  2089. }
  2090. // The main elxr cli process
  2091. function elxrworker() {
  2092. var __runcmd = function (label) {
  2093. var distinquishedlabel = subcommandlabels[label] || label
  2094. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  2095. }
  2096. // --runas
  2097. if (processedArgs.runas) {
  2098. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  2099. return __runcmd('runas')
  2100. }
  2101. else return __runcmd(processedArgs.label || processedArgs._[0] || 'undefined');
  2102. }
  2103. // function acquireChoices(selectedinstance) {
  2104. // var hasconfig = false;
  2105. // console.warn(chalk.cyan(`
  2106. // -------------------------------------------------------------------------------
  2107. // Could not locate your preferred configuration (you may not specified it)
  2108. // You should fork the default chess configuration to customize and make it
  2109. // your own instance with a named config as
  2110. // {{yourowninstancename}}-config-{{yourchosenenvironment}}
  2111. // And then run this tool as follows
  2112. // NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  2113. // OR
  2114. // Run this tool with the following command to use a quick start default.
  2115. // elxr --default
  2116. // OR
  2117. // Choose one of the options below to run interactively.
  2118. // We will run your choice at the next prompt.
  2119. // -------------------------------------------------------------------------------
  2120. // `))
  2121. // var choices = getInteractionPoints(detectedinstanceoptions, __interactive_prompts)
  2122. // var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  2123. // return initinstances(selectedinstance)
  2124. // })
  2125. // // var prompt = cli.prompter;
  2126. // // return prompt.ask(`Choose an option :
  2127. // // d) Install the default chess instance.
  2128. // // => elxr i chess node_env=development --default
  2129. // // n) Create your custom new instance interactively
  2130. // // => elxr i {{instanceName}} node_env={{environment}}
  2131. // // i) Choose an instance and environment to install
  2132. // // => elxr i {{instanceName}} node_env={{environment}}
  2133. // // c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  2134. // // => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  2135. // // h) Help
  2136. // // q) Quit
  2137. // // Default <= d
  2138. // // : `).then((choice) => {
  2139. // // if (choice && choice === 'd' || !choice) {
  2140. // // processedArgs._[0] = 'i'
  2141. // // selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  2142. // // selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  2143. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  2144. // // }
  2145. // // else if (choice === 'h') {
  2146. // // processedArgs._[0] = 'h'
  2147. // // fs.writeFileSync('run.done', 'noop help');
  2148. // // console.log(elxr.help()); process.exit()
  2149. // // }
  2150. // // else if (choice === 'n' || choice === 'i') {
  2151. // // var p1 = cli.prompter;
  2152. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  2153. // // processedArgs._[0] = 'i'
  2154. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  2155. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  2156. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  2157. // // if (choice === 'n') {
  2158. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  2159. // // console.warn(
  2160. // // chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  2161. // // process.exit();
  2162. // // }
  2163. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  2164. // // selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  2165. // // })
  2166. // // })
  2167. // // })
  2168. // // } else if (choice === 'c') {
  2169. // // var p1 = cli.prompter;
  2170. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  2171. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  2172. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  2173. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  2174. // // return p1.ask(`Enter cmd :
  2175. // // p) pull
  2176. // // Default <= p
  2177. // // : `).then(function (cmd) {
  2178. // // if (!cmd || cmd === 'p') {
  2179. // // processedArgs._[0] = 'pull'
  2180. // // }
  2181. // // else processedArgs._[0] = cmd
  2182. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  2183. // // selectedinstance.reposerver = reposerver || selectedinstance.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  2184. // // })
  2185. // // })
  2186. // // })
  2187. // // })
  2188. // // } else {
  2189. // // 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.`));
  2190. // // fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  2191. // // fs.writeFileSync('run.done', 'noop quit');
  2192. // // process.exit()
  2193. // // }
  2194. // // })
  2195. // }
  2196. var mergeObjByKey = function(arrOfObjs, keyName) {
  2197. var keyedDistinct = {}
  2198. var distinctArrOfObjs = []
  2199. arrOfObjs.forEach( o => {
  2200. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o)
  2201. })
  2202. Object.keys(keyedDistinct).forEach(key => {
  2203. distinctArrOfObjs.push( utils.assign( ...keyedDistinct[key] ) ) // PB : TODO -- Shallow use utils.assign
  2204. })
  2205. return distinctArrOfObjs;
  2206. }
  2207. var cacheWriteInstanceConfig = function(chessinstances){
  2208. var instanceName = chessinstances['current_run'].instanceName;
  2209. var node_env = chessinstances['current_run'].node_env;
  2210. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos, 'repo') ;
  2211. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated, 'repo') ;
  2212. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  2213. }
  2214. var configs = (function(){
  2215. return {
  2216. clusterNodeInstance(selected) { var clusternodename = 'node01'
  2217. return __acquireConfig(selected, selected.username, clusternodename
  2218. , selected.instanceName + '-config-' + selected.node_env + `-${clusternodename}`
  2219. , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
  2220. return e; }
  2221. )
  2222. }
  2223. , ownerInstnace(selected) { return __acquireConfig(selected, selected.username, null, null
  2224. , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
  2225. return e }
  2226. )
  2227. }
  2228. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  2229. , commonInstance(selected) { return __acquireConfig(selected, defaultRepoOwner
  2230. // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
  2231. ) }
  2232. , genericChessInstance(selected) { return __acquireConfig(selected) }
  2233. }
  2234. })()
  2235. var eNotImplemented = function(){
  2236. console.error('Not yet implemented')
  2237. process.exit()
  2238. }
  2239. // PB : TODO -- accept additional arg - an array specifying custom configPriority.
  2240. var acquireConfig = function(slections){
  2241. var configPriority = [ 'clusterNodeInstance', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  2242. return any(configPriority.map(cfg => { return function() { return configs[cfg](slections) } } ), true, true).then(()=>{
  2243. return acquireData(slections)
  2244. })
  2245. }
  2246. var instanceData = (function(){
  2247. return {
  2248. clusterNodeInstance(selected) { var clusternodename = 'node01'
  2249. return __acquireData(selected, selected.username, clusternodename
  2250. , selected.instanceName + '-data-' + selected.node_env + `-${clusternodename}`
  2251. , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
  2252. return e; }
  2253. )
  2254. }
  2255. , ownerInstnace(selected) { return __acquireData(selected, selected.username, null
  2256. , selected.instanceName + '-data-' + selected.node_env
  2257. , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
  2258. return e }
  2259. )
  2260. }
  2261. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  2262. , commonInstance(selected) { return __acquireData(selected, defaultRepoOwner
  2263. // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
  2264. ) }
  2265. , genericChessInstance(selected) { return __acquireData(selected) }
  2266. }
  2267. })()
  2268. var acquireData = function(slections){
  2269. var configPriority = [ 'clusterNodeInstance', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  2270. return any(configPriority.map(cfg => { return function() { return instanceData[cfg](slections) } } ), true, true)
  2271. }
  2272. // Git Credential storage...
  2273. // notepad C:/Program Files/Git/etc/gitconfig
  2274. // git config --global --unset credential
  2275. // git config --edit --system
  2276. // git config --global credential.helper "store --file ~/gitcredentials"
  2277. // git credential fill
  2278. // git credential-store --file ~/git.store store
  2279. var __acquireConfig = function (selected, owner, clusternodename, configrepo, errHandler) {
  2280. configrepo = configrepo || selected.instanceName + '-config-' + selected.node_env;
  2281. var errorHandler = (e) => {
  2282. if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${owner}/${configrepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
  2283. // console.error('Could not connect to repo server. Timed Out')
  2284. 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 => {
  2285. if(propValue === 'y') {
  2286. reconfirm = getReconfirmAll()
  2287. return startElxr()
  2288. }
  2289. else if(propValue === 'r'){
  2290. return acquireConfig(selected)
  2291. }
  2292. else process.exit()
  2293. })
  2294. }
  2295. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${owner}/${configrepo}.git/' not found`))){
  2296. var choices = {
  2297. t : `install a new temporary local instance with this name ( will not persist ).
  2298. Use your own username for additional options. You can request for a username at chess@bbh.org.in )`
  2299. , e : 'exit' }
  2300. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  2301. choices = utils.assign({
  2302. i : 'create a new instance with this name => will fork the default config under your username'
  2303. , f : 'fork a new instance with this name for yourself for this node from another instance'
  2304. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  2305. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  2306. , p : 'create a custom config for yourself '
  2307. }, choices)
  2308. }
  2309. return cli.prompt( choices
  2310. , 'Config for instance not found. Would you like to ', 'e' ).then(propValue => {
  2311. if(propValue === 't') {
  2312. selectedinstance.local = true; return createInstance(selectedinstance)
  2313. }
  2314. if(propValue === 'i') return eNotImplemented()
  2315. if(propValue === 'f') return eNotImplemented()
  2316. if(propValue === 'o') return eNotImplemented()
  2317. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  2318. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  2319. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  2320. else process.exit()
  2321. })
  2322. }
  2323. console.warn(e)
  2324. throw e; //('Config acquisition failed.')
  2325. }
  2326. var successHandler = () => {
  2327. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  2328. utils.assign_strict(selectedinstance, require(manifestpath)( null, selectedinstance))
  2329. console.dir(selectedinstance.repos)
  2330. // Config from server always override merges into selection except for the current selection.
  2331. // PB : TODO -- utils.assign Array merges are non-distinct...
  2332. if(!selectedinstance.repos[0].repo) {
  2333. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  2334. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  2335. }
  2336. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  2337. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  2338. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  2339. }
  2340. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = utils.assign(selected, selectedinstance)
  2341. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  2342. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  2343. cacheWriteInstanceConfig(chessinstances)
  2344. ENV.NODE_ENV = selectedinstance.node_env;
  2345. }
  2346. return performPull(configrepo, null, owner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  2347. .catch( (e)=>{
  2348. // if(e){
  2349. if(Promise.resolve(e) === e) return e;
  2350. console.error(e)
  2351. throw e; // Not a hard error but we need this for bcontinueonfailure
  2352. // }
  2353. })
  2354. }
  2355. var __acquireData = function (selected, owner, clusternodename, datarepo, errHandler) {
  2356. datarepo = datarepo || selected.instanceName + '-data';
  2357. var errorHandler = (e) => {
  2358. if(e.messages.join(' ').match(new RegExp (`fatal: unable to access '${selectedinstance.reposerver}/${owner}/${datarepo}.git/': Failed to connect to .*? port .*? after .*? ms: Timed out`))){
  2359. // console.error('Could not connect to repo server. Timed Out')
  2360. 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 => {
  2361. if(propValue === 'y') {
  2362. reconfirm = getReconfirmAll()
  2363. return startElxr()
  2364. }
  2365. else if(propValue === 'r'){
  2366. return acquireConfig(selected)
  2367. }
  2368. else process.exit()
  2369. })
  2370. }
  2371. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${owner}/${datarepo}.git/' not found`))){
  2372. var choices = {
  2373. t : `install a temporary local data folder.
  2374. For more options. Request and use a personal username at chess@bbh.org.in )`
  2375. , e : 'exit' }
  2376. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  2377. choices = utils.assign({
  2378. i : 'create a new instance with this name => will fork the default config under your username'
  2379. , f : 'fork a new instance with this name for yourself for this node from another instance'
  2380. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  2381. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  2382. , p : 'create a custom config for yourself '
  2383. }, choices)
  2384. }
  2385. return cli.prompt( choices
  2386. , 'Data repo for instance not found. Would you like to ', 'e' ).then(propValue => {
  2387. if(propValue === 't') {
  2388. selectedinstance.local = true; return createInstanceData(selectedinstance)
  2389. }
  2390. if(propValue === 'i') return eNotImplemented()
  2391. if(propValue === 'f') return eNotImplemented()
  2392. if(propValue === 'o') return eNotImplemented()
  2393. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  2394. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  2395. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  2396. else process.exit()
  2397. })
  2398. }
  2399. console.warn(e)
  2400. throw e; //('Config acquisition failed.')
  2401. }
  2402. var successHandler = () => {
  2403. }
  2404. return performPull(datarepo, null, owner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  2405. .catch( (e)=>{
  2406. // if(e){
  2407. if(Promise.resolve(e) === e) return e;
  2408. console.error(e)
  2409. throw e; // Not a hard error but we need this for bcontinueonfailure
  2410. // }
  2411. })
  2412. }
  2413. var launchpath = path.normalize(process.cwd())
  2414. 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 we were run.
  2415. // The easisest would be to ask for a target directory and default to current dir....
  2416. var instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
  2417. // PB : TODO -- Embed this in the build instead of inlining it.
  2418. // Also attepmt to load from ../chess-config/...
  2419. var __default = ((name, options)=>{
  2420. // Default set of users in main repos.
  2421. var users = [
  2422. { username : `${options.username}`, password : `${options.password}` }
  2423. , { username : `chess` }
  2424. // , { username : `baptistdev`, password : 'encrypted' }
  2425. // , { username : `guest`, password : 'encrypted' }
  2426. ]
  2427. // ${options.reposerver} should be used to lookup current config.
  2428. // User can always add more branches and remotes as needed. Mainifest only occupies
  2429. // well defined namespaces
  2430. var remotes = {
  2431. // these are both fetch and push remotes. Use push - remotes to override push.
  2432. 'chess' : {
  2433. server : `${options.reposerver}`, user : 'chess', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2434. , push : 'no-pushing' }
  2435. , 'baptistdev-public' : {
  2436. server : `https://github.com`, user : 'baptistdev', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2437. , push : 'no-pushing' }
  2438. // Multiple urls dont tell us the current origin which may be
  2439. // different based on currently available/accessible based on device and client.
  2440. // We just treat them as different remotes and merge as needed.
  2441. //
  2442. , 'origin' : {
  2443. server : `${options.reposerver}`, user : '${options.username}', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2444. }
  2445. , 'origin-public' : {
  2446. server : `https://git.bbh.org.in`, user : 'chess', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2447. , push : {
  2448. server : `${options.reposerver}`, user : `${options.username}`, path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`}
  2449. }
  2450. }
  2451. , 'origin-unc' : {
  2452. server : `//172.16.0.27/repos`, user : '${options.username}', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2453. }
  2454. // , { `${options.username}` : `https://git.bbh.org.in/${options.username}/elxr.git` }
  2455. }
  2456. // , 'fetch-remotes' : [] // Multiple fetch remotes are not supported by git.
  2457. // We therefore need to use
  2458. // - a pullall
  2459. // - or branch alias for multiple remote branch tracking branch strategy.
  2460. // -- This is however limited to corresponding branch names
  2461. // tracking branches.
  2462. // We at least need one branch for each remote that we wish to track.
  2463. // , 'tracking-branches' : [
  2464. // { master : ['origin/master', 'chess/master'] }
  2465. // ]
  2466. var reposerverinstances = {
  2467. 'http://git.bbh' : { users, remotes }
  2468. , 'https://git.bbh.org.in' : { users, remotes, external : true }
  2469. , '//172.16.0.27/repos' : { users, remotes }
  2470. , 'https://github.com' : {
  2471. // We host a miniaml set of repositories in github.
  2472. get users() { return [{ username : `${this.username}` }]}, username : `baptistdev`
  2473. , remotes : {
  2474. 'baptistdev-public' : {
  2475. server : `https://github.com`, user : 'baptistdev', path : ``, get url(){ return `${this.server}/${this.user}/${this.path}`} // fetch
  2476. , push : 'no-pushing' }
  2477. // , Add other remotes here.
  2478. }
  2479. , external : true, public : true
  2480. }
  2481. }
  2482. return {
  2483. reposervers : Object.keys(reposerverinstances)
  2484. , reposerverinstances
  2485. // Common baseline repos for all chess instances.
  2486. , repos : [
  2487. { repo : 'ember-masonry-grid' /*, branch : master*/ } // Default need not be specified.
  2488. , { repo : 'bbhverse' }
  2489. , { repo : 'clientverse' }
  2490. , { repo : 'serververse' }
  2491. , { repo : 'elxr' }
  2492. , { repo : 'ember-searchable-select' }
  2493. , { repo : 'loopback-component-jsonapi' }
  2494. , { repo : 'loopback-jsonapi-model-serializer' }
  2495. , { repo : 'loopback-connector-mysql' }
  2496. , { repo : 'loopback-connector-ds' }
  2497. , { repo : 'chess-server-lib' }
  2498. , { repo : 'ember-service-worker' }
  2499. , { repo : 'ember-service-worker-asset-cache' }
  2500. , { repo : 'ember-service-worker-cache-fallback' }
  2501. , { repo : 'ember-service-worker-index' }
  2502. , { repo : 'ember-sw-client-route' }
  2503. , { repo : 'global-this' }
  2504. ]
  2505. , elevated : [ ]
  2506. , exludeMergeRepos : { }
  2507. }
  2508. })(
  2509. '__default' // name
  2510. , { username : 'guest', instanceName : 'chess', node_env : 'development', reposerver : 'https://git.bbh.org.in' } // options
  2511. )
  2512. // We first load the default and then override with a runconfig if it exists else we override with the interactive prompts.
  2513. // Then acquire and reload and replace this default.
  2514. var hasElxr = function(path, options, cb) {
  2515. // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
  2516. options = options || {};
  2517. var tasks = [
  2518. '/elxr' // Is there a subfolder named elxr
  2519. , '/elxr/.git' // which is self git repository
  2520. , '/elxr/.elxr' // and has .elxr subfolder
  2521. , '/elxr/.elxr/' + __ALIAS__STAMP__ // Which has our stamp.
  2522. ]
  2523. if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
  2524. var value = existsFolderSync(path + tpath);
  2525. return { value, done : acc && !value };
  2526. }).value }
  2527. if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
  2528. var value = existsFolderSync(path + tpath);
  2529. return { value, done : acc && !value };
  2530. }).value );
  2531. return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
  2532. var value = existsFolderSync(path + tpath);
  2533. return { value, done : acc && !value };
  2534. }).value);
  2535. }
  2536. var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); }
  2537. var detectfromroot = function(root){
  2538. return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(root) ) }
  2539. }
  2540. var detectLocalInstances = function () {
  2541. console.log(`launchpath = ${launchpath}`)
  2542. console.log(`thisscriptdir = ${thisscriptdir}`)
  2543. // PB : TODO -- !Postpone this.
  2544. console.log(`instanceroot = ${instanceroot}`) // Not yet confirmed...
  2545. // Note : Paths should already be normalized fefore this.
  2546. var root = instanceroot;
  2547. var detected = { root };
  2548. var instanceoptions = [clioverrides]
  2549. return hasElxr(launchpath).then( (elxrCliExists) => {
  2550. // We need a reference to the root director for elxr cli to be properly oriented.
  2551. if (( elxrCliExists && path.normalize(launchpath + '/elxr')) === thisscriptdir) {
  2552. // We were run from the proper root with elxr cli in the subfolder.
  2553. instanceroot = root = launchpath;
  2554. instanceoptions.splice( 0, 0, detected = { root })
  2555. instanceoptions.splice( 0, 0, detectfromroot(root))
  2556. }
  2557. else {
  2558. if(path.normalize(launchpath + '/elxr') === thisscriptdir) {
  2559. // elxrCliExists is false -- and yet thiscriptdir is still proper.
  2560. // PB : TODO -- Maybe a warning / abort if for some reason this scriptdir should not be taken over...
  2561. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.')
  2562. instanceroot = root = launchpath;
  2563. instanceoptions.splice( 0, 0, detected = { root })
  2564. instanceoptions.splice( 0, 0, detectfromroot(root))
  2565. }
  2566. else if (launchpath === thisscriptdir) {
  2567. var parentHasElxr = hasElxrSync(launchpath + '/..')
  2568. // PB : TODO -- verify if we have .elxr folder in the parent...
  2569. if(!parentHasElxr) {
  2570. // ! thisscriptdir is not elxr.
  2571. console.error('Invalid run location in subfolder that looks like elxr. We should probably abort as elxr will not sync.')
  2572. }
  2573. // Same directory doesn't mean we are being run from elxr sub directory.
  2574. // In standalone build script we may or not be in the same location.
  2575. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  2576. // Unbuilt therefore we are in the elxr sub directory.
  2577. instanceroot = root = path.normalize(launchpath + '/..');
  2578. instanceoptions.splice( 0, 0, detected = { root });
  2579. instanceoptions.splice( 0, 0, detectfromroot(root));
  2580. }
  2581. else {
  2582. // Built version.
  2583. // We could have been run from the elxr subfolder. Highly likely that the built version isn't the full elxr.
  2584. if(parentHasElxr) {
  2585. // Built version was run from the full elxr subfolder. Should work
  2586. // PB : TODO -- but we should switch to the full version...
  2587. instanceroot = root = path.normalize(launchpath + '/..');
  2588. instanceoptions.splice( 0, 0, detected = { root })
  2589. instanceoptions.splice( 0, 0, detectfromroot(root))
  2590. }
  2591. else {
  2592. instanceroot = root = launchpath;
  2593. instanceoptions.splice( 0, 0, detected = { root })
  2594. instanceoptions.splice( 0, 0, detectfromroot(root))
  2595. // Assume current launchpath is a new instance and create.
  2596. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  2597. // if(clioverrides.instanceName) {
  2598. // if(clioverrides.node_env) {
  2599. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  2600. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  2601. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  2602. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  2603. // // eg : floder name can be elixir01 but instance name is elixr
  2604. // }
  2605. // else {
  2606. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + 'development')
  2607. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  2608. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  2609. // }
  2610. // }
  2611. // else {
  2612. // instanceroot = root = launchpath;
  2613. // if(clioverrides.node_env) {
  2614. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  2615. // instanceoptions.splice( 0, 0, detectfromroot(root))
  2616. // }
  2617. // else {
  2618. // // Nothing was specified... We only have one option from root.
  2619. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  2620. // }
  2621. // }
  2622. }
  2623. }
  2624. }
  2625. else {
  2626. if(elxrCliExists) {
  2627. instanceroot = root = launchpath;
  2628. instanceoptions.splice( 0, 0, detected = { root })
  2629. instanceoptions.splice( 0, 0, detectfromroot(root))
  2630. }
  2631. }
  2632. }
  2633. instanceroot = detected.root
  2634. __default.root = root;
  2635. clioverrides.root = clioverrides.root || root;
  2636. // Resolves empty array when No known instances detected.
  2637. return Promise.resolve(instanceoptions)
  2638. })
  2639. }
  2640. var getReconfirmAll = ()=>{return { instanceName : true, instanceType : true, reposerver : true, username : true, password : true } }
  2641. if(clioverrides.reconfirm) {
  2642. var reconfirm = getReconfirmAll()
  2643. }
  2644. else { var reconfirm = {}; }
  2645. var shouldPrompt = function(k, possiblePrompts, target){
  2646. return ((possiblePrompts[k] !== undefined && possiblePrompts[k] !== null) && target[k] !== possiblePrompts[k]
  2647. || (possiblePrompts[k] === undefined || possiblePrompts[k] === null) && (target[k] === undefined || target[k] === null)
  2648. || reconfirm[k])
  2649. }
  2650. var getBoundEachPrompt = function(target, possiblePrompts, promptables, choices, promptsfilter) {
  2651. return function(prompts, k, i, a){
  2652. // No local instances config found. We use a default initialized instance available in selectedinstance
  2653. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  2654. // PB : TODO -- selectedinstance === __default check to prompt everything...
  2655. if( shouldPrompt(k, possiblePrompts, target) ) {
  2656. delete reconfirm[k];
  2657. // console.log(k)
  2658. // console.dir(possiblePrompts); //console.dir(target)
  2659. prompts.push(async ()=>{
  2660. // PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
  2661. // We take a snapshot... Shallow.. !! If required deep should be used based on use case.
  2662. // If latest altered state is required we can reerence this directly.
  2663. // var asyncthis = Object.assign(this);
  2664. promptables[k].choices = choices[k]
  2665. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  2666. return await target[k]
  2667. })
  2668. }
  2669. delete possiblePrompts[k] // PB : TODO We should keep this around instead of deleting so we can do a second pass if required.
  2670. return prompts
  2671. }
  2672. }
  2673. var __interactive_prompts = function( target, choices, promptsfilter ){
  2674. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  2675. var interactionpoints = {
  2676. runchoice : {
  2677. label :
  2678. `Choose an option :
  2679. d) Install the default chess instance.
  2680. => elxr i chess node_env=development --default
  2681. n) Create your custom new instance interactively
  2682. => elxr i {{instanceName}} node_env={{environment}}
  2683. i) Choose an instance and environment to install
  2684. => elxr i {{instanceName}} node_env={{environment}}
  2685. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  2686. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  2687. h) Help
  2688. q) Quit
  2689. : `
  2690. , choices : []
  2691. , defaultchoice : 'c'
  2692. , interpret : function(choice){
  2693. var interpret_map = {
  2694. d : function(){
  2695. processedArgs._[0] = 'i'
  2696. target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  2697. target.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  2698. target.reposerver = 'https://git.bbh.org.in'
  2699. }
  2700. , n : function() { processedArgs._[0] = 'i' }
  2701. , i : function() { processedArgs._[0] = 'i' }
  2702. , c : async function() {
  2703. Object.defineProperty(this, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  2704. label : `Enter cmd :
  2705. p) pull
  2706. Default <= p
  2707. : `
  2708. , defaultchoice : 'pull'
  2709. }
  2710. ));
  2711. var cmd = await target['cmd'];
  2712. if (!cmd || cmd === 'p') { target['cmd'] = processedArgs._[0] = 'pull' }
  2713. else target['cmd'] = processedArgs._[0] = cmd
  2714. return cmd;
  2715. }
  2716. , h : function() { console.log(elxr.help()); process.exit() } // PB : TODO -- Why do we need log.
  2717. , q : function() { process.exit() }
  2718. }
  2719. var __interpreter = interpret_map['c']
  2720. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  2721. if(interpret_map[choice]) __interpreter = interpret_map[choice];
  2722. return __interpreter.call(target)
  2723. }
  2724. }
  2725. , instanceName : { label : `Enter Instance Name ( <= ${target.instanceName || 'chess'} ) : `
  2726. , choices : choices['instanceName'], defaultchoice : 'chess'}
  2727. , instanceType : { label : `Enter Instance Type ( <= ${target.instanceType || 'development'} ) : `
  2728. , choices : choices['instanceType'], defaultchoice : 'development'}
  2729. , reposerver : { label : `Enter Repo Url ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `
  2730. , choices : choices['reposerver'], defaultchoice : 'https://git.bbh.org.in'}
  2731. , get username() { return { label : `Enter User Id for ${target.reposerver} ( <= ${target.username || 'chess'} ) : `
  2732. , choices : choices['username'], defaultchoice : 'chess'} }
  2733. , get password() { return { label : `Enter Password for ${target.username} @ ${target.reposerver} ( <= ${target.password || ''} ) : `
  2734. , choices : choices['password'], defaultchoice : '***'} }
  2735. , get email() { return { label : `Enter Email for ${target.username} @ ${target.reposerver} ( <= ${target.email || ''} ) : `
  2736. , choices : choices['email'], defaultchoice : 'guest@bbh.org.in'} }
  2737. }
  2738. function getPromptKeys() {
  2739. if(! (processedArgs.label || processedArgs._[0]) ) return Object.assign({}, interactionpoints);
  2740. return promptkeys
  2741. }
  2742. var eachPrompt = getBoundEachPrompt( target, getPromptKeys() , interactionpoints, choices, promptsfilter)
  2743. return Object.keys(promptsfilter || interactionpoints).reduce(eachPrompt, [])
  2744. }
  2745. var downloadsdir = '../Downloads';
  2746. var prerequisites = [
  2747. {
  2748. shellcmd: 'git',
  2749. name : 'git',
  2750. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  2751. , installer: 'Git-2.31.0-64-bit.exe'
  2752. , installcmd: ['cmd', ['/c', 'start',
  2753. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  2754. , '/VERYSILENT'
  2755. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  2756. ]]
  2757. , preinstallsteps: function() {
  2758. var steps = [
  2759. () => {
  2760. if (!existsSync(downloadsdir + '/' + this.installer)) {
  2761. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  2762. }
  2763. else return Promise.resolve(true)
  2764. }
  2765. ]
  2766. var prompts = this.getuser(null, ()=>{
  2767. // console.log('preinstallsteps')
  2768. // var gitUser = 'guest';
  2769. // var gitEmail = 'guest@bbh.org.in';
  2770. // var prompts = [];
  2771. // prompts.push( ()=>{ return cli.prompt(choices['username'], 'git user name').then(gituser => gitUser = gituser) } )
  2772. // prompts.push( ()=>{ return cli.prompt(choices['useremail'], 'git user email').then(gitemail => gitEmail = gitemail) } )
  2773. // console.log('prompting in preinstallsteps')
  2774. // return any(prompts).then(()=>{
  2775. // var steps = [
  2776. // ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  2777. // , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  2778. // ]
  2779. // return any(steps.map(getshelltask)).then(() => {
  2780. // })
  2781. // });
  2782. return Promise.resolve(true)
  2783. })
  2784. return any([any(steps), prompts])
  2785. }
  2786. , installsteps: function () {
  2787. return any([this.installcmd].map(getshelltask))
  2788. }
  2789. , postinstallsteps: function(err, users){
  2790. return this.getuser(null, (err, data)=>{
  2791. // ignore err and proceed with data as guest.
  2792. console.dir(data)
  2793. if(data && data.length === 1 && !shouldPrompt('username', promptkeys, selectedinstance) ) {
  2794. return username = data[0];
  2795. }
  2796. data = data || ['guest']
  2797. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  2798. console.log('prompting in postinstallsteps')
  2799. var username = 'guest';
  2800. var email = 'guest@bbh.org.in';
  2801. var password = '***';
  2802. return any( getInteractionPoints(selectedinstance, promptkeys, { username, password, email}) ).then(()=>{
  2803. if(!data.find(e => e === selectedinstance.username)) {
  2804. var steps = [
  2805. ['git', ['config', '--global', '--add', 'user.name', `${username}`]]
  2806. , ['git', ['config', '--global', '--add', 'user.email', `${email}`]]
  2807. ]
  2808. return any(steps.map(getshelltask)).then(() => {
  2809. })
  2810. }
  2811. else {
  2812. return Promise.resolve(true)
  2813. }
  2814. });
  2815. })
  2816. }
  2817. , install: function () {
  2818. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  2819. }
  2820. , verifyAndInstall : function(){
  2821. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  2822. if(exists) {
  2823. // return any(['git', ['config', '--global', '-l']].map(getshelltask))
  2824. return this.postinstallsteps.bind(this)()
  2825. }
  2826. return this.install();
  2827. });
  2828. }
  2829. , getuser : function(repo, onResult){
  2830. var __onResult = onResult || function(e, data){
  2831. data = data || []
  2832. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  2833. // console.dir(choices)
  2834. return data[0]
  2835. }
  2836. var globalOrLocal = '--global';
  2837. if(repo) globalOrLocal = '--local'
  2838. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(getshelltask)).then((result)=>{
  2839. // not yet configured.
  2840. if(!result.success) return __onResult(result)
  2841. else {
  2842. var users = result.messages[0].trim().split('\n');
  2843. if(users.length === 0 ||
  2844. users.length === 1 && users[0] === 'guest') {
  2845. return __onResult(result)
  2846. }
  2847. else {
  2848. return __onResult(null, Array.from( new Set( users ) ) ); }// PB : TODO == We should probably prompt with all the users available for selection !
  2849. }
  2850. })
  2851. .catch((e)=>{
  2852. console.log(e)
  2853. return __onResult(e)
  2854. })
  2855. }
  2856. }
  2857. ,
  2858. {
  2859. shellcmd: 'node',
  2860. name : 'ndoe',
  2861. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  2862. , installer: 'node-v14.16.0-x64.msi'
  2863. , installcmd: ['MSIEXEC.exe', ['/i'
  2864. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  2865. , 'ACCEPT=YES', '/passive']]
  2866. , install : function() { return any([this.installcmd].map(getshelltask)).then(() => { }) }
  2867. }
  2868. ]
  2869. for(var i=0; i<prerequisites.length; i++) {
  2870. prerequisites[prerequisites[i].name] = prerequisites[i];
  2871. }
  2872. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  2873. function ensureDirectoryExistence(filePath) {
  2874. var dirname = path.dirname(filePath);
  2875. if (fs.existsSync(dirname)) {
  2876. return filePath;
  2877. }
  2878. ensureDirectoryExistence(dirname);
  2879. fs.mkdirSync(dirname);
  2880. return filePath;
  2881. }
  2882. var mainTasks = [];
  2883. function verifyAndInstallPrerequisites() {
  2884. fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
  2885. // PB : TODO include and build from files... using rollup..
  2886. var downloadbatch =
  2887. `::**************************************************************************
  2888. :Download_ <url> <File>
  2889. Powershell.exe ^
  2890. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  2891. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  2892. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  2893. exit /b
  2894. ::**************************************************************************`
  2895. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch)
  2896. var windowselevate =
  2897. `
  2898. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  2899. <script language="vbscript">
  2900. document.title = "elxr control panel"
  2901. self.ResizeTo 200,600
  2902. Sub Window_Onload
  2903. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  2904. End Sub
  2905. Set objShell = CreateObject("WScript.Shell")
  2906. Set objENV = objShell.Environment("Process")
  2907. dim NODE_ENV
  2908. NODE_ENV = objENV("NODE_ENV")
  2909. </script>
  2910. <script language="javascript">
  2911. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  2912. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  2913. // alert(windowselevate.commandLine)
  2914. var args = windowselevate.commandLine.split('"').slice(3);
  2915. // alert(args)
  2916. var processedArgs = { _ : [] }
  2917. var namedArgs = [];
  2918. for(var item in args){
  2919. if(args[item].charAt(0) === '-'){
  2920. namedArgs.push(args[item])
  2921. var split = args[item].split('=');
  2922. processedArgs[split[0].slice(2)] = split[1] || true;
  2923. }
  2924. else processedArgs._.push(args[item]);
  2925. }
  2926. // args = args.forEach(function(item){ })
  2927. // alert('processedArgs._ : ' + processedArgs._);
  2928. // alert(processedArgs.runas);
  2929. // PB : TODO -- Convert all the cli args back to string.
  2930. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  2931. // alert(cargs)
  2932. var shell = new ActiveXObject('shell.application');
  2933. // alert('launching node privilged. ' + processedArgs['nodepath'])
  2934. // shell.ShellExecute('where', 'node', '', '', 10);
  2935. // shell.ShellExecute('cmd.exe', '/k notepad.exe', '', 'runas', 1);
  2936. // shell.ShellExecute('cmd.exe ', '/k node "' + cargs + '"', '', 'runas', 1);
  2937. shell.ShellExecute('node', cargs, '', 'runas', 1);
  2938. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  2939. var fso = new ActiveXObject('Scripting.FileSystemObject');
  2940. window.onload = function() {
  2941. document.body.style.backgroundColor = 'black';
  2942. document.body.style.fontFamily = 'arial';
  2943. var log = document.createElement('div');
  2944. log.innerHTML='Please Wait';
  2945. function l(msg){ log.innerHTML+= msg; };
  2946. log.style.color = 'blue';
  2947. log.style.width = '95%';
  2948. log.id = 'log';
  2949. document.body.appendChild(log);
  2950. l('<Br/>Current config : ')
  2951. l('<Br/>NODE_ENV = ' + NODE_ENV)
  2952. l('<Br/>cmd = ' + processedArgs._[0])
  2953. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  2954. l('<Br/><Br/>')
  2955. var timer = function(){
  2956. l('.');
  2957. if(fso.FileExists("run.done")) close();
  2958. else window.setTimeout(timer, 1000);
  2959. };
  2960. window.setTimeout(timer, 3000);
  2961. };
  2962. </script>
  2963. </html>
  2964. `
  2965. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate)
  2966. var downloadtasks = [];
  2967. var installtasks = [];
  2968. prerequisites.forEach(preq => {
  2969. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  2970. if (exists) console.log(`${preq.shellcmd} exists`)
  2971. else {
  2972. console.log(`${preq.shellcmd} is not installed`)
  2973. return preq.preinstallsteps.call(preq).then(() => {
  2974. installtasks.push(preq.install.bind(preq))
  2975. })
  2976. }
  2977. }))
  2978. })
  2979. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  2980. }
  2981. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  2982. return {
  2983. get (){
  2984. return cli.prompt( promptable.choices, promptable.label, promptable.defaultchoice ).then(propValue => {
  2985. var asyncprop = Promise.resolve(propValue)
  2986. if(promptable.interpret){
  2987. asyncprop = promptable.interpret(propValue)
  2988. }
  2989. return asyncprop.then(
  2990. ()=>{
  2991. Object.defineProperty(this, propName, {
  2992. value: propValue,
  2993. writable: true,
  2994. configurable : true,
  2995. enumerable : true
  2996. });
  2997. return propValue
  2998. }
  2999. )
  3000. })
  3001. }
  3002. // , set (propValue){
  3003. // Object.defineProperty(this, propName, {
  3004. // value: propValue,
  3005. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  3006. // configurable : true,
  3007. // enumerable : true
  3008. // })
  3009. // return propValue;
  3010. // }
  3011. , configurable : true
  3012. , enumerable : true
  3013. }
  3014. }
  3015. function acquirelocalinstances(selected){
  3016. // utils.assign is used to cleanup duplicates...
  3017. var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
  3018. return chessinstances
  3019. }
  3020. function findlocalinstances(chessinstances, instanceoptions){
  3021. // We can expect a .elxr at each level.
  3022. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../..' /* instanceNames */].
  3023. earlyreduce( ( value, p, i, a )=>{
  3024. var localinstancesPath = `${instanceroot}/${p}.elxr`;
  3025. if(existsSync( localinstancesPath )) {
  3026. try {
  3027. var chessinstances = acquirelocalinstances( { localinstancesPath } )
  3028. return Object.keys(chessinstances).earlyreduce( ( value, instanceName) => {
  3029. return Object.keys(chessinstances[instanceName]).earlyreduce( (value, instanceType) => {
  3030. if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize( instanceroot) ) {
  3031. instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType])
  3032. return {
  3033. value : chessinstances[instanceName][instanceType]
  3034. , done : true
  3035. };
  3036. }
  3037. })
  3038. })
  3039. }
  3040. catch(e){
  3041. return { }
  3042. }
  3043. }
  3044. else return { }
  3045. }
  3046. )
  3047. }
  3048. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  3049. var selectedinstance = null;
  3050. var chessinstances = { current_run : {} };
  3051. var promptkeys = {
  3052. cmd : processedArgs._[0] || 'pull'
  3053. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  3054. // 'instanceName' : true
  3055. // , 'node_env' : true
  3056. // , username : ''
  3057. // , runchoice : 'c'
  3058. }
  3059. // promptkeys.runchoice = promptkeys.cmd ? 'c' : undefined
  3060. function createLocalChessInstance( cfg ){
  3061. // return createInstance(cfg)
  3062. reconfirm = getReconfirmAll()
  3063. var inst = {};
  3064. var __new = Object.assign({}, __default, cfg)
  3065. inst[cfg.node_env] = __new; return inst;
  3066. }
  3067. var choices = {
  3068. 'instanceName' : []
  3069. , 'reposerver' : []
  3070. , 'instanceType' : []
  3071. , username : ['guest', 'chessdemo', 'demo']
  3072. }
  3073. var getInteractionPoints = function(detectedinstanceoptions, possiblePrompts, promptsfilter){
  3074. var instances = []
  3075. var reposervers = [];
  3076. var instanceNames = []
  3077. var instanceTypes = ['development', 'production'];
  3078. Object.keys( chessinstances).forEach(instanceName => {
  3079. if(instanceName === 'current_run') return;
  3080. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  3081. var instance = chessinstances[instanceName][node_env];
  3082. reposervers = reposervers.concat(instance.reposervers)
  3083. if(instance.reposerver) reposervers.push(instance.reposerver)
  3084. instances.push(instance)
  3085. instanceTypes.push(instance.node_env)
  3086. instanceNames.push(instance.instanceName)
  3087. })
  3088. })
  3089. instances = instances.concat(detectedinstanceoptions)
  3090. if(selectedinstance['instanceName']) instanceNames.push(selectedinstance['instanceName'])
  3091. if(possiblePrompts['instanceName']) instanceNames.push(possiblePrompts['instanceName'])
  3092. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers'])
  3093. choices['instanceName'] = Array.from( new Set(instanceNames.concat(choices['instanceName'])) )
  3094. choices['reposerver'] = Array.from( new Set(reposervers.concat(choices['reposerver'])) )
  3095. choices['instanceType'] = Array.from( new Set(instanceTypes.concat(choices['instanceType'])) )
  3096. return __interactive_prompts(selectedinstance, choices, promptsfilter)
  3097. }
  3098. var detection_state = {
  3099. localInstanceDetected : false
  3100. }
  3101. const https = require('https')
  3102. const http = require('http');
  3103. const { resolve } = require('path');
  3104. const RESTAPI = (function(){
  3105. // Singleton
  3106. function RESTAPI(){}
  3107. // RESTAPI.create = RESTAPI; // Returns the one singe instance which is the class itself
  3108. // const options = {
  3109. // hostname: 'whatever.com',
  3110. // port: 443,
  3111. // path: '/todos',
  3112. // method: 'POST',
  3113. // headers: {
  3114. // 'Content-Type': 'application/json',
  3115. // 'Content-Length': data.length
  3116. // }
  3117. // }
  3118. RESTAPI.method = function(options, resolve, reject){
  3119. var __method = function() {
  3120. options.headers = options.headers || { 'Content-Type': 'application/json' }
  3121. if(options.payload) {
  3122. const data = new TextEncoder().encode( JSON.stringify(options.payload) )
  3123. options.headers = options.headers || {
  3124. 'Content-Type': 'application/json',
  3125. 'Content-Length': data.length
  3126. }
  3127. }
  3128. if(!options.authenticatepost) options.headers.Authorization = `token ${usertokens[options.username]}`
  3129. var acquirer = getHTTPorS(options)
  3130. const req = acquirer.request(options, res => {
  3131. if (res.statusCode < 200 || res.statusCode >= 300) {
  3132. return reject(new Error('statusCode=' + res.statusCode));
  3133. }
  3134. var body = [];
  3135. // res.setEncoding('utf8');
  3136. res.on('data', function(chunk) {
  3137. body.push(chunk);
  3138. });
  3139. res.on('end', function() {
  3140. try {
  3141. body = JSON.parse(Buffer.concat(body).toString());
  3142. } catch(e) {
  3143. reject(e);
  3144. }
  3145. resolve(body);
  3146. });
  3147. });
  3148. req.on('error', error => {
  3149. console.error(error)
  3150. reject(error)
  3151. })
  3152. if(options.payload) req.write(data)
  3153. req.end()
  3154. }
  3155. if(!options.authenticatepost && !usertokens[options.username]) {
  3156. RESTAPI.authenticate(options, function(tokenresp){
  3157. usertokens[options.username] = tokenresp.sha1
  3158. __method(options, resolve, reject)
  3159. },
  3160. function(err){ throw err}
  3161. )
  3162. }
  3163. else __method(options, resolve, reject)
  3164. }
  3165. RESTAPI.post = RESTAPI.method
  3166. var usertokens = {}
  3167. RESTAPI.authenticate = function(options, resolve, reject){
  3168. options.headers = options.headers || { 'Content-Type': 'application/json' }
  3169. if(!usertokens[options.username]) {
  3170. // Authenticate and acquire token.
  3171. // https://git.bbh/api/v1/users/<username>/tokens
  3172. // curl -XPOST -H "Content-Type: application/json" -k -d '{"name":"demo"}' -u demo:demo123 http://git.bbh/api/v1/users/demo/tokens
  3173. var _options = Object.assign({}, options)
  3174. // _options.username = 'demo'
  3175. // _options.password = 'demo123'
  3176. _options.method = 'POST'
  3177. _options.headers.Authorization = `Basic ${Buffer.from(`${_options.username}:${_options.password}`).toString('base64')}`
  3178. _options.path = `/api/v1/users/${_options.username}/tokens`
  3179. _options.authenticatepost = true
  3180. var postoptions = { name : _options.username }
  3181. delete _options.username
  3182. delete _options.password
  3183. _options.payload = postoptions
  3184. RESTAPI.post( _options, function(tokenresp){
  3185. // tokenresp = JSON.parse(tokenresp)
  3186. usertokens[options.username] = tokenresp.sha1
  3187. resolve(tokenresp)
  3188. },
  3189. function(err){ reject(err) }
  3190. )
  3191. }
  3192. else resolve(tokenresp.sha1)
  3193. }
  3194. RESTAPI.get = RESTAPI.post = RESTAPI.method
  3195. return RESTAPI
  3196. })();
  3197. var getHTTPorS = function(options){ return options.protocol.startsWith('https') ? https : http; }
  3198. const GITEA = (function(){
  3199. function GITEA(){}
  3200. GITEA.repository = {
  3201. fork( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  3202. // forkoptions = { owner : httpoptions.username, repo : {{reoptoFork}} }
  3203. // giteaoptions = {
  3204. // organization string
  3205. // --- organization name, if forking into an organization
  3206. // }
  3207. // http://try.gitea.io/api/v1/repos/{owner}/{repo}/forks
  3208. httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}/forks`
  3209. httpoptions.method = 'POST'
  3210. httpoptions.payload = giteaoptions;
  3211. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  3212. }
  3213. , updateattributes( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  3214. httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}`
  3215. httpoptions.method = 'PATCH'
  3216. httpoptions.payload = giteaoptions;
  3217. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  3218. }
  3219. }
  3220. GITEA.user = {
  3221. getuser( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  3222. // ​/users​/{username} // Get a user
  3223. httpoptions.path = `/api/v1/users/${httpoptions.username}`
  3224. httpoptions.method = 'GET'
  3225. return RESTAPI.get(httpoptions, giteaoptions, resolve || function(){}, reject || function(){} )
  3226. }
  3227. }
  3228. return GITEA
  3229. })();
  3230. // Wrapper for Git shell operations. Some meta operations will map to a bunch of GIT commands.
  3231. const GIT = (function(){
  3232. function GIT(){}
  3233. Object.assign(GIT, {
  3234. 'switch user'(username){
  3235. var server = new URL(selectedinstance.reposerver);
  3236. return GITEA.user.getuser({ hostname : server.host, protocol : server.protocol
  3237. , username : selectedinstance.username, password : selectedinstance.password
  3238. }).then(()=>{
  3239. return nodeShellExec('git', ['config', '--replace-all', 'user.name', username],
  3240. {
  3241. inherit: true, shell: true,
  3242. env: process.env
  3243. , cwd: instanceroot + '/' + repo
  3244. , runas: processedArgs.runas
  3245. , title: `'git', ${['config', '--replace-all', 'user.name', username].join(' ')}`
  3246. })
  3247. }
  3248. )
  3249. .catch(e => {
  3250. console.error(e + 'Could not switch. Probably no such user.')
  3251. })
  3252. }
  3253. })
  3254. return GIT
  3255. })();
  3256. function createInstanceData(target, source) {
  3257. var sourceinstance = source || target;
  3258. console.dir(sourceinstance)
  3259. var args = {
  3260. remotebase : sourceinstance.reposerver + '/chess/'
  3261. , sourcerepo : sourceinstance.repo || 'chess-data'
  3262. , targetrepo : `${target.instanceName}-data-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  3263. }
  3264. if(sourceinstance.local) {
  3265. var options = {
  3266. inherit: true, shell: true,
  3267. env: process.env
  3268. , cwd : instanceroot
  3269. , runas: processedArgs.runas
  3270. }
  3271. var cmdseq = [
  3272. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  3273. ]
  3274. return any(cmdseq.map(getshelltask)).then(() => { return true })
  3275. }
  3276. else {
  3277. // http://try.gitea.io/api/v1/org/{org}/repos
  3278. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  3279. throw 'createInstanceData is possible only within the same repository server.'
  3280. }
  3281. var server = new URL(target.reposerver);
  3282. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  3283. , username : target.username, password : target.password
  3284. }
  3285. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  3286. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  3287. return GITEA.repository.updateattributes( {
  3288. hostname : server.host, protocol : server.protocol
  3289. , username : target.username, password : target.password
  3290. }
  3291. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  3292. , { name : `${args.targetrepo}`}
  3293. )
  3294. }
  3295. )
  3296. }
  3297. // GITEA.repository.updateattributes( {
  3298. // hostname : server.host, protocol : server.protocol
  3299. // , username : selectedinstance.username, password : selectedinstance.password
  3300. // }
  3301. // , { repo : `chess-config`, owner : selectedinstance.username }
  3302. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  3303. // )
  3304. // return selectedinstance
  3305. }
  3306. function createInstance(target, source) {
  3307. var sourceinstance = source || target;
  3308. console.dir(sourceinstance)
  3309. var args = {
  3310. remotebase : sourceinstance.reposerver + '/chess/'
  3311. , sourcerepo : sourceinstance.repo || 'chess-config'
  3312. , targetrepo : `${target.instanceName}-config-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  3313. }
  3314. if(sourceinstance.local) {
  3315. var options = {
  3316. inherit: true, shell: true,
  3317. env: process.env
  3318. , cwd : instanceroot
  3319. , runas: processedArgs.runas
  3320. }
  3321. var cmdseq = [
  3322. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  3323. ]
  3324. return any(cmdseq.map(getshelltask)).then(() => { return true })
  3325. }
  3326. else {
  3327. // http://try.gitea.io/api/v1/org/{org}/repos
  3328. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  3329. throw 'createInstance is possible only within the same repository server.'
  3330. }
  3331. var server = new URL(target.reposerver);
  3332. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  3333. , username : target.username, password : target.password
  3334. }
  3335. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  3336. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  3337. return GITEA.repository.updateattributes( {
  3338. hostname : server.host, protocol : server.protocol
  3339. , username : target.username, password : target.password
  3340. }
  3341. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  3342. , { name : `${args.targetrepo}`}
  3343. )
  3344. }
  3345. )
  3346. }
  3347. // GITEA.repository.updateattributes( {
  3348. // hostname : server.host, protocol : server.protocol
  3349. // , username : selectedinstance.username, password : selectedinstance.password
  3350. // }
  3351. // , { repo : `chess-config`, owner : selectedinstance.username }
  3352. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  3353. // )
  3354. // return selectedinstance
  3355. }
  3356. var skipprerequisites = false;
  3357. function initinstances(selected_overrides) {
  3358. var root = selected_overrides.root // We should always have this coz we are running at some place which is fixed by detectLocalInstances.
  3359. var instanceName = selected_overrides.instanceName
  3360. || clioverrides.instanceName
  3361. // || processedArgs._[1]
  3362. || chessinstances.current_run.instanceName
  3363. var node_env = selected_overrides.node_env
  3364. || clioverrides.node_env
  3365. // || processedArgs.node_env
  3366. || chessinstances.current_run.node_env
  3367. var reposerver = selected_overrides.reposerver
  3368. || clioverrides.reposerver
  3369. // || processedArgs.node_env
  3370. || chessinstances.current_run.reposerver
  3371. if(!instanceName) {
  3372. promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  3373. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  3374. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  3375. }
  3376. if(!node_env) {
  3377. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  3378. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  3379. }
  3380. if(!reposerver) {
  3381. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  3382. }
  3383. chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
  3384. instanceName, node_env, root : selected_overrides.root, reposerver : selected_overrides.reposerver /* promptkeys['reposerver'] */ } );
  3385. chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root }
  3386. if(path.normalize(selected_overrides.root) !== path.normalize(chessinstances[instanceName][node_env].root)) {
  3387. throw "instanceName and instanceType specified doesn't match whats already present do you want to continue " + chessinstances[instanceName][node_env].root + ' does not match ' + selected_overrides.root
  3388. }
  3389. // Override sequence.
  3390. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  3391. selectedinstance = utils.assign(
  3392. chessinstances[instanceName][node_env]
  3393. , clioverrides
  3394. , selected_overrides
  3395. // , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
  3396. );
  3397. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  3398. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  3399. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  3400. // // Brand New.
  3401. // selectedinstance = Object.assign( __default, selectedinstance )
  3402. // }
  3403. if(!selectedinstance.repos[0].repo) {
  3404. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  3405. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  3406. }
  3407. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  3408. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  3409. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  3410. }
  3411. // Config from server always override merges into selection except for the current selection.
  3412. // PB : TODO -- utils.assign Array merges are non-distinct...
  3413. chessinstances[instanceName][node_env] = selectedinstance;
  3414. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  3415. cacheWriteInstanceConfig(chessinstances)
  3416. // PB : TODO -- We should probably write the new server config also...
  3417. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  3418. return chessinstances
  3419. }
  3420. var skipprereqs = {}
  3421. var maintask = () => {
  3422. // Default cmd to run !
  3423. processedArgs._[0] === processedArgs._[0] || 'pull';
  3424. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  3425. if(!noprerequisites[processedArgs._[0]]
  3426. && !skipprereqs[processedArgs._[0]]
  3427. ) {
  3428. return prerequisites.git.verifyAndInstall().then(()=>{
  3429. var e = { message : 'verifyAndInstall', success : true}
  3430. var inittasks = []
  3431. if(!detection_state.localInstanceDetected) {
  3432. var specifictask = ()=>{ return createInstance(selectedinstance) }
  3433. var commantask = () => { preworkerconfig(); return elxrworker(true) }
  3434. if(!__isElevated) {
  3435. }
  3436. else {
  3437. specifictask = ()=>{ Promise.resolve(true) }
  3438. }
  3439. inittasks.push(specifictask().then( commantask ))
  3440. }
  3441. else {
  3442. var specifictask = ()=>{ return acquireConfig(selectedinstance) }
  3443. var commantask = () => { preworkerconfig(); return elxrworker(true) }
  3444. if(!__isElevated) {
  3445. }
  3446. else {
  3447. specifictask = ()=>{ return Promise.resolve(true) }
  3448. }
  3449. inittasks.push( specifictask().catch((err) => {
  3450. e = err;
  3451. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  3452. console.error(err)
  3453. }).then( commantask )
  3454. // .finally(()=>{
  3455. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  3456. // if(!e.success) fs.writeFileSync('run.done', 'error');
  3457. // // return process.exit()
  3458. // }))
  3459. )
  3460. }
  3461. return any(inittasks)
  3462. })
  3463. }
  3464. else {
  3465. console.log('cmd has no preqs or has been configured to skip preqs')
  3466. preworkerconfig()
  3467. return elxrworker()
  3468. }
  3469. }
  3470. var startElxr = function() {
  3471. const retaincount = 2
  3472. var min = runtimestamp;
  3473. var collect = []
  3474. if(reconfirmcmds[processedArgs.label || processedArgs._[0]]) {
  3475. reconfirm = getReconfirmAll()
  3476. }
  3477. return detectLocalInstances().then((detectedinstanceoptions)=>{
  3478. detectedinstanceoptions.splice(0,0, __default)
  3479. var cmdinstance = cmds[clioverrides.cmd]
  3480. var cmdprompts = cmdinstance.getPossiblePrompts()
  3481. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  3482. selectedinstance = utils.assign( ...detectedinstanceoptions.slice(-2), promptkeys )
  3483. // promptkeys = utils.assign(promptkeys, clioverrides)
  3484. if(cmdprompts.instanceName) {
  3485. // not an instanceless cmd.
  3486. console.dir(selectedinstance)
  3487. try {
  3488. chessinstances = acquirelocalinstances(selectedinstance);
  3489. findlocalinstances(chessinstances, detectedinstanceoptions)
  3490. initinstances(selectedinstance) // use the local instances for defaults if at all possible.
  3491. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  3492. var inst = initinstances(selectedinstance)
  3493. detection_state.localInstanceDetected = true;
  3494. return inst;
  3495. })
  3496. }
  3497. catch (e) {
  3498. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  3499. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  3500. return initinstances(selectedinstance)
  3501. })
  3502. // if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  3503. // // Weve not been told what to do.
  3504. // todo = todo.then(() => { return acquireChoices(selectedinstance) })
  3505. // }
  3506. todo = todo.then(() => {
  3507. try {
  3508. chessinstances = acquirelocalinstances(selectedinstance)
  3509. findlocalinstances(chessinstances, detectedinstanceoptions)
  3510. detectedinstanceoptions.splice(0,0, __default)
  3511. initinstances(selectedinstance)
  3512. detection_state.localInstanceDetected = true;
  3513. }
  3514. catch (e) {
  3515. // console.error(e)
  3516. console.log('No local instances config found in current root = ' + selectedinstance.root);
  3517. console.log('A config will be createed with the instance and environment chosen...')
  3518. // return (async ()=>{return await __default.reposerver})().then(()=>{
  3519. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  3520. // return selectedinstance = Object.assign(__default, selectedinstance);
  3521. // })
  3522. detection_state.localInstanceDetected = false;
  3523. return selectedinstance
  3524. }
  3525. })
  3526. }
  3527. return todo
  3528. }
  3529. else return Promise.resolve(true)
  3530. })
  3531. .then(()=>{
  3532. if(noprerequisites[processedArgs._[0]]
  3533. || skipprereqs[processedArgs._[0]]
  3534. ) {
  3535. return elxrworker()
  3536. }
  3537. if(!__isElevated) {
  3538. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`)
  3539. // collect garbage
  3540. return dirs( (dir)=>{
  3541. var matches = /run-(.*)/gm.exec(dir.name)
  3542. if(matches) {
  3543. if(+(matches[1]) < min) {
  3544. min = matches[1]
  3545. collect.splice( 0, 0, matches[1] )
  3546. }
  3547. else collect.push(matches[1])
  3548. }
  3549. }, `${selectedinstance.root}/.elxr` ).then(()=>{
  3550. // delete garbage
  3551. if(collect.length > retaincount) {
  3552. var asyncs = [];
  3553. while((collect.length - asyncs.length) > retaincount) {
  3554. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  3555. }
  3556. return Promise.all(asyncs)
  3557. }
  3558. else return true
  3559. })
  3560. }
  3561. else return true;
  3562. })
  3563. .then(()=>{
  3564. // PB : TODO -- Keep only the last n runs...
  3565. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  3566. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
  3567. if (!skipprerequisites && !__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
  3568. mainTasks.push(maintask)
  3569. return any(mainTasks);
  3570. })
  3571. }
  3572. acquireElevationState().then(() => {
  3573. return startElxr()
  3574. })
  3575. // detect if alread installed -> Take no action.
  3576. // download if no installer avalable -> next()
  3577. // install
  3578. function chackandinstall(items) {
  3579. var tasks = []
  3580. items.forEach(item => {
  3581. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  3582. })
  3583. return Promise.all(tasks).then(existances => {
  3584. existances.forEach((exists, i) => {
  3585. if (!exists) {
  3586. return downloadandinstall([items[i]])
  3587. }
  3588. })
  3589. })
  3590. }
  3591. function downloadandinstall(items) {
  3592. var tasks = []
  3593. items.forEach(item => {
  3594. tasks.push(getTaskDownload(item))
  3595. })
  3596. return Promise.all(tasks)
  3597. }
  3598. // Sample instances config.
  3599. // var instances = {
  3600. // "elixir": {
  3601. // "production": {
  3602. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  3603. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  3604. // , "exludeMergeRepos": {
  3605. // "elixir-config-development": true, "elixir-config-test": true
  3606. // , "elixir-config-production": true, "elixir-data": true
  3607. // }
  3608. // , "instanceName": "elixir", "node_env": "production"
  3609. // }
  3610. // },
  3611. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  3612. // }
  3613. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...