Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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