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

index.js 149KB

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