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 100KB

il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 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 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 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 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 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 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 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 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 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 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 ans
il y a 3 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676
  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 BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  12. const runtimestamp = (new Date()).getTime();
  13. function getVersion() { return BUILD_VERSION; }
  14. console.log(getVersion());
  15. // 'use strict';
  16. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  17. // PB : TODO --
  18. // runas bypass non elevated tasks when we request privelege
  19. // runas message is always error needs to be fixed.
  20. // runas wait needs to be parallelized.
  21. // suppress elevation check error messages
  22. // support runas lauched directly from shell.
  23. // pass in environment in hta to shellexecute.
  24. // PB : NOTE -- iife doesnt work if previous statement is not terminated by ;
  25. (function () {
  26. "use strict";
  27. if (!Array.prototype.earlyreduce) {
  28. Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
  29. var iterable = this;
  30. var donecallback = donecallback || (a=>a)
  31. var result = { value : initialValue === undefined ? iterable[0] : initialValue };
  32. initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
  33. // function *earlyReduceGenerator(acc, v, i, a) {
  34. for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
  35. var element = iterable[i]
  36. result = eachcallback(result, element, i, iterable)
  37. if(result.done) return donecallback(result)
  38. }
  39. // }
  40. return donecallback(result)
  41. }
  42. }
  43. }());
  44. const { existsSync } = require('fs');
  45. const fs = require('fs')
  46. const cliargs = utils.cliargs;
  47. const processedArgs = cliargs(process.argv.slice(2));
  48. console.dir(processedArgs)
  49. // PB : TODO -- defaults for valuless arguments if passed.
  50. // Object.keys(processedArgs).forEach(a=>{
  51. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  52. // }
  53. // })
  54. var clioverrides = { }
  55. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  56. clioverrides.node_env = processedArgs.node_env ?
  57. processedArgs.node_env || (process.env.NODE_ENV && process.env.NODE_ENV.trim())
  58. : (process.env.NODE_ENV && process.env.NODE_ENV.trim())
  59. ? (process.env.NODE_ENV && process.env.NODE_ENV.trim()): null;
  60. clioverrides.reconfirm = processedArgs.reconfirm
  61. var globSync = require('glob').sync;
  62. var ENV = Object.assign({}, process.env); // Shallow clone it.
  63. const { readdir } = require("fs").promises
  64. // Directory shallow walk and do perform on each dir.
  65. const dirs = async (perform, path) => {
  66. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  67. if (dir.isDirectory()) perform(dir)
  68. }
  69. }
  70. var getShellTask = (command, args, options) => {
  71. options = options || {}
  72. return () => {
  73. var p = nodeShellExec.apply(null, [command, args, Object.assign({
  74. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  75. }, options)
  76. ])
  77. if (options.ignorefailures) {
  78. return p.catch(e => {
  79. // Ignore. Not a major error.
  80. })
  81. }
  82. else return p;
  83. }
  84. }
  85. var callsheltask = (args) => { return () => { return nodeShellExec.apply(null, args) } }
  86. var callgitbashtask = (args) => { return () => {
  87. return nodeShellExec( `"${gitbash}"`, ['-c', `"${args[0]} ${args[1].join(' ')}"`], args[2]) }
  88. }
  89. var getTaskCheckExists = (command, options) => {
  90. options = options || {}
  91. return () => {
  92. var p = nodeShellExec.apply(null, ['where', [command]])
  93. if (options.ignorefailures) {
  94. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  95. return false;
  96. })
  97. }
  98. else return p.then(() => { return true });
  99. }
  100. }
  101. var getTaskWithElevation = function(tasdef){
  102. return ()=>{
  103. if (__isElevated) {
  104. return tasdef.elevatedpulltasks().then(()=>{
  105. // PB : TODO -- Every elevation should have its own messaging file. Async writes from multiple processes are a problem here...
  106. fs.writeFileSync('run.done', 'success')
  107. }).catch(e=>{
  108. fs.writeFileSync('run.done', 'failure')
  109. });
  110. }
  111. else {
  112. // PB : TODO -- Rename op['runas'] to 'elevate'
  113. var __runasresult = null;
  114. return op['runas']().then((r) => { return __runasresult = r; })
  115. .catch((e) => {
  116. console.error(e)
  117. })
  118. .finally(() => {
  119. if(__runasresult && !__runasresult.skipped) fs.unlinkSync('run.done')
  120. if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
  121. })
  122. }
  123. }
  124. }
  125. var getTaskWithoutElevation = function(tasdef){
  126. return ()=>{
  127. if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  128. else Promise.resolve(true)
  129. }
  130. }
  131. var gitops = {
  132. getdiscoverbranchcmd : function(repo){
  133. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  134. var cmd = [gitbash
  135. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  136. , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo + ' ' + parameters.join(' ') }]
  137. return cmd
  138. }
  139. }
  140. var getPullCmd = (repo, branch) => {
  141. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  142. // console.log(useGitPull)
  143. // var pullCmd = [gitInstallDir
  144. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  145. // , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo }]
  146. if(branch) {
  147. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  148. var pullCmd = [ gitbash
  149. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  150. , { cwd: instanceroot + '/' + repo, title : 'pull all origins for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  151. }
  152. else {
  153. // console.warn('No branch was specified detecting from working client.')
  154. // First check if working client exits.
  155. // if (existsSync(instanceroot + '/' + repo)) {
  156. var pullCmd = gitops.getdiscoverbranchcmd(repo)
  157. // }
  158. // else performpull
  159. }
  160. // var pullCmd = ['pullall', [], { cwd : repo }]
  161. if (useGitPull) pullCmd = ['git', ['pull'], {
  162. inherit: true, shell: true,
  163. cwd: instanceroot + '/' + repo
  164. // , env: process.env
  165. , runas: processedArgs.runas
  166. , title: `git pull ${repo}`
  167. }]
  168. return pullCmd
  169. }
  170. var performPull = (repo, branch) => {
  171. // PB : TODO -- Handle no branch passed in case.
  172. // if(!branch) { throw 'No branch specified' }
  173. if (existsSync(instanceroot + '/' + repo)) {
  174. var branchprint = branch ? ' branch :' + branch : '';
  175. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  176. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  177. if (__isElevated) {
  178. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  179. }
  180. else statuslog.statuslog(null, repo)
  181. return true;
  182. })
  183. .catch((e) => {
  184. e.repo = repo;
  185. if (__isElevated) {
  186. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  187. }
  188. else statuslog.statuslog(e); console.error(e)
  189. })
  190. }
  191. else {
  192. console.log('cloning ' + repo)
  193. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  194. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'],
  195. {
  196. inherit: true, shell: true,
  197. env: process.env
  198. , cwd : instanceroot
  199. , runas: processedArgs.runas
  200. }).catch((e) => {
  201. throw e;
  202. }).then(() => {
  203. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  204. {
  205. inherit: true, shell: true,
  206. env: process.env
  207. , cwd: instanceroot + '/' + repo
  208. , runas: processedArgs.runas
  209. , title: `git core.symlinks --replace-all true for ${selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'}`
  210. })
  211. .then(() => {
  212. if (__isElevated) {
  213. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  214. }
  215. else statuslog.statuslog(null, repo)
  216. })
  217. .catch((e) => {
  218. e.repo = repo;
  219. if (__isElevated) {
  220. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  221. }
  222. else statuslog.statuslog(e);
  223. })
  224. })
  225. .catch(e => {
  226. e.repo = repo;
  227. if (__isElevated) {
  228. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  229. }
  230. else statuslog.statuslog(e);
  231. })
  232. }
  233. }
  234. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  235. // -- Currently workaround is to always run from a non-elevated shell.
  236. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  237. var acquireElevationState = () => {
  238. if (__isElevated === null) {
  239. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  240. inherit: true
  241. // , shell: true
  242. , stdio: 'ignore'
  243. , env: process.env
  244. , title: `check privileged execution mode using "fsutil dirty query C:"`
  245. }).then((exitcode) => {
  246. console.log('Elevated')
  247. __isElevated = true;
  248. return true;
  249. }).catch(() => {
  250. __isElevated = false;
  251. console.log('Not Elevated');
  252. return false;
  253. });
  254. }
  255. else return Promise.resolve(__isElevated);
  256. }
  257. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current gittea username
  258. var defaultRepoOwner = 'chess';
  259. var elevatedRunasRepos = null
  260. var gitRepos = null
  261. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  262. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  263. var dbForLabel = function (label) {
  264. var dbsForLabel = {
  265. devmysql: 'mysql'
  266. , development: 'mssql'
  267. , production: 'mssql'
  268. }
  269. return dbsForLabel[label] || 'mysql'
  270. }
  271. // SAM : TODO Use nodeshellexec where to detect git installation dir
  272. var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe"
  273. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  274. // Relevant git repos
  275. var exludeMergeRepos = [];
  276. var useGitPull = processedArgs.useGitPull || false;
  277. var configPromise = null
  278. // elxr cli operations
  279. var op = {
  280. 'h': () => { console.log(elxr.help()); return '-h' }
  281. , 'clean' : () => {
  282. // delete all node_module folders and links.
  283. var tasklist = [];
  284. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot )
  285. return Promise.all(tasklist)
  286. }
  287. , 'undefined': () => { return op.h(); }
  288. , 'reset': () => {
  289. // Reset NPM packages semver so major versions can be updated.
  290. const fs = require('fs')
  291. const wipeDependencies = (__package) => {
  292. const file = fs.readFileSync(__package + '/package.json')
  293. const content = JSON.parse(file)
  294. for (var devDep in content.devDependencies) {
  295. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  296. content.devDependencies[devDep] = '*';
  297. }
  298. }
  299. for (var dep in content.dependencies) {
  300. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  301. content.dependencies[dep] = '*';
  302. }
  303. }
  304. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  305. }
  306. var repos = ['client'];
  307. // repos = gitRepos;
  308. repos.forEach(wipeDependencies)
  309. // if (require.main === module) {
  310. // } else {
  311. // module.exports = wipeDependencies
  312. // }
  313. }
  314. , 'upgrade': () => {
  315. console.log('upgrade.......')
  316. var tasks = [
  317. () => {
  318. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  319. inherit: true, shell: true
  320. , env: process.env
  321. }).catch((e) => { console.error(e) })
  322. p.position = 1;
  323. console.log('One')
  324. return p;
  325. }
  326. , () => {
  327. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  328. inherit: true, shell: true
  329. , env: process.env
  330. }).catch((e) => { console.error(e) })
  331. p.position = 2;
  332. console.log('Two')
  333. return p;
  334. }
  335. , () => {
  336. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  337. inherit: true, shell: true
  338. , env: process.env
  339. }).catch((e) => { console.error(e) })
  340. p.position = 3;
  341. console.log('Three')
  342. return p;
  343. }
  344. , () => {
  345. var p = nodeShellExec('n', ['latest'], {
  346. inherit: true, shell: true
  347. , env: process.env
  348. }).catch((e) => { console.error(e) })
  349. p.position = 4;
  350. console.log('Four')
  351. return p;
  352. }
  353. ]
  354. any(tasks)
  355. console.log('.......done')
  356. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  357. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  358. console.info('Uninstalling existing ember globally');
  359. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  360. stdio: ['pipe', process.stdout, process.stderr],
  361. inherit: true,
  362. shell: true,
  363. cwd: path.dirname(__dirname),
  364. env: env
  365. })
  366. step1.on('close', () => {
  367. console.info('Installing ember globally');
  368. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  369. stdio: ['pipe', process.stdout, process.stderr],
  370. inherit: true,
  371. shell: true,
  372. cwd: path.dirname(__dirname),
  373. env: env
  374. })
  375. step2.on('close', () => {
  376. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  377. stdio: ['pipe', process.stdout, process.stderr],
  378. inherit: true,
  379. shell: true,
  380. cwd: path.dirname(__dirname),
  381. env: env
  382. })
  383. })
  384. })
  385. }
  386. , 'runas': () => {
  387. if(processedArgs.skipelevated) return Promise.resolve({ skipped : true });
  388. console.log('Testing Elevation')
  389. if (__isElevated) {
  390. try {
  391. op[processedArgs.label || processedArgs._[0] || 'h']()
  392. }
  393. catch (e) {
  394. console.error('Error Invalid command : ' + e)
  395. fs.writeFileSync('run.done', 'error')
  396. }
  397. finally {
  398. }
  399. }
  400. else {
  401. console.log('Requesting Elevated Privileges');
  402. // Wait for the runas to complete before we read it.
  403. try {
  404. fs.unlinkSync('run.done')
  405. fs.unlinkSync('run.log')
  406. }
  407. catch (e) { } //Ignore
  408. // Find node path to send to hta.
  409. return nodeShellExec('where', ['node']).then(r => {
  410. var namedArgs = [];
  411. console.log('result : ' + JSON.stringify(r))
  412. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; })
  413. // PB : TODO -- Convert all the cli args back to string.
  414. var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  415. args.push('--nodepath=' + r[r.length - 1])
  416. if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
  417. if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
  418. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  419. , {
  420. inherit: true
  421. , shell: true
  422. , env: ENV
  423. , runas: 'self'
  424. , title: `runas`
  425. }
  426. ).then(() => {
  427. // runas returned.
  428. try {
  429. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  430. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  431. runaslog.forEach((logEntry) => {
  432. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry)
  433. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  434. })
  435. }
  436. catch (e) {
  437. // We must have a runas log
  438. statuslog.statuslog(e)
  439. console.error('Run log error probably was not created by runas : ' + e)
  440. }
  441. })
  442. .catch(err => console.error('Elevation failed : ' + err));
  443. })
  444. }
  445. }
  446. , 'push': () => {
  447. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  448. // init remote bare from local
  449. // pushandinitremotebare
  450. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  451. // connect to repo server -- net use 172.16.0.27
  452. // cd 172.16.0.27/repos/
  453. // mkdir repo.git
  454. // cd repo.git
  455. // git init --bare
  456. // cd localrepo
  457. // git remote rename origin githubclone
  458. // git remote add origin //172.16.0.27/repos/repo.git
  459. // git push origin master
  460. var repo = processedArgs._[1];
  461. var sequentialTaskShellCommands = [];
  462. if (!existsSync(`Z:/${repo}.git`)) {
  463. sequentialTaskShellCommands = [
  464. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  465. // inherit : true, shell: true
  466. // , env: process.env
  467. // }]
  468. ['pwd', { cwd: 'Z:', inherit: true }]
  469. , ['mkdir', [`${repo}.git`], {
  470. cwd: `Z:`
  471. , inherit: true, shell: true
  472. , env: process.env
  473. }]
  474. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  475. , ['git', ['init', '--bare'], {
  476. cwd: `Z:/${repo}.git`
  477. , inherit: true, shell: true
  478. , env: process.env
  479. }]
  480. // PB : TODO -- Do this conditionally only...
  481. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  482. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  483. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  484. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  485. // PB : TODO -- If threre is a gitbubclone origin
  486. // Set the master to pull from the local repo.
  487. ]
  488. if (!existsSync(`Z:`)) {
  489. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  490. inherit: true, shell: true
  491. , env: process.env
  492. }])
  493. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  494. // throw 'done'
  495. }
  496. }
  497. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }])
  498. // console.dir(sequentialTaskShellCommands);
  499. var tasks = [];
  500. sequentialTaskShellCommands.forEach(shellcmd => {
  501. // console.log(shellcmd)
  502. tasks.push(() => {
  503. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
  504. return p;
  505. })
  506. })
  507. any(tasks);
  508. }
  509. , 'is-git-repo': (dir) => {
  510. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  511. }
  512. // git remote equivalents...
  513. // git branch --set-upstream-to=elixir-unc/master master
  514. // git push --set-upstream elixir-unc branch..
  515. , 'remote': (args) => {
  516. // Subcommands!
  517. if(!processedArgs.v) return false; // Only -v is supported presently..
  518. var serial_perform = (repo) => {
  519. var options = { cwd: instanceroot + '/' + repo }
  520. return [
  521. ['git', ['remote', '-v'], options]
  522. ]
  523. }
  524. var x = (args) => {
  525. var tasq = () => {
  526. // console.log(args)
  527. return nodeShellExec.apply(null, args).catch(e => {
  528. // We continue on failure.
  529. console.error(tasq.toString())
  530. })
  531. }
  532. tasq.toString = function(){
  533. return JSON.stringify(args)
  534. }
  535. return tasq;
  536. }
  537. var perform = (dir) => {
  538. return any(serial_perform(dir.name).map(x))
  539. }
  540. dirs(perform)
  541. }
  542. , 'remote set-url': (args) => {
  543. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  544. var __args = {
  545. remotename : args.remotename || processedArgs._[2]
  546. , url : args.url || processedArgs._[3]
  547. }
  548. // pushable doesn't mean the remote doesn't support being pushed to.
  549. // 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.
  550. // PB : TODO -- change this to enablepushing.
  551. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  552. var pushable = processedArgs.pushable || false;
  553. remotename = __args.remotename
  554. url = __args.url
  555. var serial_perform_git_seturl = (repo) => {
  556. var options = { cwd: instanceroot + '/' + repo }
  557. // console.log(repo)
  558. if (pushable) {
  559. return [
  560. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  561. , ['git', ['remote', `set-url`, '--push', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  562. ]
  563. }
  564. else {
  565. return [
  566. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  567. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  568. ]
  569. }
  570. }
  571. var x = (args) => {
  572. var tasq = () => {
  573. // console.log(args)
  574. return nodeShellExec.apply(null, args).catch(e => {
  575. // We continue on failure.
  576. console.error(tasq.toString())
  577. })
  578. }
  579. tasq.toString = function(){
  580. return JSON.stringify(args)
  581. }
  582. return tasq;
  583. }
  584. var perform_git_seturl = (dir) => {
  585. op['is-git-repo'](dir).then((logEntry) => {
  586. return any(serial_perform_git_seturl(dir.name).map(x))
  587. }).catch((e) => {
  588. // console.log('Failed : ' + dir.name)
  589. })
  590. }
  591. dirs(perform_git_seturl)
  592. }
  593. , 'reset' : ()=>{
  594. // Reset the whole installation pertaining to this elxr folder.
  595. }
  596. , 'remote add': (args) => {
  597. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  598. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  599. // That explicitly has a remote name prefix.
  600. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  601. // git branch branch_name -u your_new_remote/branch_name -- older versions
  602. // git branch -vv -- Detect which branch are we tracking.
  603. // default upstream should be users own fork.
  604. // Also need alias branches to
  605. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  606. // probably git merge from all remotes... and relevant branches...
  607. // alias pushall='for i in `git remote`; do git push $i; done;'
  608. // alias pullall='for i in `git remote`; do git pull $i; done;'
  609. // args === processedArgs ? args = {} : null;
  610. var __args = {
  611. remotename : args.remotename|| processedArgs._[2]
  612. , url : args.url || processedArgs._[3]
  613. , branch : args.branch || processedArgs._[4]
  614. }
  615. var remotename = __args.remotename
  616. var url = __args.url
  617. var branch = __args.branch
  618. var pushable = processedArgs.pushable || false;
  619. var serial_perform_git_add = (repo) => {
  620. var options = { cwd: instanceroot + '/' + repo }
  621. // console.log(repo)
  622. if (pushable) {
  623. return [
  624. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  625. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  626. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  627. ]
  628. }
  629. else {
  630. return [
  631. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  632. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  633. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  634. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  635. ]
  636. }
  637. }
  638. var x = (args) => {
  639. return () => {
  640. // console.log(args)
  641. return nodeShellExec.apply(null, args)
  642. }
  643. // return Promise.resolve(true)
  644. }
  645. var perform_git_add = (dir) => {
  646. op['is-git-repo'](dir).then((logEntry) => {
  647. // console.log(code)
  648. if (logEntry.success) {
  649. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  650. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  651. })
  652. .catch((e) => {
  653. any(serial_perform_git_add(dir.name).map(x))
  654. })
  655. }
  656. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  657. }).catch((e) => {
  658. console.log('Failed : ' + dir.name)
  659. })
  660. }
  661. const { readdir } = require("fs").promises
  662. dirs(perform_git_add)
  663. }
  664. , 'remote remove': (args) => {
  665. var __args = {
  666. remotename : args.remotename|| processedArgs._[2]
  667. }
  668. var remotename = __args.remotename
  669. var serial_perform_git_remove = (repo) => {
  670. var options = { cwd: instanceroot + '/' + repo }
  671. // console.log(repo)
  672. return [
  673. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  674. ]
  675. }
  676. var x = (args) => {
  677. return () => {
  678. // console.log(args)
  679. return nodeShellExec.apply(null, args)
  680. }
  681. // return Promise.resolve(true)
  682. }
  683. var perform_git_remove = (dir) => {
  684. op['is-git-repo'](dir).then((logEntry) => {
  685. // console.log(code)
  686. if (logEntry.success) {
  687. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  688. any(serial_perform_git_remove(dir.name).map(x))
  689. })
  690. .catch((e) => {
  691. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`)
  692. })
  693. }
  694. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  695. }).catch((e) => {
  696. // console.log('Failed : ' + dir.name)
  697. })
  698. }
  699. const { readdir } = require("fs").promises
  700. dirs(perform_git_remove)
  701. }
  702. , 'init-gitea': (user) => {
  703. user = user || processedArgs._[1]
  704. if (!user) throw 'User name required'
  705. var serial_perform_init_gitea = (repo) => {
  706. var options = { cwd: instanceroot + '/' + repo }
  707. // console.log(repo)
  708. return [
  709. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  710. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  711. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  712. ]
  713. }
  714. var x = (args) => {
  715. return () => {
  716. // console.log(args)
  717. return nodeShellExec.apply(null, args)
  718. }
  719. // return Promise.resolve(true)
  720. }
  721. var perform_init_gitea = (dir) => {
  722. op['is-git-repo'](dir).then((logEntry) => {
  723. // console.log(code)
  724. if (logEntry.success) {
  725. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  726. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  727. })
  728. .catch((e) => {
  729. any(serial_perform_init_gitea(dir.name).map(x))
  730. })
  731. }
  732. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  733. }).catch((e) => {
  734. // console.log('Failed : ' + dir.name)
  735. })
  736. }
  737. const { readdir } = require("fs").promises
  738. dirs(perform_init_gitea)
  739. }
  740. , 'syncmaster': (label) => {
  741. // Usage :
  742. // elxr pull -- Defaults to run config
  743. var env = Object.assign({}, process.env); // Shallow clone it.
  744. // console.dir(env)
  745. console.log('Running exlr pull : ' + path.dirname(__dirname))
  746. if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'))
  747. if (__isElevated) {
  748. return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
  749. fs.writeFileSync('run.done', 'success')
  750. }).catch(() => {
  751. fs.writeFileSync('run.done', 'error')
  752. })
  753. }
  754. else return op['runas']()
  755. }
  756. , 'repo-relocate' : function(args){
  757. // relocate a subfolder in source repo to same subfolder in target repo with history.
  758. var args = args || {
  759. remotebase : processedArgs._[4] || 'http://git.bbh/chess/'
  760. , folder : processedArgs._[3] || 'server'
  761. , sourcerepo : processedArgs._[2] || 'client'
  762. , targetrepo : processedArgs._[1] || 'elixir-server'
  763. }
  764. var sourcerepooptions = { cwd: `${instanceroot}/relocate/${args.sourcerepo}`
  765. // , stdio: ['pipe', process.stdout, process.stderr]
  766. , inherit: true,
  767. shell: true,
  768. env: process.env
  769. , runas: processedArgs.runas
  770. }
  771. return op['repo-split'](args).then(()=>{
  772. return op['repo-merge'](args).then(()=>{
  773. // cleanup folder from source.
  774. var cmdseq = [
  775. ['rm', ['-rf', `${args.folder}`], sourcerepooptions ]
  776. // commits have to intentional...
  777. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  778. ]
  779. return any(cmdseq.map(callsheltask))
  780. })
  781. }).catch(e=>{console.error(e)})
  782. }
  783. , 'repo-split' : function(args) {
  784. // https://gist.github.com/smdabdoub/17065c348289158277b5
  785. /**
  786. * Eg : folder, remotebase, sourcerepo, targetrepo
  787. * args.folder = 'server'
  788. * args.remotebase = 'https://git.bbh/chess/'
  789. * args.sourcerepo = 'client'
  790. * args.targetrepo = 'elixir-server'
  791. */
  792. var args = args || {
  793. folder : 'server'
  794. , remotebase : 'http://git.bbh/chess/'
  795. , sourcerepo : 'client'
  796. , targetrepo : 'elixir-server'
  797. }
  798. var options = { cwd: `${instanceroot}/relocate`
  799. // , stdio: ['pipe', process.stdout, process.stderr]
  800. , inherit: true,
  801. shell: true,
  802. env: process.env
  803. , runas: processedArgs.runas
  804. }
  805. var cmdseq = [
  806. // create a temporary working dir in current folder where we started execution.
  807. ['mkdir', [ '-p', 'relocate']]
  808. , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  809. , ['git', ['clone', `${args.sourcerepo}`, `relocate-${args.sourcerepo}-${args.folder}`], options]
  810. , ['git', ['clone', `${args.remotebase}${args.targetrepo}`, `relocate-${args.targetrepo}-${args.folder}`], options]
  811. ]
  812. return any(cmdseq.map(callsheltask)).then(() => {
  813. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  814. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  815. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  816. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  817. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  818. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  819. // subtree split and filter-branch are options. We currently use repo-filter.
  820. return op['filter-repo'](args)
  821. }).catch(e=>{console.error(e); throw 'failed'})
  822. }
  823. , 'repo-merge' : function(args) {
  824. // Merge source repo into target repo
  825. var args = args || {
  826. folder : 'server'
  827. , remotebase : 'http://git.bbh/chess/'
  828. , sourcerepo : 'client'
  829. , targetrepo : 'elixir-server'
  830. }
  831. var sourcerepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  832. // , stdio: ['pipe', process.stdout, process.stderr]
  833. , inherit: true,
  834. shell: true,
  835. env: process.env
  836. , runas: processedArgs.runas
  837. }
  838. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.targetrepo}-${args.folder}`
  839. // , stdio: ['pipe', process.stdout, process.stderr]
  840. , inherit: true,
  841. shell: true,
  842. env: process.env
  843. , runas: processedArgs.runas
  844. }
  845. var cmdseq = [
  846. ['git', ['pull', `../relocate-${args.sourcerepo}-${args.folder}`, `master`, '--allow-unrelated-histories']
  847. , targetrepooptions ]
  848. // , ['git', ['push', targetrepooptions ] // manual push for now..
  849. ]
  850. return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e)})
  851. }
  852. , 'filter-repo' : function(args){
  853. // Merge source repo into target repo
  854. var args = args || {
  855. folder : 'server'
  856. , remotebase : 'http://git.bbh/chess/'
  857. , targetrepo : 'elixir-server'
  858. }
  859. var targetrepooptions = { cwd: `${instanceroot}/relocate/relocate-${args.sourcerepo}-${args.folder}`
  860. , inherit: true, shell: true
  861. , env: process.env
  862. , runas: processedArgs.runas
  863. }
  864. var cmdseq = [
  865. // git checkout -b feature/merge-old-project
  866. // git remote add src-project ../src-project
  867. ['git', ['filter-repo', '--path', `${args.folder}`], targetrepooptions ]
  868. ]
  869. return any(cmdseq.map(callsheltask)).catch(e=>{console.error(e); throw 'failed' })
  870. }
  871. , 'filter-branch' : function(preservefolder, repo){
  872. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  873. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  874. // Preserve a specific folder.
  875. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  876. /*
  877. git clone repo reposplit
  878. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  879. git remote rm origin
  880. */
  881. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  882. }
  883. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  884. // // Merge repo2 into a subfolder in repo1
  885. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  886. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  887. // /*
  888. // cd repo1
  889. // git remote add -f tempmergesource ../{{mergesource}}/.git
  890. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  891. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  892. // git commit
  893. // // Repair History
  894. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  895. // #!/usr/bin/env bash
  896. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  897. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  898. // subdir=server
  899. // git filter-branch --tree-filter '
  900. // first='"$first"'
  901. // last='"$last"'
  902. // subdir='"$subdir"'
  903. // log_file=/tmp/filter.log
  904. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  905. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  906. // echo "=== $GIT_COMMIT: making changes"
  907. // files=$(git ls-tree --name-only $GIT_COMMIT)
  908. // mkdir -p $subdir
  909. // for i in $files; do
  910. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  911. // done
  912. // else
  913. // echo "=== $GIT_COMMIT: ignoring"
  914. // fi \
  915. // >> $log_file
  916. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  917. // status=0 # tell tree-filter never to fail
  918. // '
  919. // git remote rm tempmergesource
  920. // */
  921. // // better alternative for history
  922. // /**
  923. // *
  924. // git clone git@server.com:old-project.git
  925. // git clone git@server.com:new-project.git
  926. // cd old-project
  927. // mkdir old-project
  928. // git mv !(old-project) old-project
  929. // ls -la and gt mv hidden files ....
  930. // git commit -a -S -m “Moving old project into its own subdirectory”
  931. // cd ../new-project
  932. // git remote add old-project ../old-project
  933. // git fetch old-project
  934. // git checkout -b feature/merge-old-project
  935. // git merge -S --allow-unrelated-histories old-project/master
  936. // git push origin feature/merge-old-project
  937. // git remote rm old-project
  938. // */
  939. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  940. // }
  941. , 'pull' : (label) => {
  942. // Usage :
  943. // elxr pull -- Defaults to run config
  944. return elxr.getpulltask(selectedinstance)()
  945. }
  946. , 'isInstalled': () => {
  947. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  948. console.log(processedArgs._[1] + ' exists.')
  949. return true;
  950. });
  951. }
  952. , 'i' : () => {
  953. var tasks = []
  954. // tasks.push(op['pull']);
  955. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
  956. tasks.push(op['use'])
  957. if (!__isElevated) {
  958. tasks.push(op['npmi'])
  959. }
  960. // var tasksdefs = [
  961. // ['elxr', ['pull']]
  962. // , ['elxr', ['use', 'elixir']]
  963. // , ['elxr', ['npmi']]
  964. // ]
  965. // tasksdefs.forEach(tasksdef=>{
  966. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  967. // })
  968. return any(tasks);
  969. }
  970. , 'npmi': () => {
  971. var tasks = [];
  972. // Build fails without babel...
  973. tasks.push(getShellTask(
  974. 'npm',[ 'i', '-g', 'babel-cli' ]
  975. ) )
  976. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  977. npmbuildrepos = []
  978. npmbuildrepos.forEach(repo => {
  979. tasks.push(() => {
  980. return nodeShellExec('npm', ['i --force'], {
  981. inherit: true, shell: true
  982. , cwd: instanceroot + '/' + repo
  983. , env: process.env
  984. , title: `npm i for ${repo}`
  985. }).catch((e) => {
  986. console.error('Ignoring Benign Error'); console.error(e);
  987. }).then(() => {
  988. console.log(`--npm run build for ${repo}--------------------`)
  989. return nodeShellExec('npm', ['run build'], {
  990. inherit: true, shell: true
  991. , cwd: instanceroot + '/' + repo
  992. , env: process.env
  993. , title: `npm run build for ${repo}`
  994. }).then(Tasq.then).catch(Tasq.catch)
  995. })
  996. })
  997. })
  998. any(tasks).then(() => {
  999. gitRepos.push('client/server');
  1000. gitRepos = gitRepos.concat(elevatedRunasRepos);
  1001. // gitRepos = [
  1002. // // 'bbhverse', 'serververse', 'elixir-server',
  1003. // // 'clientverse',
  1004. // 'client'
  1005. // ];
  1006. var rmtasks = []
  1007. var repotasks = []
  1008. var env = Object.assign({}, process.env)
  1009. delete env.NODE_ENV
  1010. gitRepos.forEach(repodef => {
  1011. rmtasks.push(
  1012. // () => {
  1013. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1014. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  1015. nodeShellExec('rm', ['package-lock.json'], {
  1016. inherit: true, shell: true
  1017. , cwd: instanceroot + '/' + repodef.repo
  1018. , env: process.env
  1019. , title: `rm 'package-lock.json' for ${repodef.repo}`
  1020. })
  1021. .then(()=>{
  1022. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  1023. }).catch((e) => { console.error(e) })
  1024. // }
  1025. )
  1026. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  1027. repotasks.push(
  1028. () => {
  1029. console.log(`--npm i for ${repodef.repo}--------------------`)
  1030. var p = nodeShellExec('npm', ['i', '--force'], {
  1031. inherit: true, shell: true
  1032. , cwd: instanceroot + '/' + repodef.repo
  1033. , env
  1034. , title: `npm i for ${repodef.repo}`
  1035. }).then(Tasq.then).catch(Tasq.catch)
  1036. return p;
  1037. })
  1038. }
  1039. })
  1040. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  1041. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  1042. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  1043. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  1044. // Second time try also doesnt work.
  1045. // repotasks.push(
  1046. // () => {
  1047. // var env = Object.assign({}, process.env)
  1048. // delete env.NODE_ENV
  1049. // console.log(`--------------------second time npm i for client--------------------`)
  1050. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  1051. // // return nodeShellExec('npm', ['i --force'], {
  1052. // inherit: true, shell: true
  1053. // , cwd: instanceroot + '/' + 'client'
  1054. // , env
  1055. // , title: `npm i for client`
  1056. // }).then(Tasq.then).catch(Tasq.catch)
  1057. // })
  1058. var bowerRepos = [{ repo : 'client'}]
  1059. bowerRepos.forEach(repodef => {
  1060. repotasks.push(() => {
  1061. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
  1062. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  1063. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  1064. inherit: true, shell: true
  1065. , cwd: instanceroot + '/' + repodef.repo
  1066. , env: process.env
  1067. , title: `bower i for ${repodef.repo}`
  1068. }).then(Tasq.then).catch(Tasq.catch)
  1069. return p;
  1070. })
  1071. })
  1072. // console.log('rmtasks.length : ' + rmtasks.length)
  1073. return Promise.all(rmtasks).then(() => any(repotasks));
  1074. }).catch(e => {
  1075. }).finally(statuslog.finally)
  1076. }
  1077. , 'start': (label) => {
  1078. console.log('Starting Elixir Server.');
  1079. var env = Object.assign({}, process.env); // Shallow clone it.
  1080. // console.dir(env)
  1081. env.NODE_ENV = process.env.NODE_ENV || 'development';
  1082. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  1083. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  1084. // cmd = 'node'
  1085. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
  1086. var childPromise = nodeShellExec(...cmd, {
  1087. // inherit : true,
  1088. shell: true,
  1089. detached: true,
  1090. stdio: 'ignore',
  1091. cwd: instanceroot + '/' + 'elixir-server'
  1092. , env: env
  1093. })
  1094. var child = childPromise.process;
  1095. if (typeof child.pid !== 'undefined') {
  1096. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1097. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  1098. encoding: 'utf8'
  1099. })
  1100. }
  1101. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  1102. // inherit : true,
  1103. // shell: true, detached: true,
  1104. // cwd : 'qms/server',
  1105. // env: env,
  1106. // shell : true
  1107. // })
  1108. // nodeShellExec('ember', ['s'], {
  1109. // // inherit : true,
  1110. // shell: true, detached: true,
  1111. // cwd : 'client/',
  1112. // env: env
  1113. // })
  1114. console.log('Starting Elixir Client Host.');
  1115. var cmd = ['ember', ['s']]
  1116. var childPromise = nodeShellExec(...cmd, {
  1117. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  1118. // PB : TODO -- ember debugging.
  1119. // inherit : true,
  1120. shell: true,
  1121. detached: true,
  1122. stdio: 'ignore',
  1123. cwd: instanceroot + '/' + 'client'
  1124. , env: env
  1125. })
  1126. // .catch(e=>console.error(e))
  1127. child = childPromise.process;
  1128. if (typeof child.pid !== 'undefined') {
  1129. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  1130. fs.writeFileSync('.client.server.pid', child.pid, {
  1131. encoding: 'utf8'
  1132. })
  1133. }
  1134. }
  1135. , 'stop': (label) => {
  1136. const kill = require('tree-kill');
  1137. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  1138. encoding: 'utf8'
  1139. })
  1140. fs.unlinkSync('.elixir-server.elixir.server.pid')
  1141. console.log(serverPid)
  1142. kill(serverPid)
  1143. serverPid = fs.readFileSync('.client.server.pid', {
  1144. encoding: 'utf8'
  1145. })
  1146. fs.unlinkSync('.client.server.pid')
  1147. console.log(serverPid)
  1148. kill(serverPid)
  1149. }
  1150. , 'model' : () => {
  1151. if (__isElevated) {
  1152. var tasks = [
  1153. () => {
  1154. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  1155. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  1156. inherit: true, shell: true
  1157. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  1158. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  1159. , env: process.env
  1160. }).catch((e) => { console.error(e) })
  1161. return p;
  1162. }
  1163. ];
  1164. return any(tasks).then(() => {
  1165. fs.writeFileSync('run.done', 'success')
  1166. }).catch(() => {
  1167. fs.writeFileSync('run.done', 'error')
  1168. })
  1169. }
  1170. else return op['runas']()
  1171. }
  1172. , 'use' : () => {
  1173. // use a certain named instance.
  1174. // Eg :
  1175. // 1) elxr use elixir
  1176. // 2) elxr use cihsr
  1177. // If environment is not specified defaults to development.
  1178. // 1) NODE=test elxr use elixir
  1179. /*// Steps
  1180. 1) Delete Config and Data symlinks
  1181. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  1182. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  1183. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1184. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  1185. */
  1186. var runconfig = { NODE_ENV: selectedinstance.node_env }
  1187. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  1188. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  1189. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  1190. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  1191. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  1192. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  1193. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  1194. return
  1195. }
  1196. var tasks = [
  1197. () => {
  1198. if (existsSync('config')) {
  1199. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  1200. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  1201. return p;
  1202. }
  1203. else return Promise.resolve(true);
  1204. },
  1205. () => {
  1206. if (existsSync('data')) {
  1207. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  1208. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  1209. return p;
  1210. }
  1211. else return Promise.resolve(true);
  1212. },
  1213. ];
  1214. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  1215. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  1216. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  1217. // console.log(process.env.cwd)
  1218. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  1219. // Maps an environment to a branch. Not required if the branch is appropriately named.
  1220. var checkoutMap = { 'development': 'master' }
  1221. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  1222. var performPullOrCloneForBranch = (def)=>{
  1223. var promise = Promise.resolve(true)
  1224. if (!branch) {
  1225. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1226. promise = nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{ branch = __branch})
  1227. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1228. }
  1229. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e )})
  1230. }
  1231. var performCloneAndCheckout = null;
  1232. // cant use git checkout -b it fails when branch already exists.
  1233. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1234. return performPullOrCloneForBranch(def).then(()=>{
  1235. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1236. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1237. // inherit : true, shell: true,
  1238. cwd: instanceroot + '/' + def.repo
  1239. // , stdio : ignore // Use when we want to silence output completely.
  1240. , runas: processedArgs.runas
  1241. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  1242. }).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 } })
  1243. })
  1244. }
  1245. // var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  1246. // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  1247. var elevatedqueue = [];
  1248. var enqueueOnce = (queue, task, def) => {
  1249. var found = queue.find(element => {
  1250. var keys = Object.keys( element )
  1251. for(var k=0; k < keys.length; k++) {
  1252. if(element[keys[k]] !== def[k]) return false;
  1253. }
  1254. })
  1255. queue.push(function(){ return task(this)}.bind(def));
  1256. }
  1257. var enqueue = (queue, task, def) => {
  1258. queue.push(function(){ return task(def)}.bind(def));
  1259. }
  1260. var mergeSources = {
  1261. 'development': null,
  1262. 'test': 'master',
  1263. 'production': 'master'
  1264. }
  1265. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1266. // Checkout is reduced to pull provided the current branch is the targetbranch
  1267. if(branch === mergesource) performCheckout = (def) => {
  1268. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1269. return nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{
  1270. if(branch === __branch) return performCloneAndCheckout(def)
  1271. return performPullOrCloneForBranch(def)
  1272. })
  1273. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1274. }
  1275. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  1276. var performPullAll = (def) => {
  1277. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1278. return nodeShellExec('git', ['pull', '--all'], {
  1279. // inherit : true, shell: true,
  1280. cwd: instanceroot + '/' + def.repo
  1281. , runas: processedArgs.runas
  1282. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  1283. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  1284. }
  1285. var excludeCheckouts = Object.assign(exludeMergeRepos)
  1286. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  1287. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  1288. var performMerge = (def) => {
  1289. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  1290. return nodeShellExec('git', ['merge', mergesource], {
  1291. inherit: true, shell: true,
  1292. cwd: instanceroot + '/' + def.repo
  1293. , runas: processedArgs.runas
  1294. }).catch((e) => { console.error(e) })
  1295. }
  1296. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
  1297. // var performRepoOperation = function(def) {
  1298. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  1299. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  1300. // }
  1301. return any(tasks).then(() => {
  1302. var pr = Promise.resolve(true)
  1303. if (!__isElevated) {
  1304. pr = op['runas']()
  1305. return pr.then(()=>{
  1306. //target is the env is we specify in elxr use command. Default is dev
  1307. //Switch to target branch
  1308. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  1309. // pull or clone target branch
  1310. .then(() => {
  1311. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1312. return any(gitRepos.map((repo) => performPullAll(repo)))
  1313. })
  1314. // switch to source branch
  1315. .then( () => {
  1316. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  1317. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  1318. })
  1319. //Pull on merge source branch
  1320. .then( () => {
  1321. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1322. return any(gitRepos.map((repo) => performPullAll(repo)))
  1323. })
  1324. //Switch to target branch
  1325. .then( () => {
  1326. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1327. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  1328. })
  1329. .then( //Merge source branch to target branch
  1330. () => {
  1331. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1332. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
  1333. })
  1334. })
  1335. }
  1336. else {
  1337. tasks = [
  1338. () => {
  1339. // Use junctions to avoid npm package issues
  1340. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  1341. inherit: true, shell: true
  1342. , cwd : instanceroot
  1343. , env: process.env
  1344. }).catch((e) => { console.error(e) })
  1345. return p;
  1346. }
  1347. ];
  1348. if (processedArgs._[1]) {
  1349. tasks = tasks.concat(
  1350. [
  1351. () => {
  1352. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  1353. inherit: true, shell: true
  1354. , cwd : instanceroot
  1355. , env: process.env
  1356. }).catch((e) => { console.error(e) })
  1357. return p;
  1358. }
  1359. ]
  1360. )
  1361. }
  1362. return any(tasks).then(()=>{
  1363. // checkout target branch
  1364. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1365. // pull or clone target branch
  1366. .then(() => {
  1367. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1368. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  1369. })
  1370. // switch to source branch
  1371. .then( () => {
  1372. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1373. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  1374. })
  1375. //Pull on merge source branch
  1376. .then( () => {
  1377. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1378. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  1379. })
  1380. //Switch to target branch
  1381. .then( () => {
  1382. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1383. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1384. })
  1385. .then( //Merge source branch to target branch
  1386. () => {
  1387. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1388. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
  1389. })
  1390. .then(() => {
  1391. fs.writeFileSync('run.done', 'success')
  1392. }).catch(() => {
  1393. fs.writeFileSync('run.done', 'error')
  1394. })
  1395. })
  1396. }
  1397. }).catch(() => {
  1398. fs.writeFileSync('run.done', 'error')
  1399. })
  1400. // Antibiotic stewardship program.
  1401. // 1st use is fine.
  1402. // Max vials dispense
  1403. // 2nd use Pharmacy needs justification Form.
  1404. // Approval after a certain period of time.
  1405. }
  1406. , 'g': () => {
  1407. if (processedArgs.h) {
  1408. console.log('elxr g [modelname] => generate a model named [modelname]');
  1409. console.log('elxr g => regenerate all known models');
  1410. return
  1411. }
  1412. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1413. // console.log('Starting directory: ' + process.cwd());
  1414. // try {
  1415. // child = child.on('close', () => { process.chdir(label) } );
  1416. // console.log('New directory: ' + process.cwd());
  1417. // }
  1418. // catch (err) {
  1419. // console.log('chdir: ' + err);
  1420. // }
  1421. // child.on('close', function(){
  1422. // var options = {
  1423. // shell : true
  1424. // , inherit : true
  1425. // // , cwd : '' + process.cwd
  1426. // // , env : process.env
  1427. // };
  1428. // nodeShellExec('git', ['init'], { inherit : true});
  1429. if (0) {
  1430. // PB : TODO -- Special google chrome profile for tests etc.
  1431. nodeShellExec('pwd', { inherit: true });
  1432. // /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"
  1433. // "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
  1434. // "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
  1435. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1436. "--profile-directory=Profile 1"
  1437. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1438. }
  1439. // nodeShellExec('npm', ['init', '-y'], options);
  1440. // nodeShellExec('npm', ['init', '-y'], options);
  1441. // })
  1442. var g = {
  1443. 'client': () => {
  1444. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  1445. console.info('Creating new ember client named : ' + processedArgs._[2]);
  1446. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1447. stdio: ['pipe', process.stdout, process.stderr],
  1448. inherit: true,
  1449. shell: true,
  1450. cwd: path.dirname(__dirname),
  1451. env: env
  1452. })
  1453. },
  1454. 'modelr': () => {
  1455. var tasks = [
  1456. () => {
  1457. var p = nodeShellExec('"ember"', [
  1458. 'g'
  1459. , 'modelr'
  1460. , processedArgs._[2]], {
  1461. inherit: true, shell: true, env: process.env
  1462. }).then(() => {
  1463. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  1464. return true;
  1465. }).catch((e) => { console.error(e) })
  1466. return p;
  1467. },
  1468. () => {
  1469. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1470. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  1471. chromeprefs = JSON.parse(chromeprefs)
  1472. var previous = chromeprefs.download.default_directory;
  1473. var parentDir = path.dirname(__dirname);
  1474. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1475. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1476. // PB : TODO -- detect where chrome is installed.
  1477. // PB : TODO -- set the download dir to the place where files are needed.
  1478. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1479. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1480. , '--profile-directory="chess"'
  1481. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1482. inherit: true, shell: true
  1483. , env: process.env
  1484. }).then(() => {
  1485. chromeprefs.download.default_directory = previous;
  1486. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1487. return true;
  1488. }).catch((e) => { console.error(e) })
  1489. return p;
  1490. }
  1491. ,
  1492. () => {
  1493. console.log('Browser process should have closed here....')
  1494. return true;
  1495. }
  1496. ]
  1497. any(tasks)
  1498. }
  1499. }
  1500. g[processedArgs._[1]]();
  1501. }
  1502. }
  1503. var util = require('util');
  1504. var cliname = 'elxr';
  1505. var ver = '1.1';
  1506. var readme = `
  1507. Command syntax examples
  1508. elxr
  1509. Displays help. Same as elxr h
  1510. elxr i
  1511. Runs interactive propmts to help choose installation options.
  1512. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  1513. General command syntax.
  1514. Eg: NODE_ENV=development elxr pull elixir
  1515. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  1516. The specific cmd defines what the value is interpreted as.
  1517. There are several cmds that do not require an {{instancename}} parameter.
  1518. Eg: elxr remote remove origin
  1519. Git operations or passthrough external commands on all repository folders in you working directory.
  1520. Main objectives.
  1521. elxr cli is a wrapper around other shell commands and api based operations.
  1522. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  1523. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  1524. `;
  1525. var help = `
  1526. ${readme}
  1527. # list of commands... please refer dveloper documentation for ${cliname}
  1528. ${
  1529. // util.inspect(
  1530. [Object.keys(op)]
  1531. // )
  1532. }
  1533. `;
  1534. var elxr = {
  1535. help() {
  1536. return chalk.cyanBright(`
  1537. -------------------------------------------------------------------------------
  1538. *** BBH Elixir ***
  1539. -------------------------------------------------------------------------------
  1540. elxr ${ver}
  1541. A cli tool for chess
  1542. ${help}
  1543. -------------------------------------------------------------------------------
  1544. `)
  1545. }
  1546. , info() {
  1547. return chalk.cyanBright(`
  1548. -------------------------------------------------------------------------------
  1549. *** BBH Elixir ***
  1550. -------------------------------------------------------------------------------
  1551. elxr ${ver}
  1552. A cli tool for chess
  1553. -------------------------------------------------------------------------------
  1554. `)
  1555. }
  1556. , getpulltask(def){
  1557. // def can be an instance config
  1558. // Or an object with many repos and elevated repos
  1559. // Or a single repo ( Either Elevated or normal. )
  1560. def = def || {
  1561. repos : selectedinstance.repos,
  1562. elevated : selectedinstance.elevated
  1563. }
  1564. var elevatedpulltasks = null;
  1565. if(def.repo) {
  1566. // Single repo case.
  1567. if(def.repo.requiresElevation) {
  1568. elevatedpulltasks = function() {
  1569. return performPull(def.repo).then(() => {
  1570. return true;
  1571. }).catch((e) => {
  1572. console.error(e)
  1573. })
  1574. }
  1575. return
  1576. }
  1577. else {
  1578. var regularpulltasks = function(){
  1579. var pendingpulls = [];
  1580. pendingpulls.push(performPull(def.repo))
  1581. return Promise.all(pendingpulls).finally(Traq.finally)
  1582. }
  1583. }
  1584. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1585. else return getTaskWithoutElevation({ regularpulltasks})
  1586. }
  1587. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  1588. console.dir(def)
  1589. var env = Object.assign({}, process.env); // Shallow clone it.
  1590. console.log('Running exlr pull : ' + path.dirname(__dirname))
  1591. var useGitPull = processedArgs.useGitPull || false;
  1592. if(def.elevated || def.repos) {
  1593. if(def.elevated) def.requiresElevation = true;
  1594. else delete def.requiresElevation;
  1595. }
  1596. else {
  1597. if(def.requiresElevation) def.elevated = [def]
  1598. else def.repos = [def]
  1599. }
  1600. var regularpulltasks = function(){ return Promise.resolve(true) }
  1601. if(def.elevated){
  1602. elevatedpulltasks = function() {
  1603. return any(def.elevated.map((def) => performPull(def.repo))).then(() => {
  1604. return true;
  1605. }).catch((e) => {
  1606. console.error(e)
  1607. })
  1608. }
  1609. }
  1610. if(def.repos) {
  1611. var regularpulltasks = function(){
  1612. var pendingpulls = [];
  1613. def.repos.forEach((def) => { pendingpulls.push(performPull(def.repo)) })
  1614. return Promise.all(pendingpulls).finally(Traq.finally)
  1615. }
  1616. }
  1617. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1618. else return getTaskWithoutElevation({ regularpulltasks})
  1619. }
  1620. }
  1621. function preworkerconfig(){
  1622. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  1623. gitRepos = selectedinstance.repos
  1624. // gitRepos = ['chess-server-lib'];
  1625. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  1626. elevatedRunasRepos = selectedinstance.elevated
  1627. // Repos that should excluded from merge for releases...
  1628. exludeMergeRepos = selectedinstance.exludeMergeRepos
  1629. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  1630. // mysql -u root -p db_name < drop_all_tables.sql
  1631. var mysql = '../xampp/mysql/bin/mysql'
  1632. var mysqldump = '../xampp/mysql/bin/mysqldump'
  1633. }
  1634. // The main elxr cli process
  1635. function elxrworker() {
  1636. var subcommandlabels = {
  1637. remote : (`remote ${processedArgs._[1] || ''}`).trim()
  1638. }
  1639. var __runcmd = function (label) {
  1640. var distinquishedlabel = subcommandlabels[label] || label
  1641. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  1642. }
  1643. // --runas
  1644. if (processedArgs.runas) {
  1645. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  1646. return __runcmd('runas')
  1647. }
  1648. else return __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  1649. }
  1650. function acquireChoices(selectedinstance) {
  1651. var hasconfig = false;
  1652. console.warn(chalk.yellow(`
  1653. -------------------------------------------------------------------------------
  1654. Warning : Cannot locate your preferred configuration since it was not specified
  1655. You should fork the default chess configuration to customize and make it
  1656. your own instance with a named config as
  1657. {{yourowninstancename}}-config-{{yourchosenenvironment}}
  1658. And then run this tool as follows
  1659. NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  1660. OR
  1661. Run this tool with the following command to use a quick start default.
  1662. elxr --default
  1663. OR
  1664. Choose one of the options below to run interactively.
  1665. We will run your choice at the next prompt.
  1666. -------------------------------------------------------------------------------
  1667. `))
  1668. var prompt = cli.prompter;
  1669. return prompt.ask(`Choose an option :
  1670. d) Install the default chess instance.
  1671. => elxr i chess node_env=development --default
  1672. n) Create your custom new instance interactively
  1673. => elxr i {{instanceName}} node_env={{environment}}
  1674. i) Choose an instance and environment to install
  1675. => elxr i {{instanceName}} node_env={{environment}}
  1676. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  1677. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  1678. h) Help
  1679. q) Quit
  1680. Default <= d
  1681. : `).then((choice) => {
  1682. if (choice && choice === 'd' || !choice) {
  1683. processedArgs._[0] = 'i'
  1684. selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  1685. selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  1686. selectedinstance.reposerver = 'https://git.bbh.org.in'
  1687. }
  1688. else if (choice === 'h') {
  1689. processedArgs._[0] = 'h'
  1690. fs.writeFileSync('run.done', 'noop help');
  1691. console.log(elxr.help()); process.exit()
  1692. }
  1693. else if (choice === 'n' || choice === 'i') {
  1694. var p1 = cli.prompter;
  1695. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1696. processedArgs._[0] = 'i'
  1697. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  1698. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1699. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1700. if (choice === 'n') {
  1701. selectedinstance.reposerver = 'https://git.bbh.org.in'
  1702. console.warn(
  1703. chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  1704. process.exit();
  1705. }
  1706. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1707. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1708. })
  1709. })
  1710. })
  1711. } else if (choice === 'c') {
  1712. var p1 = cli.prompter;
  1713. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1714. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  1715. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1716. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1717. return p1.ask(`Enter cmd :
  1718. p) pull
  1719. Default <= p
  1720. : `).then(function (cmd) {
  1721. if (!cmd || cmd === 'p') {
  1722. processedArgs._[0] = 'pull'
  1723. }
  1724. else processedArgs._[0] = cmd
  1725. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1726. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1727. })
  1728. })
  1729. })
  1730. })
  1731. } else {
  1732. 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.`));
  1733. fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  1734. fs.writeFileSync('run.done', 'noop quit');
  1735. process.exit()
  1736. }
  1737. })
  1738. }
  1739. var mergeObjByKey = function(arrOfObjs, keyName) {
  1740. var keyedDistinct = {}
  1741. var distinctArrOfObjs = []
  1742. arrOfObjs.forEach( o => {
  1743. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o)
  1744. })
  1745. Object.keys(keyedDistinct).forEach(key => {
  1746. distinctArrOfObjs.push( utils.assign( ...keyedDistinct[key] ) ) // PB : TODO -- Shallow use utils.assign
  1747. })
  1748. return distinctArrOfObjs;
  1749. }
  1750. var cacheWriteInstanceConfig = function(chessinstances){
  1751. var instanceName = chessinstances['current_run'].instanceName;
  1752. var node_env = chessinstances['current_run'].node_env;
  1753. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos, 'repo') ;
  1754. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated, 'repo') ;
  1755. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  1756. }
  1757. var acquireConfig = function (selected) {
  1758. var configrepo = selected.instanceName + '-config-' + selected.node_env;
  1759. return performPull(configrepo).then(() => {
  1760. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  1761. selectedinstance = require(manifestpath)()
  1762. // Config from server always override merges into selection ecept for the current selection.
  1763. // PB : TODO -- utils.assign Array merges are non-distinct...
  1764. if(!selectedinstance.repos[0].repo) {
  1765. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  1766. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  1767. }
  1768. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  1769. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  1770. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  1771. }
  1772. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = utils.assign(selected, selectedinstance)
  1773. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  1774. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  1775. cacheWriteInstanceConfig(chessinstances)
  1776. ENV.NODE_ENV = selectedinstance.node_env;
  1777. })
  1778. .catch((e) => {
  1779. console.error(e)
  1780. console.error('Config acquisition failed.')
  1781. })
  1782. }
  1783. var launchpath = process.cwd().replace(/\\/, '/')
  1784. var thisscriptdir = __dirname
  1785. var instanceroot = launchpath;
  1786. var __default = {
  1787. // Default is public server only.
  1788. // All public repos are by default available.
  1789. reposervers: ['https://git.bbh.org.in']
  1790. , repos: [
  1791. { repo : 'setup' }
  1792. , { repo : 'elxr' }
  1793. , { repo : 'loopback-connector-mysql' }
  1794. , { repo : 'loopback-jsonapi-model-serializer' }
  1795. , { repo : 'loopback-component-jsonapi' }
  1796. , { repo : 'ember-service-worker' }
  1797. , { repo : 'ember-service-worker-asset-cache' }
  1798. , { repo : 'ember-service-worker-cache-fallback' }
  1799. , { repo : 'ember-service-worker-index' }
  1800. , { repo : 'ember-sw-client-route' }
  1801. ]
  1802. , elevated: []
  1803. , exludeMergeRepos: {}
  1804. , instanceName: 'chess'
  1805. // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
  1806. , node_env: 'development'
  1807. }
  1808. var detectInstance = function () {
  1809. console.log(`launchpath = ${launchpath}`)
  1810. console.log(`thisscriptdir = ${thisscriptdir}`)
  1811. var root = launchpath;
  1812. // We need a reference to the root director for elxr cli to be properly oriented.
  1813. if ((launchpath + path.normalize('/elxr')) === thisscriptdir) {
  1814. // We ran unbuilt from the proper root with elxr subfolder.
  1815. console.log(`Instance Path : ${root}`)
  1816. }
  1817. else {
  1818. if (launchpath === thisscriptdir) {
  1819. // Same directory doesn't mean we are being run from elxr directory or the root directory.
  1820. // It could be a standalone elxr build which may or maynot be in the proper location.
  1821. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  1822. // Unbuilt therefore we are in the elxr directory.
  1823. root = path.normalize(launchpath + '/..');
  1824. }
  1825. else {
  1826. // Built version.
  1827. // check if we have a elxr subfolder.
  1828. if (fs.existsSync(launchpath + '/..' + path.normalize('/elxr'))) {
  1829. // Probably in the right place.
  1830. root = path.normalize(launchpath + '/..');
  1831. }
  1832. else {
  1833. // Assume launchpath is meaningless.
  1834. // Figure it out from the input instance name and environment parameters if we are in the right location.
  1835. root = path.normalize(launchpath + '/' + processedArgs._[1] + '/' + processedArgs.node_env)
  1836. }
  1837. }
  1838. }
  1839. }
  1840. instanceroot = root.replace(/\\/g, '/');
  1841. __default.root = root;
  1842. clioverrides.root = clioverrides.root || root;
  1843. // Resolves undefined when No known instances detected.
  1844. return Promise.resolve(
  1845. // We can expect a .elxr at each level.
  1846. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../..' /* instanceNames */].earlyreduce( ( acc, p, i, a )=>{
  1847. var root = `${instanceroot}/${p}.elxr`;
  1848. if(existsSync( root )) {
  1849. try {
  1850. var chessinstances = acquirelocalinstances( { root } )
  1851. return Object.keys(chessinstances).earlyreduce( ( acc, instanceName) => {
  1852. return Object.keys(chessinstances[instanceName]).earlyreduce( (acc, instanceType) => {
  1853. if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize(root) ) return {
  1854. value : chessinstances[instanceName][instanceType]
  1855. , done : true
  1856. };s
  1857. })
  1858. })
  1859. }
  1860. catch(e){
  1861. return {}
  1862. }
  1863. }
  1864. else return {}
  1865. }).value
  1866. )
  1867. }
  1868. var __interactve_promts = {
  1869. get reposerver(){
  1870. return cli.prompt(this.reposervers, 'git default repo').then(reposerver => {
  1871. Object.defineProperty(this, 'reposerver', {
  1872. value: reposerver,
  1873. writable: false,
  1874. configurable : true,
  1875. enumerable : true
  1876. });
  1877. return reposerver
  1878. })
  1879. }
  1880. , set reposerver(reposerver){
  1881. Object.defineProperty(this, 'reposerver', {
  1882. value: reposerver,
  1883. writable: false,
  1884. configurable : true,
  1885. enumerable : true
  1886. });
  1887. return reposerver
  1888. }
  1889. }
  1890. var downloadsdir = '../Downloads';
  1891. var prerequisites = [
  1892. {
  1893. shellcmd: 'git',
  1894. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  1895. , installer: 'Git-2.31.0-64-bit.exe'
  1896. , installcmd: ['cmd', ['/c', 'start',
  1897. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  1898. , '/VERYSILENT'
  1899. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  1900. ]]
  1901. , preinstallsteps: function() {
  1902. var prompt = cli.prompter;
  1903. var steps = [
  1904. () => {
  1905. if (!existsSync(downloadsdir + '/' + this.installer)) {
  1906. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  1907. }
  1908. else return Promise.resolve(true)
  1909. }
  1910. ]
  1911. var prompts = [
  1912. () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
  1913. , () => prompt.ask(`git email : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
  1914. ]
  1915. return any([any(steps), any(prompts)])
  1916. }
  1917. , installsteps: function () {
  1918. return any([this.installcmd].map(callsheltask))
  1919. }
  1920. , postinstallsteps: function(){
  1921. var prompt = cli.prompter;
  1922. var gitUser = 'guest';
  1923. var gitEmail = 'guest@bbh.org.in';
  1924. var prompts = [];
  1925. prompts.push(
  1926. ()=>{
  1927. var choices = { 0 : 'guest', 1 : 'chessdemo' }
  1928. return cli.prompt(choices, 'git user name').then(gituser => gitUser = gituser)
  1929. }
  1930. )
  1931. prompts.push(
  1932. ()=>{
  1933. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  1934. return cli.prompt(choices, 'git user email').then(gitemail => gitEmail = gitemail)
  1935. }
  1936. )
  1937. return any(prompts).then(()=>{
  1938. var steps = [
  1939. ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  1940. , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  1941. ]
  1942. return any(steps.map(callsheltask)).then(() => {
  1943. })
  1944. });
  1945. }
  1946. , install: function () {
  1947. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  1948. }
  1949. , verifyAndInstall : function(){
  1950. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  1951. if(exists) {
  1952. // return any(['git', ['config', '--global', '-l']].map(callsheltask))
  1953. return this.getUser(null, this.postinstallsteps.bind(this))
  1954. }
  1955. return this.install();
  1956. });
  1957. }
  1958. , getUser : function(repo, onNoResult){
  1959. onNoResult = onNoResult || function(){return false}
  1960. var globalOrLocal = '--global';
  1961. if(!repo) globalOrLocal = '--global';
  1962. else globalOrLocal = '--local'
  1963. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(callsheltask)).then((result)=>{
  1964. // not yet configured.
  1965. if(!result.success) return onNoResult()
  1966. else {
  1967. var users = result.messages[0].trim().split('\n');
  1968. if(users.length === 0 ||
  1969. users.length === 1 && users[0] === 'guest') {
  1970. return onNoResult()
  1971. }
  1972. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  1973. }
  1974. })
  1975. .catch((e)=>{
  1976. console.log(e)
  1977. return onNoResult()
  1978. })
  1979. }
  1980. }
  1981. ,
  1982. {
  1983. shellcmd: 'node',
  1984. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  1985. , installer: 'node-v14.16.0-x64.msi'
  1986. , installcmd: ['MSIEXEC.exe', ['/i'
  1987. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  1988. , 'ACCEPT=YES', '/passive']]
  1989. , install : function() { return any([this.installcmd].map(callsheltask)).then(() => { }) }
  1990. }
  1991. ]
  1992. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  1993. function ensureDirectoryExistence(filePath) {
  1994. var dirname = path.dirname(filePath);
  1995. if (fs.existsSync(dirname)) {
  1996. return filePath;
  1997. }
  1998. ensureDirectoryExistence(dirname);
  1999. fs.mkdirSync(dirname);
  2000. return filePath;
  2001. }
  2002. var mainTasks = [];
  2003. function verifyAndInstallPrerequisites() {
  2004. fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
  2005. // PB : TODO include and build from files... using rollup..
  2006. var downloadbatch =
  2007. `::**************************************************************************
  2008. :Download_ <url> <File>
  2009. Powershell.exe ^
  2010. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  2011. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  2012. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  2013. exit /b
  2014. ::**************************************************************************`
  2015. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch)
  2016. var windowselevate =
  2017. `
  2018. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  2019. <script language="vbscript">
  2020. document.title = "elxr control panel"
  2021. self.ResizeTo 200,600
  2022. Sub Window_Onload
  2023. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  2024. End Sub
  2025. Set objShell = CreateObject("WScript.Shell")
  2026. Set objENV = objShell.Environment("Process")
  2027. dim NODE_ENV
  2028. NODE_ENV = objENV("NODE_ENV")
  2029. </script>
  2030. <script language="javascript">
  2031. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  2032. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  2033. // alert(windowselevate.commandLine)
  2034. var args = windowselevate.commandLine.split('"').slice(3);
  2035. // alert(args)
  2036. var processedArgs = { _ : [] }
  2037. var namedArgs = [];
  2038. for(var item in args){
  2039. if(args[item].charAt(0) === '-'){
  2040. namedArgs.push(args[item])
  2041. var split = args[item].split('=');
  2042. processedArgs[split[0].slice(2)] = split[1] || true;
  2043. }
  2044. else processedArgs._.push(args[item]);
  2045. }
  2046. // args = args.forEach(function(item){ })
  2047. // alert('processedArgs._ : ' + processedArgs._);
  2048. // alert(processedArgs.runas);
  2049. // PB : TODO -- Convert all the cli args back to string.
  2050. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  2051. // alert(cargs)
  2052. var shell = new ActiveXObject('shell.application');
  2053. // alert('launching node privilged. ' + processedArgs['nodepath'])
  2054. // shell.ShellExecute('where', 'node', '', '', 10);
  2055. shell.ShellExecute('node', cargs, '', 'runas', 1);
  2056. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  2057. var fso = new ActiveXObject('Scripting.FileSystemObject');
  2058. window.onload = function() {
  2059. document.body.style.backgroundColor = 'black';
  2060. document.body.style.fontFamily = 'arial';
  2061. var log = document.createElement('div');
  2062. log.innerHTML='Please Wait';
  2063. function l(msg){ log.innerHTML+= msg; };
  2064. log.style.color = 'blue';
  2065. log.style.width = '95%';
  2066. log.id = 'log';
  2067. document.body.appendChild(log);
  2068. l('<Br/>Current config : ')
  2069. l('<Br/>NODE_ENV = ' + NODE_ENV)
  2070. l('<Br/>cmd = ' + processedArgs._[0])
  2071. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  2072. l('<Br/><Br/>')
  2073. var timer = function(){
  2074. l('.');
  2075. if(fso.FileExists("run.done")) close();
  2076. else window.setTimeout(timer, 1000);
  2077. };
  2078. window.setTimeout(timer, 3000);
  2079. };
  2080. </script>
  2081. </html>
  2082. `
  2083. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate)
  2084. var downloadtasks = [];
  2085. var installtasks = [];
  2086. prerequisites.forEach(preq => {
  2087. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  2088. if (exists) console.log(`${preq.shellcmd} exists`)
  2089. else {
  2090. console.log(`${preq.shellcmd} is not installed`)
  2091. return preq.preinstallsteps.call(preq).then(() => {
  2092. installtasks.push(preq.install.bind(preq))
  2093. })
  2094. }
  2095. }))
  2096. })
  2097. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  2098. }
  2099. var getPromptableAsyncPropDescriptor = function(propName, choices, defaultchoise){
  2100. return {
  2101. get (){
  2102. return cli.prompt( choices, propName, defaultchoise).then(propValue => {
  2103. Object.defineProperty(this, propName, {
  2104. value: propValue,
  2105. writable: false,
  2106. configurable : true,
  2107. enumerable : true
  2108. });
  2109. return propValue
  2110. })
  2111. }
  2112. // , set (propValue){
  2113. // Object.defineProperty(this, propName, {
  2114. // value: propValue,
  2115. // writable: false,
  2116. // configurable : true,
  2117. // enumerable : true
  2118. // })
  2119. // return propValue;
  2120. // }
  2121. , configurable : true
  2122. , enumerable : true
  2123. }
  2124. }
  2125. function acquirelocalinstances(selected){
  2126. var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
  2127. return chessinstances
  2128. }
  2129. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  2130. var selectedinstance = null;
  2131. var chessinstances = { current_run : {} };
  2132. acquireElevationState().then(() => {
  2133. var skipprerequisites = false;
  2134. function initinstances(selected) {
  2135. // PB : TODO -- processedArgs should already be part of selected.
  2136. var instanceName = processedArgs._[1] = processedArgs._[1] || chessinstances.current_run.instanceName || selected.instanceName;
  2137. var node_env = processedArgs.node_env = processedArgs.node_env || chessinstances.current_run.node_env || selected.node_env;
  2138. chessinstances[instanceName] = chessinstances[instanceName] || {}
  2139. chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || selected;
  2140. chessinstances['current_run'] = chessinstances[instanceName][selected.node_env] ?
  2141. { instanceName: instanceName, node_env: node_env } : (chessinstances['current_run'] || { instanceName: instanceName, node_env: node_env })
  2142. // chessinstances[chessinstances.current_run.instanceName] = chessinstances[chessinstances.current_run.instanceName] || {}
  2143. if(path.normalize(selected.root) !== path.normalize(chessinstances[instanceName][node_env].root)) {
  2144. throw "Mismatched chessinstances config found " + chessinstances[instanceName][node_env].root + ' does not match ' + selected.root
  2145. }
  2146. // Override sequence.
  2147. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  2148. selectedinstance = Object.assign(
  2149. selected
  2150. , chessinstances[instanceName][node_env]
  2151. , clioverrides
  2152. // , __interactve_promts -- Cant just override. Also need selectedinstance to be ready...
  2153. );
  2154. chessinstances[instanceName] = chessinstances[instanceName] || {}
  2155. chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  2156. if(!selectedinstance.repos[0].repo) {
  2157. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  2158. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  2159. }
  2160. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  2161. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  2162. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  2163. }
  2164. // Config from server always override merges into selection except for the current selection.
  2165. // PB : TODO -- utils.assign Array merges are non-distinct...
  2166. chessinstances[instanceName][node_env] = selectedinstance = utils.assign(selected, selectedinstance)
  2167. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  2168. cacheWriteInstanceConfig(chessinstances)
  2169. // PB : TODO -- We should probably write the new server config also...
  2170. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  2171. return chessinstances
  2172. }
  2173. var noprerequisites = {
  2174. add : true, 'set-url' : true, 'repo-relocate' : true
  2175. , remote : true
  2176. }
  2177. var skipprereqs = {}
  2178. var maintask = () => {
  2179. // Default cmd to run !
  2180. processedArgs._[0] === processedArgs._[0] || 'pull';
  2181. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  2182. if(!noprerequisites[processedArgs._[0]]
  2183. && !skipprereqs[processedArgs._[0]]
  2184. ) {
  2185. return prerequisites.git.verifyAndInstall().then(()=>{
  2186. var e = { message : 'verifyAndInstall', success : true}
  2187. return acquireConfig(selectedinstance).catch((err) => {
  2188. e = err;
  2189. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  2190. console.error(err)
  2191. }).then(() => { preworkerconfig(); return elxrworker(true) })
  2192. // .finally(()=>{
  2193. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  2194. // if(!e.success) fs.writeFileSync('run.done', 'error');
  2195. // // return process.exit()
  2196. // })
  2197. })
  2198. }
  2199. else {
  2200. console.log('cmd has no preqs or has been configured to skip preqs')
  2201. preworkerconfig()
  2202. return elxrworker()
  2203. }
  2204. }
  2205. const retaincount = 2
  2206. var min = runtimestamp;
  2207. var collect = []
  2208. if(noprerequisites[processedArgs._[0]]
  2209. || skipprereqs[processedArgs._[0]]
  2210. ) {
  2211. return elxrworker()
  2212. }
  2213. return detectInstance().then((detectedInstance)=>{
  2214. selectedinstance = Object.assign(detectedInstance || {}, clioverrides);
  2215. var todo = Promise.resolve(true);
  2216. var promptkeys = { 'instanceName' : clioverrides.instanceName, 'node_env' : clioverrides.node_env }
  2217. if(clioverrides.reconfirm) {
  2218. var reconfirm = {
  2219. 'instanceName' : selectedinstance['instanceName'] === 'chess'
  2220. }
  2221. }
  2222. else {
  2223. var reconfirm = {};
  2224. }
  2225. var prompts = [];
  2226. var eachPrompt = function(k, i, a){
  2227. // No local instances config found. We use a default initialized instance available in selectedinstance
  2228. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  2229. // PB : TODO -- selectedinstance === __default check to prompt everything...
  2230. if( (promptkeys[k] !== undefined && promptkeys[k] !== null) && selectedinstance[k] !== promptkeys[k]
  2231. || (promptkeys[k] === undefined || promptkeys[k] === null) && (selectedinstance[k] === undefined || selectedinstance[k] === null)
  2232. || reconfirm[k]) {
  2233. prompts.push(async ()=>{
  2234. // PB : NOTE -- Important in async cases when this needs to be in the same state as when it was invoked.
  2235. // We take a snapshot... Shallow.. !! If required deep should be used based on use case.
  2236. // If latest altered state is required we can reerence this directly.
  2237. // var asyncthis = Object.assign(this);
  2238. Object.defineProperty(selectedinstance, k, getPromptableAsyncPropDescriptor(k, choices[k], promptkeys[k] || selectedinstance[k] ));
  2239. return await selectedinstance[k]
  2240. })
  2241. }
  2242. delete promptkeys[k]
  2243. }
  2244. try {
  2245. chessinstances = acquirelocalinstances(selectedinstance);
  2246. initinstances(selectedinstance)
  2247. var instanceNameChoices = new Set(Object.keys( chessinstances) )
  2248. instanceNameChoices.delete('current_run')
  2249. instanceNameChoices.add(selectedinstance['instanceName'])
  2250. if(promptkeys['instanceName']) instanceNameChoices.add(promptkeys['instanceName'])
  2251. var choices = {
  2252. 'instanceName' : Array.from(instanceNameChoices)
  2253. , 'reposerver' : selectedinstance['reposervers']
  2254. }
  2255. Object.keys(__interactve_promts).forEach(eachPrompt, __interactve_promts)
  2256. Object.keys(promptkeys).forEach(eachPrompt, promptkeys)
  2257. todo = any(prompts).then(()=>{ return selectedinstance })
  2258. }
  2259. catch (e) {
  2260. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  2261. initinstances(selectedinstance)
  2262. var instanceNameChoices = new Set(Object.keys( chessinstances) )
  2263. instanceNameChoices.delete('current_run')
  2264. instanceNameChoices.add(selectedinstance['instanceName'])
  2265. if(promptkeys['instanceName']) instanceNameChoices.add(promptkeys['instanceName'])
  2266. var choices = {
  2267. 'instanceName' : Array.from(instanceNameChoices)
  2268. , 'reposerver' : selectedinstance['reposervers']
  2269. , 'instanceType' : ['development', 'production']
  2270. }
  2271. Object.keys(__interactve_promts).forEach(eachPrompt, __interactve_promts)
  2272. Object.keys(promptkeys).forEach(eachPrompt, promptkeys)
  2273. todo = any(prompts).then(()=>{ return selectedinstance })
  2274. if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  2275. // Weve been told what to do.
  2276. todo = todo.then(() => { return acquireChoices(selectedinstance) })
  2277. }
  2278. todo = todo.then(() => {
  2279. try {
  2280. chessinstances = acquirelocalinstances(selectedinstance)
  2281. initinstances(selectedinstance)
  2282. }
  2283. catch (e) {
  2284. console.error(e)
  2285. console.log('No local instances config found in current root = ' + selectedinstance.root);
  2286. console.log('A config will be createed with the instance and environment chosen...')
  2287. // return (async ()=>{return await __default.reposerver})().then(()=>{
  2288. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  2289. // return selectedinstance = Object.assign(__default, selectedinstance);
  2290. // })
  2291. return selectedinstance
  2292. }
  2293. })
  2294. }
  2295. return todo
  2296. })
  2297. .then(()=>{
  2298. if(!__isElevated) {
  2299. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/readme.txt`)
  2300. // collect garbage
  2301. return dirs( (dir)=>{
  2302. var matches = /run-(.*)/gm.exec(dir.name)
  2303. if(matches) {
  2304. if(+(matches[1]) < min) {
  2305. min = matches[1]
  2306. collect.splice( 0, 0, matches[1] )
  2307. }
  2308. else collect.push(matches[1])
  2309. }
  2310. }, `${selectedinstance.root}/.elxr` ).then(()=>{
  2311. // delete garbage
  2312. if(collect.length > retaincount) {
  2313. var asyncs = [];
  2314. while((collect.length - asyncs.length) > retaincount) {
  2315. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  2316. }
  2317. return Promise.all(asyncs)
  2318. }
  2319. else return true
  2320. })
  2321. }
  2322. else return true;
  2323. })
  2324. .then(()=>{
  2325. // PB : TODO -- Keep only the last n runs...
  2326. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  2327. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
  2328. if (!skipprerequisites && !__isElevated || processedArgs.forceprereqs && !__isElevated ) mainTasks.push(verifyAndInstallPrerequisites);
  2329. mainTasks.push(maintask)
  2330. return any(mainTasks);
  2331. })
  2332. })
  2333. // detect if alread installed -> Take no action.
  2334. // download if no installer avalable -> next()
  2335. // install
  2336. function chackandinstall(items) {
  2337. var tasks = []
  2338. items.forEach(item => {
  2339. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  2340. })
  2341. return Promise.all(tasks).then(existances => {
  2342. existances.forEach((exists, i) => {
  2343. if (!exists) {
  2344. return downloadandinstall([items[i]])
  2345. }
  2346. })
  2347. })
  2348. }
  2349. function downloadandinstall(items) {
  2350. var tasks = []
  2351. items.forEach(item => {
  2352. tasks.push(getTaskDownload(item))
  2353. })
  2354. return Promise.all(tasks)
  2355. }
  2356. // Sample instances config.
  2357. // var instances = {
  2358. // "elixir": {
  2359. // "production": {
  2360. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  2361. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  2362. // , "exludeMergeRepos": {
  2363. // "elixir-config-development": true, "elixir-config-test": true
  2364. // , "elixir-config-production": true, "elixir-data": true
  2365. // }
  2366. // , "instanceName": "elixir", "node_env": "production"
  2367. // }
  2368. // },
  2369. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  2370. // }
  2371. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...