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

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