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

index.js 191KB

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