Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887
  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. // Usage : elxr start {{instanceName=elixir}} {{all||server||client||{{microserviceName=elixir||express}}}}
  1618. var label = clioverrides.cmd
  1619. var env = Object.assign({}, process.env); // Shallow clone it.
  1620. env.NODE_ENV = clioverrides.node_env || 'development';
  1621. var nodecmd = clioverrides.node_env === 'development' ? 'nodemon' : 'node';
  1622. function startFn( o ){
  1623. var cmd = [nodecmd, [`--inspect=${o.debugport}`, '--preserve-symlinks', o.script]]
  1624. console.log(`Starting ${o.name}.`);
  1625. if(shell_verse.iswin()){
  1626. var __cmd = 'cmd'
  1627. var a1 = '/k'
  1628. }
  1629. else if(shell_verse.islin()) {
  1630. var __cmd = 'sh'
  1631. var a1 = '-c'
  1632. }
  1633. if(o.cmd) {
  1634. cmd = o.cmd
  1635. var childPromise = nodeShellExec(...o.cmd, {
  1636. // inherit : true,
  1637. shell: true,
  1638. detached: true,
  1639. stdio: 'ignore',
  1640. cwd: instanceroot + o.path
  1641. , env: env
  1642. })
  1643. }
  1644. else {
  1645. var childPromise = nodeShellExec(__cmd, [a1, getCmdString(cmd) ], {
  1646. // inherit : true,
  1647. shell: true,
  1648. detached: true,
  1649. stdio: 'ignore',
  1650. cwd: instanceroot + o.path
  1651. , env: env
  1652. })
  1653. }
  1654. var child = childPromise.process;
  1655. var cpid = child.pid
  1656. childPromise.then(()=>{
  1657. console.log(` *** started ${o.name} PID(${cpid}) ${cmd}`);
  1658. fs.writeFileSync(o.pidstore, '' + cpid)
  1659. })
  1660. .catch(e => console.error(e) )
  1661. }
  1662. if(clioverrides.node_env === 'development') {
  1663. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  1664. if(!processedArgs._[2]) processedArgs._[2] = 'all'
  1665. if(processedArgs._[2] === 'server' || processedArgs._[2] === 'all'
  1666. || processedArgs._[2] === 'elixir' // specific microservice name.
  1667. ) {
  1668. startFn( { debugport : 9228, script : 'elixir/server.js', name : 'Elixir Loopback Server', path : '/' + 'elixir-server'
  1669. , pidstore : '.elixir-server.elixir.server.pid'
  1670. } )
  1671. }
  1672. if(processedArgs._[2] === 'server' || processedArgs._[2] === 'all'
  1673. || processedArgs._[2] === 'express' // specific microservice name.
  1674. ) {
  1675. startFn( { debugport : 9227, script : 'bin/www', name : 'Express Server', path : '/' + 'chess-server-lib/server'
  1676. , pidstore : '.express.server.pid'
  1677. } )
  1678. }
  1679. if(processedArgs._[2] === 'client' || processedArgs._[2] === 'all') {
  1680. startFn( {
  1681. name : 'Elixir Ember Client', path : '/' + 'client'
  1682. , cmd : ['node_modules/ember-cli/bin/ember', ['s']]
  1683. , pidstore : '.client.server.pid'
  1684. } )
  1685. }
  1686. }
  1687. }
  1688. , 'stop': (label) => {
  1689. const kill = require('tree-kill');
  1690. try{
  1691. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', { encoding: 'utf8'})
  1692. fs.unlinkSync('.elixir-server.elixir.server.pid')
  1693. console.log(serverPid)
  1694. kill(serverPid)
  1695. }
  1696. catch(e){ console.error(e) }
  1697. try{
  1698. serverPid = fs.readFileSync('.express.server.pid', { encoding: 'utf8' })
  1699. fs.unlinkSync('.express.server.pid')
  1700. console.log(serverPid)
  1701. kill(serverPid)
  1702. }
  1703. catch(e){ console.error(e) }
  1704. try{
  1705. serverPid = fs.readFileSync('.client.server.pid', { encoding: 'utf8' })
  1706. fs.unlinkSync('.client.server.pid')
  1707. console.log(serverPid)
  1708. kill(serverPid)
  1709. }
  1710. catch(e){ console.error(e) }
  1711. }
  1712. , 'model' : () => {
  1713. var etask = ()=>{
  1714. var tasks = [
  1715. () => {
  1716. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  1717. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  1718. inherit: true, shell: true
  1719. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  1720. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  1721. , env: process.env
  1722. }).catch((e) => { console.error(e) })
  1723. return p;
  1724. }
  1725. ];
  1726. return any(tasks).then(() => {
  1727. fs.writeFileSync('run.done', 'success')
  1728. }).catch(() => {
  1729. fs.writeFileSync('run.done', 'error')
  1730. })
  1731. }
  1732. etask.statuslog = statuslog
  1733. etask.selectedinstance = selectedinstance
  1734. etask.processedArgs = processedArgs
  1735. etask.runtimestamp = runtimestamp
  1736. etask.ENV = ENV
  1737. return shell_verse.runElevated(etask)
  1738. }
  1739. , 'use' : () => {
  1740. // use a certain named instance.
  1741. // Eg :
  1742. // 1) elxr use elixir
  1743. // 2) elxr use cihsr
  1744. // If environment is not specified defaults to development.
  1745. // 1) NODE=test elxr use elixir
  1746. /*// Steps
  1747. 1) Delete Config and Data symlinks
  1748. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  1749. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  1750. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1751. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  1752. */
  1753. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  1754. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  1755. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  1756. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  1757. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  1758. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  1759. if (existsSync('config') && existsSync('data')){
  1760. return
  1761. }
  1762. }
  1763. var tasks = [
  1764. () => {
  1765. var promise = new Promise((resolve, reject)=>{
  1766. existslink('config', function(err, data){
  1767. if(data) {
  1768. var p = shell_verse.removeJuncionOrLink('config')
  1769. .then(()=>{resolve(true)})
  1770. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
  1771. }
  1772. else resolve(false)
  1773. })
  1774. })
  1775. return promise;
  1776. },
  1777. () => {
  1778. var promise = new Promise((resolve, reject)=>{
  1779. existslink('data', function(err, data){
  1780. if(data) {
  1781. var p = shell_verse.removeJuncionOrLink('data')
  1782. .then(()=>{resolve(true)})
  1783. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
  1784. }
  1785. else resolve(false)
  1786. })
  1787. })
  1788. return promise;
  1789. },
  1790. ];
  1791. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  1792. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  1793. if (!runconfig.use && selectedinstance.instanceName) runconfig.use = selectedinstance.instanceName;
  1794. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  1795. // console.log(process.env.cwd)
  1796. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  1797. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  1798. var performPullOrCloneForBranch = (def)=>{
  1799. var promise = Promise.resolve(true)
  1800. if (!branch) {
  1801. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1802. promise = nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{ branch = __branch})
  1803. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1804. }
  1805. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e )})
  1806. }
  1807. var performCloneAndCheckout = null;
  1808. // cant use git checkout -b it fails when branch already exists.
  1809. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1810. return performPullOrCloneForBranch(def).then(()=>{
  1811. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1812. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  1813. // inherit : true, shell: true,
  1814. cwd: instanceroot + '/' + def.repo
  1815. // , stdio : ignore // Use when we want to silence output completely.
  1816. , runas: processedArgs.runas
  1817. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  1818. }).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 } })
  1819. })
  1820. }
  1821. // var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  1822. // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  1823. var elevatedqueue = [];
  1824. var enqueueOnce = (queue, task, def) => {
  1825. var found = queue.find(element => {
  1826. var keys = Object.keys( element )
  1827. for(var k=0; k < keys.length; k++) {
  1828. if(element[keys[k]] !== def[k]) return false;
  1829. }
  1830. })
  1831. queue.push(function(){ return task(this)}.bind(def));
  1832. }
  1833. var enqueue = (queue, task, def) => {
  1834. queue.push(function(){ return task(def)}.bind(def));
  1835. }
  1836. var mergeSources = {
  1837. 'development': null,
  1838. 'test': 'master',
  1839. 'production': 'master'
  1840. }
  1841. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  1842. // Checkout is reduced to pull provided the current branch is the targetbranch
  1843. if(branch === mergesource) performCheckout = (def) => {
  1844. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  1845. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  1846. if(branch === __branch) return performCloneAndCheckout(def)
  1847. return performPullOrCloneForBranch(def)
  1848. })
  1849. .catch((e) => { console.error(e); return { error: true, message: repo } })
  1850. }
  1851. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  1852. var performPullAll = (def) => {
  1853. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  1854. return nodeShellExec('git', ['pull', '--all'], {
  1855. // inherit : true, shell: true,
  1856. cwd: instanceroot + '/' + def.repo
  1857. , runas: processedArgs.runas
  1858. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  1859. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  1860. }
  1861. var excludeCheckouts = Object.assign(exludeMergeRepos)
  1862. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  1863. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  1864. var performMerge = (def) => {
  1865. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  1866. return nodeShellExec('git', ['merge', mergesource], {
  1867. inherit: true, shell: true,
  1868. cwd: instanceroot + '/' + def.repo
  1869. , runas: processedArgs.runas
  1870. }).catch((e) => { console.error(e) })
  1871. }
  1872. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
  1873. // var performRepoOperation = function(def) {
  1874. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  1875. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  1876. // }
  1877. return any(tasks).then(() => {
  1878. var task = ()=>{
  1879. //target is the env is we specify in elxr use command. Default is dev
  1880. //Switch to target branch
  1881. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  1882. // pull or clone target branch
  1883. .then(() => {
  1884. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1885. return any(gitRepos.map((repo) => performPullAll(repo)))
  1886. })
  1887. // switch to source branch
  1888. .then( () => {
  1889. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  1890. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  1891. })
  1892. //Pull on merge source branch
  1893. .then( () => {
  1894. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1895. return any(gitRepos.map((repo) => performPullAll(repo)))
  1896. })
  1897. //Switch to target branch
  1898. .then( () => {
  1899. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1900. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  1901. })
  1902. .then( //Merge source branch to target branch
  1903. () => {
  1904. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1905. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
  1906. })
  1907. }
  1908. task.statuslog = statuslog
  1909. var netask = shell_verse.getNonElevatedTask(task)
  1910. var eltask = ()=> {
  1911. var opts = {
  1912. inherit: true, shell: true
  1913. , cwd : instanceroot
  1914. , env: process.env
  1915. }
  1916. var tasks = [
  1917. () => {
  1918. // Use junctions to avoid npm package issues
  1919. var target = runconfig.use + '-' + 'config' + '-' + process.env.NODE_ENV
  1920. var p = shell_verse.createJuntionOrLink('config', target, opts)
  1921. return p;
  1922. }
  1923. ];
  1924. // if (processedArgs._[1]) {
  1925. tasks = tasks.concat( [
  1926. () => {
  1927. var dataToLink = runconfig.use + '-data' + '-' + process.env.NODE_ENV
  1928. if(!existsSync(dataToLink)) dataToLink = runconfig.use + '-data';
  1929. var p = shell_verse.createJuntionOrLink('data', dataToLink, opts)
  1930. return p;
  1931. }
  1932. ]
  1933. )
  1934. // }
  1935. return any(tasks).then(()=>{
  1936. // checkout target branch
  1937. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1938. // pull or clone target branch
  1939. .then(() => {
  1940. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1941. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  1942. })
  1943. // switch to source branch
  1944. .then( () => {
  1945. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1946. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  1947. })
  1948. //Pull on merge source branch
  1949. .then( () => {
  1950. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1951. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  1952. })
  1953. //Switch to target branch
  1954. .then( () => {
  1955. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1956. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1957. })
  1958. .then( //Merge source branch to target branch
  1959. () => {
  1960. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1961. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
  1962. })
  1963. .then(() => {
  1964. fs.writeFileSync('run.done', 'success')
  1965. }).catch(() => {
  1966. fs.writeFileSync('run.done', 'error')
  1967. })
  1968. })
  1969. }
  1970. eltask.statuslog = statuslog
  1971. eltask.selectedinstance = selectedinstance
  1972. eltask.processedArgs = processedArgs
  1973. var etask = shell_verse.getElevatedTask(eltask)
  1974. return etask().then( ()=>{ return netask() })
  1975. }).catch((e) => {
  1976. fs.writeFileSync('run.done', 'error : ' + e)
  1977. })
  1978. // Antibiotic stewardship program.
  1979. // 1st use is fine.
  1980. // Max vials dispense
  1981. // 2nd use Pharmacy needs justification Form.
  1982. // Approval after a certain period of time.
  1983. }
  1984. , 'g' : () => {
  1985. if (processedArgs.h) {
  1986. console.log('elxr g model [modelname] => generate a model named [modelname]');
  1987. console.log('elxr g vmodel [modelname] => generate a model named [modelname]');
  1988. console.log('elxr g vmodel [modelname] --server=true => generate only a server model named [modelname]');
  1989. console.log('elxr g vmodel [modelname] --all=true => default generate server and client model named [modelname]');
  1990. console.log('elxr g => regenerate all known models');
  1991. return
  1992. }
  1993. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1994. // console.log('Starting directory: ' + process.cwd());
  1995. // try {
  1996. // child = child.on('close', () => { process.chdir(label) } );
  1997. // console.log('New directory: ' + process.cwd());
  1998. // }
  1999. // catch (err) {
  2000. // console.log('chdir: ' + err);
  2001. // }
  2002. // child.on('close', function(){
  2003. // var options = {
  2004. // shell : true
  2005. // , inherit : true
  2006. // // , cwd : '' + process.cwd
  2007. // // , env : process.env
  2008. // };
  2009. // nodeShellExec('git', ['init'], { inherit : true});
  2010. if (0) {
  2011. // PB : TODO -- Special google chrome profile for tests etc.
  2012. nodeShellExec('pwd', { inherit: true });
  2013. // /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"
  2014. // "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
  2015. // "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
  2016. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  2017. "--profile-directory=Profile 1"
  2018. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  2019. }
  2020. // nodeShellExec('npm', ['init', '-y'], options);
  2021. // nodeShellExec('npm', ['init', '-y'], options);
  2022. // })
  2023. var g = {
  2024. 'client': () => {
  2025. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  2026. console.info('Creating new ember client named : ' + processedArgs._[2]);
  2027. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  2028. stdio: ['pipe', process.stdout, process.stderr],
  2029. inherit: true,
  2030. shell: true,
  2031. cwd: path.dirname(__dirname),
  2032. env: env
  2033. })
  2034. },
  2035. 'modelr': () => {
  2036. var tasks = [
  2037. () => {
  2038. var p = nodeShellExec('"ember"', [
  2039. 'g'
  2040. , 'modelr'
  2041. , processedArgs._[2]], {
  2042. inherit: true, shell: true, env: process.env
  2043. }).then(() => {
  2044. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  2045. return true;
  2046. }).catch((e) => { console.error(e) })
  2047. return p;
  2048. },
  2049. () => {
  2050. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  2051. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  2052. chromeprefs = JSON.parse(chromeprefs)
  2053. var previous = chromeprefs.download.default_directory;
  2054. var parentDir = path.dirname(__dirname);
  2055. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  2056. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  2057. // PB : TODO -- detect where chrome is installed.
  2058. // PB : TODO -- set the download dir to the place where files are needed.
  2059. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  2060. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  2061. , '--profile-directory="chess"'
  2062. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  2063. inherit: true, shell: true
  2064. , env: process.env
  2065. }).then(() => {
  2066. chromeprefs.download.default_directory = previous;
  2067. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  2068. return true;
  2069. }).catch((e) => { console.error(e) })
  2070. return p;
  2071. }
  2072. ,
  2073. () => {
  2074. console.log('Browser process should have closed here....')
  2075. return true;
  2076. }
  2077. ]
  2078. any(tasks)
  2079. }
  2080. , 'undefined' : ()=>{
  2081. console.warn('Are you sure you want to refresh all the models.');
  2082. throw 'NOT YET IMPLMENTED'
  2083. }
  2084. , 'vmodel' : (options)=>{
  2085. // node --inspect-brk elxr/index.js g vmodel qlabresults --server=true
  2086. options = options || {
  2087. generate : processedArgs['all'] ? 'all' : processedArgs['server'] ? 'server' : processedArgs['client'] ? 'client' : null
  2088. }
  2089. if(!options.generate) return 'Nothing specified for generation'
  2090. var name = processedArgs._[2];
  2091. if(!name) return 'No name specified for generation'
  2092. var templateverse = `${selectedinstance.root}/bbhverse/__universe__/vmodel`
  2093. // var templateverse = `${selectedinstance.root}/bbhverse/__universe__/vmodel/__base__-server-lib/common/lib`
  2094. var workingtarget = `${selectedinstance.root}/.elxr/run-${runtimestamp}/temp/vmodelworkingdir`
  2095. var destination = `${selectedinstance.root}`
  2096. // Create a tmp working copy for staging the changes.
  2097. return copyrecursive(templateverse, workingtarget).then( r => {
  2098. var base = 'chess' // -- The server base from where this instance was dervied from.
  2099. var patternsubstitutions = [
  2100. { strOrregexp : /(__name__)/g, substitutes : [name]}
  2101. , { strOrregexp : /(__instance__)/g, substitutes : [selectedinstance.instanceName]}
  2102. , { strOrregexp : /(__base__)/g, substitutes : [base]}
  2103. , { strOrregexp : /(__microservice__)/g, substitutes : [selectedinstance.microservice || selectedinstance.instanceName]}
  2104. , { strOrregexp : /(__microclient__)/g, substitutes : [selectedinstance.microclient || `${selectedinstance.instanceName}-client` || 'client']} // PB : TODO -- elixir-client etc... use a config to find the microclient..
  2105. ]
  2106. var options = { source : templateverse, target : workingtarget
  2107. , base , destinationroot : destination, workingtarget
  2108. , processingtype : 'inplace', sourcetype : 'filesystem', patternsubstitutions }
  2109. var actions = [
  2110. fswalk( workingtarget, options
  2111. , [ function(t, o){
  2112. // A series of tasks to be executed on each pattern in patternsubstitutions.
  2113. return any([
  2114. // PB : TODO -- Contentreplace is better addressed in memory instead of file IO so do all regexps in sequence in one shot and then rename.
  2115. ()=>{ return fscontentreplace( t, o ) }
  2116. , ()=>{ return fsrename( t, o ) }
  2117. ])
  2118. }] )
  2119. // Post process links in place.
  2120. , () => dirs((innernode, s, t, o ) => fswalk( path.join(workingtarget, innernode.name), utils.assign({}, o, { innernode }), [ templatelink ] )
  2121. , workingtarget, null, options)
  2122. // Move to the final destination. Whole tree should move only top level folders are required.
  2123. // , () => fswalk( workingtarget, options, [ fsrename ])
  2124. // , () => dirs( ( child, src, target, options )=>{ return fs.renameSync(path.join(src, child.name), path.join(target, child.name) ) }
  2125. // , workingtarget, destination )
  2126. ]
  2127. return any(actions);
  2128. })
  2129. }
  2130. }
  2131. g[processedArgs._[1]]();
  2132. }
  2133. , 'create' : () => { return createInstance(selectedinstance) }
  2134. , 'httpget' : () => {
  2135. // RESTAPI.get({
  2136. // hostname: 'git.bbh',
  2137. // // port: 443,
  2138. // protocol : 'http:',
  2139. // path: '/',
  2140. // method: 'GET'
  2141. // }, function(data){ console.log(data)}, function(error){ console.log(error)} )
  2142. return createInstance(selectedinstance)
  2143. }
  2144. , 'getuser' : ()=>{ return prerequisites.git.getuser().then(u=>{ console.log(u)}) }
  2145. , 'switch user' : (tousername)=>{ return GIT['switch user'](tousername) }
  2146. }
  2147. // independent elxr cli operations
  2148. var noprerequisites = {
  2149. add : true, 'set-url' : true, 'repo-relocate' : true
  2150. , remote : true, 'c' : true, 'h' : true
  2151. , httpget : true, getuser : true
  2152. , 'switch user' : true
  2153. , 'switch' : true
  2154. // , 'undefined' : true
  2155. }
  2156. var reconfirmcmds = { create : true }
  2157. var subcommandlabels = {
  2158. remote : (`remote ${processedArgs._[1] || ''}`).trim()
  2159. , switch : (`switch ${processedArgs._[1] || ''}`).trim()
  2160. }
  2161. var independentcmd = function(){
  2162. return false;
  2163. }
  2164. var cmds = {
  2165. remote : {
  2166. // return a interpreted set of arguments for this comd run context.
  2167. interpret() {
  2168. return { cmd : subcommandlabels['remote'], runchoice : 'c' }
  2169. }
  2170. }
  2171. , resetgitconfig : {
  2172. // return a interpreted set of arguments for this comd run context.
  2173. cmdFn : resetgitconfig
  2174. , interpret() { return { cmd : 'resetgitconfig' } }
  2175. , getPossiblePrompts(){ return {} }
  2176. , noprerequisites : true
  2177. , independentcmd : true
  2178. }
  2179. , reinit : {
  2180. // return a interpreted set of arguments for this comd run context.
  2181. cmdFn : reinit
  2182. , interpret() { return { cmd : 'reinit' } }
  2183. , getPossiblePrompts(){ return {} }
  2184. , noprerequisites : true
  2185. , independentcmd : true
  2186. , requiresElevation : true
  2187. , requires : [ generateDependencies ]
  2188. }
  2189. , init : {
  2190. // return a interpreted set of arguments for this comd run context.
  2191. cmdFn : init
  2192. , interpret() { return { cmd : 'init' } }
  2193. , getPossiblePrompts(){ return {} }
  2194. , noprerequisites : true
  2195. , independentcmd : true
  2196. , requiresElevation : true
  2197. , requires : [ generateDependencies ]
  2198. }
  2199. , switch : {
  2200. interpret() {
  2201. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2]
  2202. , reposerver : __default.reposerver
  2203. }
  2204. }
  2205. , getPossiblePrompts(){ return { username : true, reposerver : 'http://git.bbh' } } // Requires only one argument...
  2206. }
  2207. , 'switch user' : {
  2208. interpret() {
  2209. return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2] }
  2210. }
  2211. , getPossiblePrompts(){ return { username : true } } // Requires only one argument...
  2212. }
  2213. // Flat linear structure. Every subcommand should have a top level 'label'
  2214. , 'users' : {
  2215. // default to the users list
  2216. subcommands : { list : {} }
  2217. , cmdFn : ()=>getCredentials() // default
  2218. , cmd : 'users'
  2219. , noprerequisites : true
  2220. }
  2221. , 'users list' : {
  2222. cmdFn : ()=>getCredentials()
  2223. , cmd : 'users list'
  2224. , noprerequisites : true
  2225. }
  2226. , 'get-upstream' :{
  2227. cmdFn : op['get-upstream'] // default
  2228. , cmd : 'get-upstream'
  2229. , noprerequisites : true
  2230. , independentcmd : true
  2231. , interpret() { return { cmd : 'get-upstream' } }
  2232. , getPossiblePrompts(){ return {} }
  2233. }
  2234. , 'g' : {
  2235. cmdFn : op['g'] // default
  2236. , cmd : 'g'
  2237. , noprerequisites : true
  2238. , getPossiblePrompts(){ return {} }
  2239. }
  2240. , 'link' : {
  2241. 'cmd' : 'link'
  2242. // , cmdFn : function( sourecpath, filename, dir ){
  2243. // var afterTargetPath = (dir)=>{
  2244. // console.dir(dir);
  2245. // // var tasks = [
  2246. // // () => {
  2247. // // // Use junctions to avoid npm package issues
  2248. // // var p = nodeShellExec('mklink', ['/J', filename, sourecpath], {
  2249. // // inherit: true, shell: true
  2250. // // , cwd : dir || instanceroot
  2251. // // , env: process.env
  2252. // // }).catch((e) => { console.error(e) })
  2253. // // return p;
  2254. // // }
  2255. // // ];
  2256. // }
  2257. // // console.dir(process.env)
  2258. // if(!dir) getCurrentFolder().then(afterTargetPath);
  2259. // else afterTargetPath(dir)
  2260. // }
  2261. , cmdFn : function( cmdopts ){
  2262. // sourecpathandfile should include name of file name
  2263. targetfilename = cmdopts.targetfilename || processedArgs._[1]
  2264. // console.log(processedArgs)
  2265. if(!targetfilename) return Promise.reject('error no file provided for linking')
  2266. targetdir = cmdopts.targetdir || process.env.wd
  2267. sourecpathandfile = cmdopts.sourecpathandfile || path.normalize(`../../node_modules/chess-server-lib/common/models/${targetfilename}`)
  2268. var tasks = [
  2269. () => {
  2270. // Use junctions to avoid npm package issues
  2271. var p = nodeShellExec('mklink', [path.normalize(`${targetdir + '/' + targetfilename}`), sourecpathandfile], {
  2272. inherit: true, shell: true
  2273. , cwd : targetdir
  2274. , env: process.env
  2275. }).catch((e) => { console.error(e) })
  2276. return p;
  2277. }
  2278. ];
  2279. var etask = ()=>{
  2280. return any(tasks).then(() => {
  2281. fs.writeFileSync('run.done', 'success')
  2282. }).catch(() => {
  2283. fs.writeFileSync('run.done', 'error')
  2284. })
  2285. }
  2286. etask.statuslog = statuslog
  2287. etask.selectedinstance = selectedinstance
  2288. etask.processedArgs = processedArgs
  2289. etask.runtimestamp = runtimestamp
  2290. etask.ENV = ENV
  2291. return shell_verse.runElevated(etask)
  2292. }
  2293. , noprerequisites : true
  2294. , privileged : true
  2295. }
  2296. }
  2297. var elxrcmd = (function(){
  2298. var __cmdprototype = function(){}
  2299. function subcommandlabelFor(cmd, sub){ return (`${cmd} ${sub || ''}`).trim() }
  2300. var __cmd = {
  2301. interpret() { return { cmd : this.cmd } }
  2302. , getPossiblePrompts(){ return {} } // Requires only one argument...
  2303. , cmdFn : ()=>{ throw "Elxr Unknown command."}
  2304. , finalized : true
  2305. }
  2306. function __createO(o){
  2307. if(o.finalized) return o;
  2308. var subs = Object.keys(cmds[o.cmd].subcommands || {})
  2309. // console.log(subs)
  2310. // console.log(o)
  2311. subs.forEach(sub=>elxrcmd.create( cmds[subcommandlabelFor(o.cmd, sub)] ))
  2312. var created = utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  2313. , {}, __cmd, cmds[o.cmd], o)
  2314. cmds[o.cmd] = created;
  2315. op[o.cmd] = created.cmdFn;
  2316. noprerequisites[o.cmd] = created.noprerequisites
  2317. return created.cmdFn;
  2318. }
  2319. function create(o){ return __createO(o) }
  2320. __cmdprototype.create = create;
  2321. return __cmdprototype;
  2322. })()
  2323. elxrcmd.create(cmds['users'])
  2324. elxrcmd.create(cmds['g'])
  2325. elxrcmd.create(cmds['link'])
  2326. var interpretrun = function(){
  2327. var cmd = processedArgs._[0];
  2328. var clioverrides = { cmd }
  2329. processedArgs.node_env ? clioverrides.node_env = processedArgs.node_env
  2330. : (process.env.NODE_ENV && process.env.NODE_ENV.trim())
  2331. ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) : null;
  2332. return cmds[cmd] ? cmds[cmd].interpret() : (function(){
  2333. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  2334. // return clioverrides
  2335. cmds[cmd] = {
  2336. interpret() {
  2337. return Object.assign(clioverrides, { cmd, runchoice : 'c' })
  2338. }
  2339. , getPossiblePrompts(){ return { cmd, username : true, password : true,
  2340. instanceName : true, instanceType : true, reposerver : true } }
  2341. }
  2342. return cmds[cmd].interpret()
  2343. })()
  2344. }
  2345. var clioverrides = interpretrun()
  2346. console.dir(clioverrides)
  2347. var util = require('util');
  2348. var cliname = 'elxr';
  2349. var ver = '1.1';
  2350. var readme = `
  2351. Command syntax examples
  2352. elxr
  2353. Displays help. Same as elxr h
  2354. elxr i
  2355. Runs interactive propmts to help choose installation options.
  2356. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  2357. General command syntax.
  2358. Eg: NODE_ENV=development elxr pull elixir
  2359. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  2360. The specific cmd defines what the value is interpreted as.
  2361. There are several cmds that do not require an {{instancename}} parameter.
  2362. Eg: elxr remote remove origin
  2363. Git operations or passthrough external commands on all repository folders in you working directory.
  2364. Main objectives.
  2365. elxr cli is a wrapper around other shell commands and api based operations.
  2366. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  2367. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  2368. `;
  2369. var help = `
  2370. ${readme}
  2371. # list of commands... please refer dveloper documentation for ${cliname}
  2372. \r\n\t${
  2373. Object.keys(op).join('\r\n\t')
  2374. }
  2375. `;
  2376. var elxr = {
  2377. help() {
  2378. return chalk.cyanBright(`
  2379. -------------------------------------------------------------------------------
  2380. *** BBH Elixir ***
  2381. -------------------------------------------------------------------------------
  2382. elxr ${ver}
  2383. A cli tool for chess
  2384. ${help}
  2385. -------------------------------------------------------------------------------
  2386. `)
  2387. }
  2388. , info() {
  2389. return chalk.cyanBright(`
  2390. -------------------------------------------------------------------------------
  2391. *** BBH Elixir ***
  2392. -------------------------------------------------------------------------------
  2393. elxr ${ver}
  2394. A cli tool for chess
  2395. -------------------------------------------------------------------------------
  2396. `)
  2397. }
  2398. , getpulltask(args){
  2399. // def can be an instance config
  2400. // Or an object with many repos and elevated repos
  2401. // Or a single repo ( Either Elevated or normal. )
  2402. // USAGE
  2403. // elxr pull elixir origin master
  2404. // elxr pull
  2405. // not all remote branches are setup to be tracked locally (respective remotes and branches).
  2406. // pull --all is useless. As it fetches all remotes and branches but only merges current branch.
  2407. // apart from remote tracking branches We are interested in pulling from all remotes and relavant branches.
  2408. // The branch pipline should feed back to master
  2409. // master -> test -> stage -> release[nnnn] -> production
  2410. // (master) <= git merge [all remotes] production && git merge [all remotes] release[nnnn]
  2411. // git merge [all remotes] stage && git merge [all remotes] test && git merge [all remotes] master
  2412. var __args = {
  2413. remotename : args.remotename|| processedArgs._[2]
  2414. , url : args.url || processedArgs._[3]
  2415. , branch : args.branch || processedArgs._[4] // If branch not specified opearte on the current branch of each working directorys
  2416. }
  2417. // var commands = [
  2418. // // ['git', ['checkout', __args.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]]
  2419. // ,
  2420. // ]
  2421. // var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  2422. // var pullCmd = [ gitbash
  2423. // , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  2424. // , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  2425. var def = args || {
  2426. repos : selectedinstance.repos,
  2427. elevated : selectedinstance.elevated
  2428. }
  2429. var elevatedpulltasks = null;
  2430. if(def.repo) {
  2431. // Single repo case.
  2432. if(def.repo.requiresElevation) {
  2433. var t1 = function() {
  2434. return performPull(def).then(() => {
  2435. return true;
  2436. }).catch((e) => {
  2437. console.error(e)
  2438. }).finally(Traq.finally)
  2439. }
  2440. t1.statuslog = statuslog
  2441. t1.selectedinstance = selectedinstance
  2442. t1.processedArgs = processedArgs
  2443. elevatedpulltasks = shell_verse.getElevatedTask( t1 )
  2444. }
  2445. else {
  2446. var t2 = function(){
  2447. return performPull(def).then(() => {
  2448. console.log('pulled ' + JSON.stringify(def.repo))
  2449. return true;
  2450. }).catch((e) => {
  2451. console.error(e)
  2452. }).finally(Traq.finally)
  2453. }
  2454. t2.statuslog = statuslog
  2455. var regularpulltasks = shell_verse.getNonElevatedTask( t2 )
  2456. }
  2457. if(elevatedpulltasks) return elevatedpulltasks //getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  2458. else return regularpulltasks // getTaskWithoutElevation({ regularpulltasks})
  2459. }
  2460. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  2461. console.dir(def)
  2462. var env = Object.assign({}, process.env); // Shallow clone it.
  2463. console.log('Running exlr pull : ' + path.dirname(__dirname))
  2464. var useGitPull = processedArgs.useGitPull || false;
  2465. if(def.elevated || def.repos) {
  2466. if(def.elevated) def.requiresElevation = true;
  2467. else delete def.requiresElevation;
  2468. }
  2469. else {
  2470. if(def.requiresElevation) def.elevated = [def]
  2471. else def.repos = [def]
  2472. }
  2473. var regularpulltasks = function(){ return Promise.resolve(true) }
  2474. if(def.elevated){
  2475. elevatedpulltasks = function() {
  2476. var eBatch = []
  2477. def.elevated.map((def) => getPullTask(def, null, null, null, eBatch))
  2478. return shell_verse.runElevatedBatch(eBatch).then(() => {
  2479. return true;
  2480. }).catch((e) => {
  2481. console.error(e)
  2482. })
  2483. }
  2484. elevatedpulltasks.statuslog = statuslog
  2485. }
  2486. if(def.repos) {
  2487. var regularpulltasks = function(){
  2488. var pendingpulls = [];
  2489. def.repos.forEach((def) => {
  2490. pendingpulls.push(
  2491. performPull(def).then(()=>{ console.log('pulled ' + JSON.stringify(def.repo)) })
  2492. .catch(e => { console.log(e); throw e })
  2493. )
  2494. })
  2495. return any(pendingpulls).finally(Traq.finally)
  2496. }
  2497. regularpulltasks.statuslog = statuslog
  2498. }
  2499. // if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  2500. // else return getTaskWithoutElevation({ regularpulltasks})
  2501. return any([ elevatedpulltasks, regularpulltasks ])
  2502. }
  2503. }
  2504. function preworkerconfig(){
  2505. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  2506. gitRepos = selectedinstance.repos
  2507. // gitRepos = ['chess-server-lib'];
  2508. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  2509. elevatedRunasRepos = selectedinstance.elevated
  2510. // Repos that should excluded from merge for releases...
  2511. exludeMergeRepos = selectedinstance.exludeMergeRepos
  2512. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  2513. // mysql -u root -p db_name < drop_all_tables.sql
  2514. var mysql = '../xampp/mysql/bin/mysql'
  2515. var mysqldump = '../xampp/mysql/bin/mysqldump'
  2516. }
  2517. // The main elxr cli process
  2518. function elxrworker() {
  2519. var __runcmd = function (label) {
  2520. var distinquishedlabel = subcommandlabels[label] || label
  2521. return op[distinquishedlabel] ? op[distinquishedlabel](processedArgs) : null;
  2522. }
  2523. // --runas
  2524. if (processedArgs.runas) {
  2525. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  2526. // return __runcmd('runas')
  2527. // we no longer have a runas function. This has been moved to shellverse.requestElevation...
  2528. // 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.
  2529. //
  2530. return __runcmd(processedArgs.label || processedArgs._[0] || 'undefined');
  2531. }
  2532. else return __runcmd(processedArgs.label || processedArgs._[0] || 'undefined');
  2533. }
  2534. // function acquireChoices(selectedinstance) {
  2535. // var hasconfig = false;
  2536. // console.warn(chalk.cyan(`
  2537. // -------------------------------------------------------------------------------
  2538. // Could not locate your preferred configuration (you may not specified it)
  2539. // You should fork the default chess configuration to customize and make it
  2540. // your own instance with a named config as
  2541. // {{yourowninstancename}}-config-{{yourchosenenvironment}}
  2542. // And then run this tool as follows
  2543. // NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  2544. // OR
  2545. // Run this tool with the following command to use a quick start default.
  2546. // elxr --default
  2547. // OR
  2548. // Choose one of the options below to run interactively.
  2549. // We will run your choice at the next prompt.
  2550. // -------------------------------------------------------------------------------
  2551. // `))
  2552. // var choices = getInteractionPoints(detectedinstanceoptions, __interactive_prompts)
  2553. // var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  2554. // return initinstances(selectedinstance)
  2555. // })
  2556. // // var prompt = cli.prompter;
  2557. // // return prompt.ask(`Choose an option :
  2558. // // d) Install the default chess instance.
  2559. // // => elxr i chess node_env=development --default
  2560. // // n) Create your custom new instance interactively
  2561. // // => elxr i {{instanceName}} node_env={{environment}}
  2562. // // i) Choose an instance and environment to install
  2563. // // => elxr i {{instanceName}} node_env={{environment}}
  2564. // // c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  2565. // // => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  2566. // // h) Help
  2567. // // q) Quit
  2568. // // Default <= d
  2569. // // : `).then((choice) => {
  2570. // // if (choice && choice === 'd' || !choice) {
  2571. // // processedArgs._[0] = 'i'
  2572. // // selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  2573. // // selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  2574. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  2575. // // }
  2576. // // else if (choice === 'h') {
  2577. // // processedArgs._[0] = 'h'
  2578. // // fs.writeFileSync('run.done', 'noop help');
  2579. // // console.log(elxr.help()); process.exit()
  2580. // // }
  2581. // // else if (choice === 'n' || choice === 'i') {
  2582. // // var p1 = cli.prompter;
  2583. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  2584. // // processedArgs._[0] = 'i'
  2585. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  2586. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  2587. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  2588. // // if (choice === 'n') {
  2589. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  2590. // // console.warn(
  2591. // // chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  2592. // // process.exit();
  2593. // // }
  2594. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  2595. // // selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  2596. // // })
  2597. // // })
  2598. // // })
  2599. // // } else if (choice === 'c') {
  2600. // // var p1 = cli.prompter;
  2601. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  2602. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  2603. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  2604. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  2605. // // return p1.ask(`Enter cmd :
  2606. // // p) pull
  2607. // // Default <= p
  2608. // // : `).then(function (cmd) {
  2609. // // if (!cmd || cmd === 'p') {
  2610. // // processedArgs._[0] = 'pull'
  2611. // // }
  2612. // // else processedArgs._[0] = cmd
  2613. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  2614. // // selectedinstance.reposerver = reposerver || selectedinstance.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  2615. // // })
  2616. // // })
  2617. // // })
  2618. // // })
  2619. // // } else {
  2620. // // 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.`));
  2621. // // fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  2622. // // fs.writeFileSync('run.done', 'noop quit');
  2623. // // process.exit()
  2624. // // }
  2625. // // })
  2626. // }
  2627. // PB : TODO -- Move this to utils assign... as an array merge option.
  2628. var mergeObjByKey = function(arrOfObjs, keyName) {
  2629. var keyedDistinct = {}
  2630. var distinctArrOfObjs = []
  2631. arrOfObjs.forEach( o => {
  2632. if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o)
  2633. })
  2634. Object.keys(keyedDistinct).forEach(key => {
  2635. distinctArrOfObjs.push( utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  2636. , ...keyedDistinct[key] ) ) // PB : TODO -- Shallow use utils.assign
  2637. })
  2638. return distinctArrOfObjs;
  2639. }
  2640. var cacheWriteInstanceConfig = function(chessinstances){
  2641. var instanceName = chessinstances['current_run'].instanceName;
  2642. var node_env = chessinstances['current_run'].node_env;
  2643. // PB : TODO -- We should be able to do simply merge at a higher level using assign
  2644. chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos || [], 'repo') ;
  2645. chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated || [], 'repo') ;
  2646. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  2647. }
  2648. var os = require("os");
  2649. var hostname = os.hostname();
  2650. var clustername = null; // PB : TODO -- Prompt to acquire.
  2651. var configs = (function(){
  2652. // We need to discover and use the most specialized config available.
  2653. // Two passes are required as the config currently cloned may be switched by the discovery.
  2654. // If the repo name is the same but has different remotes the newly acquired config from multiple remotes may
  2655. // iteself redefine the remotes, repos and servers for the config which we need to honor..
  2656. return {
  2657. ownerClusterNodeConfig(selected) {
  2658. // Hostname and therefore clusternodename can be anything and can participate in many clusters.
  2659. // 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 )
  2660. var clusternodename = hostname || `CHESS0001${selected.username}`; // Cluster node names need to be unique accross all clusters to avoid collitions.
  2661. clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
  2662. return __acquireConfig(selected, { remote : 'userfork' } // PB : TODO -- accessiblity state should switch to public etc..
  2663. , selected.instanceName + '-config-' + selected.node_env + `-${clusternodename}`
  2664. , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
  2665. return e; }
  2666. )
  2667. }
  2668. , ownerInstnace(selected) { return __acquireConfig(selected, { remote : 'userfork' }
  2669. , selected.instanceName + '-config-' + selected.node_env
  2670. , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
  2671. return e }
  2672. )
  2673. }
  2674. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  2675. , commonInstance(selected) { return __acquireConfig(selected, { defaultRepoOwner }
  2676. , undefined
  2677. , function(e){
  2678. // PB : TODO -- console.info('This is probably an error unless the user is asking to create a new instance with this name.')
  2679. statuslog.statuslog(e, e)
  2680. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  2681. utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  2682. , selectedinstance, require(manifestpath)( null, { utils, username : selectedinstance.username, instanceName : selectedinstance.instanceName
  2683. , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' } ))
  2684. console.dir(selectedinstance.repos)
  2685. // Config from server always override merges into selection except for the current selection.
  2686. // PB : TODO -- utils.assign Array merges are non-distinct...
  2687. if(selectedinstance?.repos && !selectedinstance.repos[0].repo) {
  2688. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  2689. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  2690. }
  2691. if(selectedinstance?.elevated && !selectedinstance.elevated[0]?.repo) {
  2692. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  2693. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  2694. }
  2695. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  2696. , selected, selectedinstance)
  2697. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  2698. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  2699. cacheWriteInstanceConfig(chessinstances)
  2700. // ENV.NODE_ENV = selectedinstance.node_env;
  2701. throw e
  2702. }
  2703. ) }
  2704. // , genericChessInstance(selected) { return __acquireConfig(selected) }
  2705. }
  2706. })()
  2707. var eNotImplemented = function(){
  2708. console.error('Not yet implemented')
  2709. process.exit()
  2710. }
  2711. // PB : TODO -- accept additional arg - an array specifying custom configPriority.
  2712. var acquireConfig = function(slections){
  2713. var configPriority = [ 'ownerClusterNodeConfig', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  2714. return any(configPriority.map(cfg => { return function() { return configs[cfg](slections) } } ), true, true).then(()=>{
  2715. return acquireData(slections)
  2716. })
  2717. }
  2718. var instanceData = (function(){
  2719. return {
  2720. ownerClusterNodeData(selected) {
  2721. var clusternodename = hostname || `CHESS0001${selected.username}`; // Cluster node names need to be unique accross all clusters to avoid collitions.
  2722. clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
  2723. return __acquireData(selected, { remote : 'userfork' }
  2724. , selected.instanceName + '-data-' + selected.node_env + `-${clusternodename}`
  2725. , function(e){ console.info('Customized node level data not found. This is not an Error. Will attempt with owner level config.');
  2726. return e; }
  2727. )
  2728. }
  2729. , ownerInstnace(selected) { return __acquireData(selected, { remote : 'userfork' }
  2730. , selected.instanceName + '-data-' + selected.node_env
  2731. , function(e){ console.info('Customized user level data not found. This is not an Error. Will attempt global common instance config.');
  2732. return e }
  2733. )
  2734. }
  2735. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  2736. , commonInstance(selected) { return __acquireData(selected, { defaultRepoOwner }
  2737. // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
  2738. ) }
  2739. , genericChessInstance(selected) { return __acquireData(selected) }
  2740. }
  2741. })()
  2742. var acquireData = function(slections){
  2743. var configPriority = [ 'ownerClusterNodeData', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  2744. return any(configPriority.map(cfg => { return function() { return instanceData[cfg](slections) } } ), true, true)
  2745. }
  2746. function reinit(){
  2747. sysAddPathVar('%AppData%\\npm')
  2748. resetgitconfig()
  2749. }
  2750. function init(){
  2751. sysAddPathVar('%AppData%\\npm')
  2752. resetgitconfig()
  2753. }
  2754. function resetgitconfig(){
  2755. // https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage
  2756. // Git Credential storage...
  2757. // git config --global credential.helper 'store --file ~/.gitcredentials'
  2758. // git credential-store --file ~/.gitcredentials store
  2759. // // notepad C:/Program Files/Git/etc/gitconfig
  2760. // git config --global --unset credential
  2761. // git config --edit --system
  2762. // git config --global credential.helper "store --file ~/gitcredentials"
  2763. // git credential fill
  2764. // git credential-store --file ~/git.store store
  2765. // Find system git config
  2766. // git config --global --edit
  2767. // git config --list --show-origin
  2768. // git config --list --show-origin --show-scope
  2769. // https://stackoverflow.com/questions/35942754/how-can-i-save-username-and-password-in-git
  2770. // Recipie
  2771. // git config --global --unset credentials.helper
  2772. // cd /path/to/my/repo
  2773. // git config --unset credential.helper
  2774. // git config credential.helper 'store --file ~/.git_repo_credentials'
  2775. // git config credential.*.username my_user_name
  2776. // git config credential.https://gitlab.com.username my_user_name
  2777. // git credential fill
  2778. // git config --global credential.modalprompt false // doesnst work.
  2779. // core askpass = ;;; https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows
  2780. var options = {
  2781. inherit: true, shell: true //, env: process.env
  2782. , cwd: instanceroot
  2783. , runas: processedArgs.runas
  2784. }
  2785. var task = ['git', ['config'], options]
  2786. var tasklist = [
  2787. // ['--global', '--unset credentials.helper']
  2788. // ['--unset', 'credentials.helper']
  2789. // ,
  2790. // ['credential.helper', `'store --file git_repo_credentials'`]
  2791. ['--global', 'credential.helper', "'store --file ~/.git_repo_credentials'"]
  2792. , ['--global', '--replace-all', 'user.name', 'pb']
  2793. , ['--global', '--replace-all', 'user.email', 'pradeep@bbh.org.in']
  2794. // , ['--list']
  2795. // , ['credential', 'fill']
  2796. ]
  2797. var onEachError = e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n')
  2798. var shellT = (args) => { return getgitbashtask(args, onEachError)
  2799. // .catch(e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n' + tasq.toString()) )
  2800. }
  2801. execserial(tasklist, task, shellT, onEachError )
  2802. }
  2803. var createTasq = (args, shellT, onEachError) => {
  2804. var tasq = shellT ? shellT(args) : (() => { return nodeShellExec.apply(null, args).catch( onEachError || function(e){ console.error(e) } ) })
  2805. tasq.toString = function(){ return JSON.stringify(args)}
  2806. return tasq;
  2807. }
  2808. var execserial = function(tasklist, task, shellT){
  2809. var exec = (taskArgs)=>{
  2810. var thistask = task.concat();
  2811. thistask[1] = thistask[1].concat()
  2812. thistask[1].push.apply(thistask[1], taskArgs)
  2813. return createTasq(thistask, shellT)
  2814. }
  2815. return any(tasklist.map(exec))
  2816. }
  2817. var execonce = function(taskArgs, task){ return any([task[1].push.apply(task[1], taskArgs)].map(createTasq)) }
  2818. var __acquireConfig = function (selected, options, configrepo, errHandler) {
  2819. configrepo = configrepo || selected.instanceName + '-config-' + selected.node_env;
  2820. var errorHandler = (e) => {
  2821. 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`))){
  2822. // console.error('Could not connect to repo server. Timed Out')
  2823. 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 => {
  2824. if(propValue === 'y') {
  2825. reconfirm = getReconfirmAll()
  2826. return startElxr()
  2827. }
  2828. else if(propValue === 'r'){
  2829. return acquireConfig(selected)
  2830. }
  2831. else process.exit()
  2832. })
  2833. }
  2834. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${selected.username || options.defaultRepoOwner}/${configrepo}.git/' not found`))){
  2835. var choices = {
  2836. t : `install a new temporary local instance with this name ( will not persist ).
  2837. Use your own username for additional options. You can request for a username at chess@bbh.org.in )`
  2838. , e : 'exit' }
  2839. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  2840. choices = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  2841. , {
  2842. i : 'create a new instance with this name => will fork the default config under your username'
  2843. , f : 'fork a new instance with this name for yourself for this node from another instance'
  2844. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  2845. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  2846. , p : 'create a custom config for yourself '
  2847. }, choices)
  2848. }
  2849. return cli.prompt( choices
  2850. , 'Config for instance not found. Would you like to ', 'e' ).then(propValue => {
  2851. if(propValue === 't') {
  2852. selectedinstance.local = true; return createInstance(selectedinstance)
  2853. }
  2854. if(propValue === 'i') return eNotImplemented()
  2855. if(propValue === 'f') return eNotImplemented()
  2856. if(propValue === 'o') return eNotImplemented()
  2857. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  2858. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  2859. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  2860. else process.exit()
  2861. })
  2862. }
  2863. console.warn(e)
  2864. throw e; //('Config acquisition failed.')
  2865. }
  2866. var successHandler = () => {
  2867. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  2868. utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  2869. , selectedinstance, require(manifestpath)( null, { utils, username : selectedinstance.username, instanceName : selectedinstance.instanceName
  2870. , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' }))
  2871. console.dir(selectedinstance.repos)
  2872. // Config from server always override merges into selection except for the current selection.
  2873. // PB : TODO -- utils.assign Array merges are non-distinct...
  2874. if(!selectedinstance.repos[0].repo) {
  2875. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  2876. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  2877. }
  2878. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  2879. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  2880. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  2881. }
  2882. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  2883. , selected, selectedinstance)
  2884. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  2885. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  2886. cacheWriteInstanceConfig(chessinstances)
  2887. ENV.NODE_ENV = selectedinstance.node_env;
  2888. }
  2889. return performPull( selected.reposindexed[configrepo] || { repo : configrepo }
  2890. , null, selected.username || options.defaultRepoOwner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  2891. .catch( (e)=>{
  2892. // if(e){
  2893. if(Promise.resolve(e) === e) return e;
  2894. // console.error(e)
  2895. e.benign = true;
  2896. throw e; // Not a hard error but we need this for bcontinueonfailure as we still want to stop on firstsuccess.
  2897. // }
  2898. })
  2899. }
  2900. var __acquireData = function (selected, options, datarepo, errHandler) {
  2901. datarepo = datarepo || selected.instanceName + '-data';
  2902. var errorHandler = (e) => {
  2903. 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`))){
  2904. // console.error('Could not connect to repo server. Timed Out')
  2905. 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 => {
  2906. if(propValue === 'y') {
  2907. reconfirm = getReconfirmAll()
  2908. return startElxr()
  2909. }
  2910. else if(propValue === 'r'){
  2911. return acquireConfig(selected)
  2912. }
  2913. else process.exit()
  2914. })
  2915. }
  2916. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${selected.username || options.defaultRepoOwner}/${datarepo}.git/' not found`))){
  2917. var choices = {
  2918. t : `install a temporary local data folder.
  2919. For more options. Request and use a personal username at chess@bbh.org.in )`
  2920. , e : 'exit' }
  2921. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  2922. choices = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  2923. , {
  2924. i : 'create a new instance with this name => will fork the default config under your username'
  2925. , f : 'fork a new instance with this name for yourself for this node from another instance'
  2926. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  2927. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  2928. , p : 'create a custom config for yourself '
  2929. }, choices)
  2930. }
  2931. return cli.prompt( choices
  2932. , 'Data repo for instance not found. Would you like to ', 'e' ).then(propValue => {
  2933. if(propValue === 't') {
  2934. selectedinstance.local = true; return createInstanceData(selectedinstance)
  2935. }
  2936. if(propValue === 'i') return eNotImplemented()
  2937. if(propValue === 'f') return eNotImplemented()
  2938. if(propValue === 'o') return eNotImplemented()
  2939. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  2940. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  2941. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  2942. else process.exit()
  2943. })
  2944. }
  2945. console.warn(e)
  2946. throw e; //('Config acquisition failed.')
  2947. }
  2948. var successHandler = () => {
  2949. }
  2950. return performPull( selected.reposindexed[datarepo] || { repo : datarepo }
  2951. , null, selected.username || options.defaultRepoOwner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  2952. .catch( (e)=>{
  2953. // if(e){
  2954. if(Promise.resolve(e) === e) return e;
  2955. // console.error(e)
  2956. e.benign = true;
  2957. throw e; // Not a hard error but we need this for bcontinueonfailure
  2958. // }
  2959. })
  2960. }
  2961. var launchpath = path.resolve(path.normalize(process.env.wd))
  2962. 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.
  2963. // The easisest would be to ask for a target directory and default to current dir....
  2964. // path.dirname(launchpath).split(path.sep).pop()
  2965. var parent = path.dirname(launchpath);
  2966. var pp = launchpath;
  2967. var instancediscoverytasks = [];
  2968. while(parent !== pp){
  2969. instancediscoverytasks.push(
  2970. ((pa)=>{
  2971. var p = pa;
  2972. return function(){
  2973. return hasElxr(p).then((value)=>{
  2974. if(value) return p
  2975. // PB : TODO -- Using throw like this is not friendly with any...
  2976. throw Object.assign( new Error('Benign Failure in Batch')
  2977. , { value : false, benign : true });
  2978. })
  2979. }
  2980. })(pp)
  2981. )
  2982. pp = parent;
  2983. parent = path.dirname(parent);
  2984. }
  2985. var instanceroot = null
  2986. var detectInstanceRoot = any(instancediscoverytasks, true, true).then( ir => {
  2987. if(ir.error) { instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ; }
  2988. else instanceroot = ir.pVal
  2989. return instanceroot
  2990. }).catch(()=>{
  2991. instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
  2992. })
  2993. // We first load the default and then override with a runconfig if it exists else we override with the interactive prompts.
  2994. // Then acquire and reload and replace this default.
  2995. var hasElxr = function(path, options, cb) {
  2996. // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
  2997. options = options || {};
  2998. var tasks = [
  2999. '/elxr' // Is there a subfolder named elxr
  3000. , '/elxr/.git' // which is self git repository
  3001. // , '/elxr/.elxr' // and has .elxr subfolder we now store this in the instanceroot.
  3002. , '/elxr/' + __ALIAS__STAMP__ // Which has our stamp.
  3003. ]
  3004. if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
  3005. var value = existsFolderSync(path + tpath);
  3006. return { value, done : acc && !value };
  3007. }).value }
  3008. if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
  3009. var value = existsFolderSync(path + tpath);
  3010. return { value, done : acc && !value };
  3011. }).value );
  3012. return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
  3013. var value = existsFolderSync(path + tpath);
  3014. return { value, done : acc && !value };
  3015. }).value);
  3016. }
  3017. var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); }
  3018. var detectfromroot = function(root){
  3019. return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(root) ) }
  3020. }
  3021. var detectLocalInstances = function () {
  3022. console.log(`launchpath = ${launchpath}`)
  3023. console.log(`thisscriptdir = ${thisscriptdir}`)
  3024. // PB : TODO -- !Postpone this.
  3025. console.log(`instanceroot = ${instanceroot}`) // Not yet confirmed...
  3026. // Note : Paths should already be normalized fefore this.
  3027. var root = instanceroot;
  3028. var detected = { root };
  3029. var instanceoptions = [clioverrides]
  3030. return hasElxr(launchpath).then( (elxrCliExists) => {
  3031. // We need a reference to the root director for elxr cli to be properly oriented.
  3032. if (( elxrCliExists && path.normalize(launchpath + '/elxr')) === thisscriptdir) {
  3033. // We were run from the proper root with elxr cli in the subfolder.
  3034. instanceroot = root = launchpath;
  3035. instanceoptions.splice( 0, 0, detected = { root })
  3036. instanceoptions.splice( 0, 0, detectfromroot(root))
  3037. }
  3038. else {
  3039. if(path.normalize(launchpath + '/elxr') === thisscriptdir) {
  3040. // elxrCliExists is false -- and yet thiscriptdir is still proper.
  3041. // PB : TODO -- Maybe a warning / abort if for some reason this scriptdir should not be taken over...
  3042. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.')
  3043. instanceroot = root = launchpath;
  3044. instanceoptions.splice( 0, 0, detected = { root })
  3045. instanceoptions.splice( 0, 0, detectfromroot(root))
  3046. }
  3047. else if (launchpath === thisscriptdir) {
  3048. var parentHasElxr = hasElxrSync(launchpath + '/..')
  3049. // PB : TODO -- verify if we have .elxr folder in the parent...
  3050. if(!parentHasElxr) {
  3051. // ! thisscriptdir is not elxr.
  3052. console.error('Invalid run location in subfolder that looks like elxr. We should probably abort as elxr will not sync.')
  3053. }
  3054. // Same directory doesn't mean we are being run from elxr sub directory.
  3055. // In standalone build script we may or not be in the same location.
  3056. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  3057. // Unbuilt therefore we are in the elxr sub directory.
  3058. instanceroot = root = path.normalize(launchpath + '/..');
  3059. instanceoptions.splice( 0, 0, detected = { root });
  3060. instanceoptions.splice( 0, 0, detectfromroot(root));
  3061. }
  3062. else {
  3063. // Built version.
  3064. // We could have been run from the elxr subfolder. Highly likely that the built version isn't the full elxr.
  3065. if(parentHasElxr) {
  3066. // Built version was run from the full elxr subfolder. Should work
  3067. // PB : TODO -- but we should switch to the full version...
  3068. instanceroot = root = path.normalize(launchpath + '/..');
  3069. instanceoptions.splice( 0, 0, detected = { root })
  3070. instanceoptions.splice( 0, 0, detectfromroot(root))
  3071. }
  3072. else {
  3073. instanceroot = root = launchpath;
  3074. instanceoptions.splice( 0, 0, detected = { root })
  3075. instanceoptions.splice( 0, 0, detectfromroot(root))
  3076. // Assume current launchpath is a new instance and create.
  3077. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  3078. // if(clioverrides.instanceName) {
  3079. // if(clioverrides.node_env) {
  3080. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  3081. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  3082. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  3083. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  3084. // // eg : floder name can be elixir01 but instance name is elixr
  3085. // }
  3086. // else {
  3087. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + 'development')
  3088. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  3089. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  3090. // }
  3091. // }
  3092. // else {
  3093. // instanceroot = root = launchpath;
  3094. // if(clioverrides.node_env) {
  3095. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  3096. // instanceoptions.splice( 0, 0, detectfromroot(root))
  3097. // }
  3098. // else {
  3099. // // Nothing was specified... We only have one option from root.
  3100. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  3101. // }
  3102. // }
  3103. }
  3104. }
  3105. }
  3106. else {
  3107. if(elxrCliExists) {
  3108. instanceroot = root = launchpath;
  3109. instanceoptions.splice( 0, 0, detected = { root })
  3110. instanceoptions.splice( 0, 0, detectfromroot(root))
  3111. }
  3112. }
  3113. }
  3114. instanceroot = detected.root
  3115. __default.root = root;
  3116. clioverrides.root = clioverrides.root || root;
  3117. // Resolves empty array when No known instances detected.
  3118. return Promise.resolve(instanceoptions)
  3119. })
  3120. }
  3121. var getReconfirmAll = ()=>{return { instanceName : true, instanceType : true, reposerver : true, username : true, password : true } }
  3122. if(clioverrides.reconfirm) {
  3123. var reconfirm = getReconfirmAll()
  3124. }
  3125. else { var reconfirm = {}; }
  3126. var shouldPrompt = function(k, possiblePrompts, target){
  3127. return ((possiblePrompts[k] !== undefined && possiblePrompts[k] !== null) && target[k] !== possiblePrompts[k]
  3128. || (possiblePrompts[k] === undefined || possiblePrompts[k] === null) && (target[k] === undefined || target[k] === null)
  3129. || reconfirm[k])
  3130. }
  3131. var getBoundEachPrompt = function(target, possiblePrompts, promptables, choices, promptsfilter) {
  3132. return function(prompts, k, i, a){
  3133. // Reducer for all prompts on targets.
  3134. // No local instances config found. We use a default initialized instance available in selectedinstance
  3135. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  3136. // PB : TODO -- selectedinstance === __default check to prompt everything...
  3137. if( shouldPrompt(k, possiblePrompts, target) ) {
  3138. delete reconfirm[k];
  3139. // console.log(k)
  3140. // console.dir(possiblePrompts); //console.dir(target)
  3141. prompts.push(async ()=>{
  3142. // PB : NOTE -- Important in async cases when this {{target}} needs to be in the same state as when it was invoked.
  3143. // We need to take a snapshot... Shallow.. !! If required deep should be used based on use case.
  3144. // var asyncthis = Object.assign(this);
  3145. // By default Latest altered state is provided which is an implicit reference directly.
  3146. promptables[k].choices = choices[k]
  3147. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  3148. return await target[k]
  3149. })
  3150. }
  3151. delete possiblePrompts[k] // PB : TODO We should keep this around instead of deleting so we can do a second pass if required.
  3152. return prompts
  3153. }
  3154. }
  3155. var __interactive_prompts = function( target, choices, promptsfilter ){
  3156. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  3157. var interactionpoints = {
  3158. runchoice : {
  3159. label :
  3160. `Choose an option :
  3161. d) Install the default chess instance.
  3162. => elxr i chess node_env=development --default
  3163. n) Create your custom new instance interactively
  3164. => elxr i {{instanceName}} node_env={{environment}}
  3165. i) Choose an instance and environment to install
  3166. => elxr i {{instanceName}} node_env={{environment}}
  3167. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  3168. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  3169. h) Help
  3170. q) Quit
  3171. : `
  3172. , choices : []
  3173. , defaultchoice : 'c'
  3174. , selectedchoice : target.runchoice
  3175. , interpret : function(choice){
  3176. var interpret_map = {
  3177. d : function(){
  3178. processedArgs._[0] = 'i'
  3179. target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  3180. target.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  3181. target.reposerver = 'https://git.bbh.org.in'
  3182. }
  3183. , n : function() { processedArgs._[0] = 'i' }
  3184. , i : function() {
  3185. processedArgs._[0] = 'i'
  3186. // processedArgs._[1] = target.instanceName || processedArgs._[1] || 'chess';
  3187. }
  3188. , c : async function() {
  3189. // this here will always be the target.
  3190. Object.defineProperty(this, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  3191. label : `Enter cmd :
  3192. p) pull
  3193. Default <= p
  3194. : `
  3195. , defaultchoice : 'pull'
  3196. }
  3197. ));
  3198. var cmd = await target['cmd'];
  3199. if (!cmd || cmd === 'p') { target['cmd'] = processedArgs._[0] = 'pull' }
  3200. else target['cmd'] = processedArgs._[0] = cmd
  3201. return cmd;
  3202. }
  3203. , h : function() { console.log(elxr.help()); process.exit() } // PB : TODO -- Why do we need log.
  3204. , q : function() { process.exit() }
  3205. }
  3206. if(Promise.resolve(choice) === choice){
  3207. return choice.then( resolvedchoice => {
  3208. return (interpret_map[choice] || interpret_map['c']).call(target)
  3209. })
  3210. }
  3211. else return Promise.resolve( (interpret_map[choice] || interpret_map['c']).call(target) )
  3212. // var __interpreter = interpret_map[choice] || interpret_map['c']
  3213. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  3214. // if(interpret_map[choice]) __interpreter = interpret_map[choice];
  3215. // return __interpreter.call(target)
  3216. }
  3217. }
  3218. , instanceName : { label : `Enter Instance Name ( <= ${target.instanceName || 'chess'} ) : `
  3219. , choices : choices['instanceName'], defaultchoice : 'chess'
  3220. , selectedchoice : target.instanceName
  3221. }
  3222. , instanceType : { label : `Enter Instance Type ( <= ${target.instanceType || 'development'} ) : `
  3223. , choices : choices['instanceType'], defaultchoice : 'development'
  3224. , selectedchoice : target.instanceType || 'development'
  3225. }
  3226. , reposerver : { label : `Enter Repo Server Base Url ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `
  3227. , get choices() {
  3228. choices['reposerver'].forEach( rs => {
  3229. var __rs = new URL(rs);
  3230. __rs.hostname = __rs.host;
  3231. __rs.path = '/'
  3232. __rs.method = 'GET'
  3233. RESTAPI.get(__rs, function(data){ rs.accessibility = 'unaccessible' }
  3234. , function(error){ rs.accessibility = 'unaccessible' } )
  3235. })
  3236. return choices['reposerver']
  3237. }
  3238. , defaultchoice : 'https://git.bbh.org.in'
  3239. , selectedchoice : target.reposerver
  3240. }
  3241. , 'upstream-remote' : { label : `Enter Remote Name ( <= ${target['upstream-remote'] || 'chess'} ) : `
  3242. , get choices() {
  3243. var reposerver = target['reposerver']
  3244. var remotes = []
  3245. var trs = target.reposervers || []
  3246. trs.forEach(rs => {
  3247. if(rs.server === reposerver){
  3248. remotes.push(remote)
  3249. // PB : TODO -- Sort and display highest priority target.remotes.sort( )
  3250. }
  3251. })
  3252. return remotes
  3253. }
  3254. , defaultchoice : 'userfork'
  3255. , selectedchoice : target['upstream-remote'] || 'userfork'
  3256. // Just using getters resolves dependencies..., dependencies : [ ()=>{ return target['reposerver'] } ]
  3257. }
  3258. , 'remote-type' : { label : `Enter Remote Type ( <= ${target['remote-type'] || 'public'} ) : `
  3259. , get choices() {
  3260. return ['public', 'private', 'github', 'unc']
  3261. }
  3262. , defaultchoice : 'public'
  3263. , selectedchoice : target['remote-type'] || 'public'
  3264. // Just using getters resolves dependencies..., dependencies : [ ()=>{ return target['reposerver'] } ]
  3265. }
  3266. , 'selectedremotes' : { label : `Chose Remote Names ( <= ${target['selectedremotes'] || 'chess'} ) : `
  3267. , get choices() {
  3268. var reposerver = target['reposerver'] // PB : TODO -- We need options to work with multiple selected reposervers at the same time..
  3269. var remotenames = []
  3270. Object.entries(target.remotes || []).forEach( ([rname, r]) => {
  3271. if(r.server === reposerver && r.accessibility.find( target[ 'remote-type' ] )){
  3272. remotes.push(rname)
  3273. // PB : TODO -- Sort and display highest priority target.remotes.sort( )
  3274. }
  3275. })
  3276. // PB : TODO -- Need to generate all possible permuted choices nP( 1 -> n )
  3277. // Currenty handles all combinations without any priority order.
  3278. var _remotechoices = [] // Array of arrays of choices.
  3279. remotenames.forEach( r => {
  3280. var __rcs = []
  3281. _remotechoices.forEach(rc => {
  3282. __rcs.push( rc.concat(r) )
  3283. })
  3284. Array.prototype.push.apply( _remotechoices, __rcs)
  3285. _remotechoices.push(r)
  3286. })
  3287. return _remotechoices
  3288. }
  3289. , defaultchoice : ['userfork-public', 'chess-public']
  3290. , selectedchoice : target['selectedremotes'] || ['userfork-public', 'chess-public']
  3291. // , defaultchoice : { 'userfork-public' : target.remotes['userfork-public'] , 'chess-public' : target.remotes['chess-public'] }
  3292. // , selectedchoice : target['selectedremotes'] || { 'userfork-public' : target.remotes['userfork-public'] , 'chess-public' : target.remotes['chess-public'] }
  3293. // Info : Just using getters resolves dependencies..., dependencies : [ ()=>{ return target['reposerver'] } ]
  3294. }
  3295. , get username() { return { label : `Enter User Id for ${target.reposerver} ( <= ${target.username || 'chess'} ) : `
  3296. , choices : choices['username'], defaultchoice : 'chess', selectedchoice : target.username } }
  3297. , get password() { return { label : `Enter Password for ${target.username} @ ${target.reposerver} ( <= ${target.password || ''} ) : `
  3298. , choices : choices['password'], defaultchoice : '***', selectedchoice : target.password } }
  3299. , get email() { return { label : `Enter Email for ${target.username} @ ${target.reposerver} ( <= ${target.email || ''} ) : `
  3300. , choices : choices['email'], defaultchoice : 'guest@bbh.org.in', selectedchoice : target.email } }
  3301. }
  3302. function getPromptKeys() {
  3303. if(! (processedArgs.label || processedArgs._[0]) ) return Object.assign({}, interactionpoints);
  3304. return promptkeys
  3305. }
  3306. var eachPrompt = getBoundEachPrompt( target, getPromptKeys() , interactionpoints, choices, promptsfilter)
  3307. return Object.keys(promptsfilter || interactionpoints).reduce(eachPrompt, [])
  3308. }
  3309. var downloadsdir = '../Downloads';
  3310. var prerequisites = [
  3311. {
  3312. shellcmd: 'git',
  3313. name : 'git',
  3314. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  3315. , installer: 'Git-2.31.0-64-bit.exe'
  3316. , installcmd: ['cmd', ['/c', 'start',
  3317. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  3318. , '/VERYSILENT'
  3319. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  3320. ]]
  3321. , preinstallsteps: function() {
  3322. var steps = [
  3323. () => {
  3324. if (!existsSync(downloadsdir + '/' + this.installer)) {
  3325. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  3326. }
  3327. else return Promise.resolve(true)
  3328. }
  3329. ]
  3330. var prompts = this.getuser(null, ()=>{
  3331. // console.log('preinstallsteps')
  3332. // var gitUser = 'guest';
  3333. // var gitEmail = 'guest@bbh.org.in';
  3334. // var prompts = [];
  3335. // prompts.push( ()=>{ return cli.prompt(choices['username'], 'git user name').then(gituser => gitUser = gituser) } )
  3336. // prompts.push( ()=>{ return cli.prompt(choices['useremail'], 'git user email').then(gitemail => gitEmail = gitemail) } )
  3337. // console.log('prompting in preinstallsteps')
  3338. // return any(prompts).then(()=>{
  3339. // var steps = [
  3340. // ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  3341. // , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  3342. // ]
  3343. // return any(steps.map(getshelltask)).then(() => {
  3344. // })
  3345. // });
  3346. return Promise.resolve(true)
  3347. })
  3348. return any([any(steps), prompts])
  3349. }
  3350. , installsteps: function () {
  3351. return any([this.installcmd].map(getshelltask))
  3352. }
  3353. , postinstallsteps: function(err, users){
  3354. return this.getuser(null, (err, data)=>{
  3355. // ignore err and proceed with data as guest.
  3356. console.dir(data)
  3357. if(data && data.length === 1 && !shouldPrompt('username', promptkeys, selectedinstance) ) {
  3358. return username = data[0];
  3359. }
  3360. data = data || ['guest']
  3361. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  3362. console.log('prompting in postinstallsteps')
  3363. var username = 'guest';
  3364. var email = 'guest@bbh.org.in';
  3365. var password = '***';
  3366. return any( getInteractionPoints(selectedinstance, promptkeys, { username, password, email}) ).then(()=>{
  3367. if(!data.find(e => e === selectedinstance.username)) {
  3368. var steps = [
  3369. ['git', ['config', '--global', '--add', 'user.name', `${username}`]]
  3370. , ['git', ['config', '--global', '--add', 'user.email', `${email}`]]
  3371. ]
  3372. return any(steps.map(getshelltask)).then(() => {
  3373. })
  3374. }
  3375. else {
  3376. return Promise.resolve(true)
  3377. }
  3378. });
  3379. })
  3380. }
  3381. , install: function () {
  3382. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  3383. }
  3384. , verifyAndInstall : function(){
  3385. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  3386. if(exists) {
  3387. // return any(['git', ['config', '--global', '-l']].map(getshelltask))
  3388. return this.postinstallsteps.bind(this)()
  3389. }
  3390. return this.install();
  3391. });
  3392. }
  3393. , getuser : function(repo, onResult){
  3394. var __onResult = onResult || function(e, data){
  3395. data = data || []
  3396. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  3397. // console.dir(choices)
  3398. return data[0]
  3399. }
  3400. var globalOrLocal = '--global';
  3401. if(repo) globalOrLocal = '--local'
  3402. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(getshelltask)).then((result)=>{
  3403. // not yet configured.
  3404. if(!result.success) return __onResult(result)
  3405. else {
  3406. var users = result.messages[0].trim().split('\n');
  3407. if(users.length === 0 ||
  3408. users.length === 1 && users[0] === 'guest') {
  3409. return __onResult(result)
  3410. }
  3411. else {
  3412. return __onResult(null, Array.from( new Set( users ) ) ); }// PB : TODO == We should probably prompt with all the users available for selection !
  3413. }
  3414. })
  3415. .catch((e)=>{
  3416. console.log(e)
  3417. return __onResult(e)
  3418. })
  3419. }
  3420. }
  3421. ,
  3422. {
  3423. shellcmd: 'node',
  3424. name : 'node',
  3425. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  3426. , installer: 'node-v14.16.0-x64.msi'
  3427. , installcmd: ['MSIEXEC.exe', ['/i'
  3428. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  3429. , 'ACCEPT=YES', '/passive']]
  3430. , install : function() { return any([this.installcmd].map(getshelltask)).then(() => { }) }
  3431. }
  3432. ]
  3433. for(var i=0; i<prerequisites.length; i++) {
  3434. prerequisites[prerequisites[i].name] = prerequisites[i];
  3435. }
  3436. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  3437. function ensureDirectoryExistence(filePath) {
  3438. var dirname = path.dirname(filePath);
  3439. if (fs.existsSync(dirname)) {
  3440. return filePath;
  3441. }
  3442. ensureDirectoryExistence(dirname);
  3443. fs.mkdirSync(dirname);
  3444. return filePath;
  3445. }
  3446. var mainTasks = [];
  3447. function verifyAndInstallPrerequisites() {
  3448. var downloadtasks = [];
  3449. var installtasks = [];
  3450. prerequisites.forEach(preq => {
  3451. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  3452. if (exists) console.log(`${preq.shellcmd} exists`)
  3453. else {
  3454. console.log(`${preq.shellcmd} is not installed`)
  3455. return preq.preinstallsteps.call(preq).then(() => {
  3456. installtasks.push(preq.install.bind(preq))
  3457. })
  3458. }
  3459. }))
  3460. })
  3461. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  3462. }
  3463. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  3464. return {
  3465. get (){
  3466. return any( promptable.dependencies || [] ).then(()=>{
  3467. return cli.prompt( promptable.choices, promptable.label, promptable.defaultchoice, promptable.selectedchoice ).then(propValue => {
  3468. var asyncprop = Promise.resolve(propValue)
  3469. if(promptable.interpret){
  3470. asyncprop = promptable.interpret(propValue)
  3471. }
  3472. return asyncprop.then(
  3473. ()=>{
  3474. Object.defineProperty(this, propName, {
  3475. value: propValue,
  3476. writable: true,
  3477. configurable : true,
  3478. enumerable : true
  3479. });
  3480. return propValue
  3481. }
  3482. )
  3483. })
  3484. } )
  3485. }
  3486. // , set (propValue){
  3487. // Object.defineProperty(this, propName, {
  3488. // value: propValue,
  3489. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  3490. // configurable : true,
  3491. // enumerable : true
  3492. // })
  3493. // return propValue;
  3494. // }
  3495. , configurable : true
  3496. , enumerable : true
  3497. }
  3498. }
  3499. function acquirelocalinstances(selected){
  3500. // utils.assign is used to cleanup duplicates... assuming chessinstances.js is probably not clean.
  3501. var chessinstances = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  3502. , require(path.normalize(selected.root + '/chessinstances.js')));
  3503. return chessinstances
  3504. }
  3505. function findlocalinstances(chessinstances, instanceoptions){
  3506. // We can expect a .elxr at each level.
  3507. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../..' /* instanceNames */].
  3508. earlyreduce( ( value, p, i, a )=>{
  3509. var localinstancesPath = `${instanceroot}/${p}.elxr`;
  3510. if(existsSync( localinstancesPath )) {
  3511. try {
  3512. var chessinstances = acquirelocalinstances( { localinstancesPath } )
  3513. return Object.keys(chessinstances).earlyreduce( ( value, instanceName) => {
  3514. return Object.keys(chessinstances[instanceName]).earlyreduce( (value, instanceType) => {
  3515. if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize( instanceroot) ) {
  3516. instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType])
  3517. return {
  3518. value : chessinstances[instanceName][instanceType]
  3519. , done : true
  3520. };
  3521. }
  3522. })
  3523. })
  3524. }
  3525. catch(e){
  3526. return { }
  3527. }
  3528. }
  3529. else return { }
  3530. }
  3531. )
  3532. }
  3533. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  3534. var selectedinstance = { root : process.env.wd };
  3535. var runconfig = null;
  3536. var chessinstances = { current_run : {} };
  3537. var promptkeys = {
  3538. cmd : processedArgs._[0] || 'pull'
  3539. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  3540. // 'instanceName' : true
  3541. // , 'node_env' : true
  3542. // , username : ''
  3543. // , runchoice : 'c'
  3544. }
  3545. // promptkeys.runchoice = promptkeys.cmd ? 'c' : undefined
  3546. function createLocalChessInstance( cfg ){
  3547. // return createInstance(cfg)
  3548. reconfirm = getReconfirmAll()
  3549. var inst = {};
  3550. var __new = Object.assign({}, __default, cfg)
  3551. inst[cfg.node_env] = __new; return inst;
  3552. }
  3553. var choices = {
  3554. 'instanceName' : []
  3555. , 'reposerver' : []
  3556. , 'upstream-remote' : []
  3557. , 'instanceType' : []
  3558. , username : ['guest', 'chessdemo', 'demo']
  3559. }
  3560. var getInteractionPoints = function(detectedinstanceoptions, possiblePrompts, promptsfilter){
  3561. var instances = []
  3562. var reposervers = [];
  3563. var remotes = [];
  3564. var instanceNames = []
  3565. var instanceTypes = ['development', 'production'];
  3566. Object.keys( chessinstances).forEach(instanceName => {
  3567. if(instanceName === 'current_run') return;
  3568. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  3569. var instance = chessinstances[instanceName][node_env];
  3570. reposervers = reposervers.concat(instance.reposervers)
  3571. if(instance.reposerver) reposervers.push(instance.reposerver)
  3572. instances.push(instance)
  3573. instanceTypes.push(instance.node_env)
  3574. instanceNames.push(instance.instanceName)
  3575. Array.prototype.push.apply(remotes, Object.keys(instance.reposerverinstances[instance.reposerver].remotes))
  3576. })
  3577. })
  3578. instances = instances.concat(detectedinstanceoptions)
  3579. if(selectedinstance['instanceName']) instanceNames.push(selectedinstance['instanceName'])
  3580. if(possiblePrompts['instanceName']) instanceNames.push(possiblePrompts['instanceName'])
  3581. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers'])
  3582. choices['instanceName'] = Array.from( new Set(instanceNames.concat(choices['instanceName'])) )
  3583. choices['reposerver'] = Array.from( new Set(reposervers.concat(choices['reposerver'])) )
  3584. // choices['upstream-remote'] = Array.from( new Set(remotes.concat(choices['upstream-remote'])) )
  3585. choices['instanceType'] = Array.from( new Set(instanceTypes.concat(choices['instanceType'])) )
  3586. return __interactive_prompts(selectedinstance, choices, promptsfilter)
  3587. }
  3588. var detection_state = {
  3589. localInstanceDetected : false
  3590. }
  3591. const https = require('https')
  3592. const http = require('http');
  3593. const { resolve } = require('path');
  3594. const { Console } = require('console');
  3595. const RESTAPI = (function(){
  3596. // Singleton
  3597. function RESTAPI(){}
  3598. // RESTAPI.create = RESTAPI; // Returns the one singe instance which is the class itself
  3599. // const options = {
  3600. // hostname: 'whatever.com',
  3601. // port: 443,
  3602. // path: '/todos',
  3603. // method: 'POST',
  3604. // headers: {
  3605. // 'Content-Type': 'application/json',
  3606. // 'Content-Length': data.length
  3607. // }
  3608. // }
  3609. RESTAPI.method = function(options, resolve, reject){
  3610. var __method = function() {
  3611. options.headers = options.headers || { 'Content-Type': 'application/json' }
  3612. if(options.payload) {
  3613. const data = new TextEncoder().encode( JSON.stringify(options.payload) )
  3614. options.headers = options.headers || {
  3615. 'Content-Type': 'application/json',
  3616. 'Content-Length': data.length
  3617. }
  3618. }
  3619. if(!options.authenticatepost) options.headers.Authorization = `token ${usertokens[options.username]}`
  3620. var acquirer = getHTTPorS(options)
  3621. const req = acquirer.request(options, res => {
  3622. if (res.statusCode < 200 || res.statusCode >= 300) {
  3623. return reject(new Error('statusCode=' + res.statusCode));
  3624. }
  3625. var body = [];
  3626. // res.setEncoding('utf8');
  3627. res.on('data', function(chunk) {
  3628. body.push(chunk);
  3629. });
  3630. res.on('end', function() {
  3631. try {
  3632. body = JSON.parse(Buffer.concat(body).toString());
  3633. } catch(e) {
  3634. reject(e);
  3635. }
  3636. resolve(body);
  3637. });
  3638. });
  3639. req.on('error', error => {
  3640. console.error(error)
  3641. reject(error)
  3642. })
  3643. if(options.payload) req.write(data)
  3644. req.end()
  3645. }
  3646. if(!options.authenticatepost && !usertokens[options.username]) {
  3647. RESTAPI.authenticate(options, function(tokenresp){
  3648. usertokens[options.username] = tokenresp.sha1
  3649. __method(options, resolve, reject)
  3650. },
  3651. function(err){ throw err}
  3652. )
  3653. }
  3654. else __method(options, resolve, reject)
  3655. }
  3656. RESTAPI.post = RESTAPI.method
  3657. var usertokens = {}
  3658. RESTAPI.authenticate = function(options, resolve, reject){
  3659. options.headers = options.headers || { 'Content-Type': 'application/json' }
  3660. if(!usertokens[options.username]) {
  3661. // Authenticate and acquire token.
  3662. // https://git.bbh/api/v1/users/<username>/tokens
  3663. // curl -XPOST -H "Content-Type: application/json" -k -d '{"name":"demo"}' -u demo:demo123 http://git.bbh/api/v1/users/demo/tokens
  3664. var _options = Object.assign({}, options)
  3665. // _options.username = 'demo'
  3666. // _options.password = 'demo123'
  3667. _options.method = 'POST'
  3668. _options.headers.Authorization = `Basic ${Buffer.from(`${_options.username}:${_options.password}`).toString('base64')}`
  3669. _options.path = `/api/v1/users/${_options.username}/tokens`
  3670. _options.authenticatepost = true
  3671. var postoptions = { name : _options.username }
  3672. delete _options.username
  3673. delete _options.password
  3674. _options.payload = postoptions
  3675. RESTAPI.post( _options, function(tokenresp){
  3676. // tokenresp = JSON.parse(tokenresp)
  3677. usertokens[options.username] = tokenresp.sha1
  3678. resolve(tokenresp)
  3679. },
  3680. function(err){ reject(err) }
  3681. )
  3682. }
  3683. else resolve(tokenresp.sha1)
  3684. }
  3685. RESTAPI.get = RESTAPI.post = RESTAPI.method
  3686. return RESTAPI
  3687. })();
  3688. var getHTTPorS = function(options){ return options.protocol.startsWith('https') ? https : http; }
  3689. const GITEA = (function(){
  3690. function GITEA(){}
  3691. GITEA.repository = {
  3692. fork( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  3693. // forkoptions = { owner : httpoptions.username, repo : {{reoptoFork}} }
  3694. // giteaoptions = {
  3695. // organization string
  3696. // --- organization name, if forking into an organization
  3697. // }
  3698. // http://try.gitea.io/api/v1/repos/{owner}/{repo}/forks
  3699. httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}/forks`
  3700. httpoptions.method = 'POST'
  3701. httpoptions.payload = giteaoptions;
  3702. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  3703. }
  3704. , updateattributes( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  3705. httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}`
  3706. httpoptions.method = 'PATCH'
  3707. httpoptions.payload = giteaoptions;
  3708. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  3709. }
  3710. }
  3711. GITEA.user = {
  3712. getuser( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  3713. // ​/users​/{username} // Get a user
  3714. httpoptions.path = `/api/v1/users/${httpoptions.username}`
  3715. httpoptions.method = 'GET'
  3716. return RESTAPI.get(httpoptions, giteaoptions, resolve || function(){}, reject || function(){} )
  3717. }
  3718. }
  3719. return GITEA
  3720. })();
  3721. // Wrapper for Git shell operations. Some meta operations will map to a bunch of GIT commands.
  3722. const GIT = (function(){
  3723. function GIT(){}
  3724. Object.assign(GIT, {
  3725. 'switch user'(username){
  3726. var server = new URL(selectedinstance.reposerver);
  3727. return GITEA.user.getuser({ hostname : server.host, protocol : server.protocol
  3728. , username : selectedinstance.username, password : selectedinstance.password
  3729. }).then(()=>{
  3730. return nodeShellExec('git', ['config', '--replace-all', 'user.name', username],
  3731. {
  3732. inherit: true, shell: true,
  3733. env: process.env
  3734. , cwd: instanceroot + '/' + repo
  3735. , runas: processedArgs.runas
  3736. , title: `'git', ${['config', '--replace-all', 'user.name', username].join(' ')}`
  3737. })
  3738. }
  3739. )
  3740. .catch(e => {
  3741. console.error(e + 'Could not switch. Probably no such user.')
  3742. })
  3743. }
  3744. })
  3745. return GIT
  3746. })();
  3747. function createInstanceData(target, source) {
  3748. var sourceinstance = source || target;
  3749. console.dir(sourceinstance)
  3750. var args = {
  3751. remotebase : sourceinstance.reposerver + '/chess/'
  3752. , sourcerepo : sourceinstance.repo || 'chess-data'
  3753. , targetrepo : `${target.instanceName}-data-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  3754. }
  3755. if(sourceinstance.local) {
  3756. var options = {
  3757. inherit: true, shell: true,
  3758. env: process.env
  3759. , cwd : instanceroot
  3760. , runas: processedArgs.runas
  3761. }
  3762. var cmdseq = [
  3763. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  3764. ]
  3765. return any(cmdseq.map(getshelltask)).then(() => { return true })
  3766. }
  3767. else {
  3768. // http://try.gitea.io/api/v1/org/{org}/repos
  3769. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  3770. throw 'createInstanceData is possible only within the same repository server.'
  3771. }
  3772. var server = new URL(target.reposerver);
  3773. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  3774. , username : target.username, password : target.password
  3775. }
  3776. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  3777. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  3778. return GITEA.repository.updateattributes( {
  3779. hostname : server.host, protocol : server.protocol
  3780. , username : target.username, password : target.password
  3781. }
  3782. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  3783. , { name : `${args.targetrepo}`}
  3784. )
  3785. }
  3786. )
  3787. }
  3788. // GITEA.repository.updateattributes( {
  3789. // hostname : server.host, protocol : server.protocol
  3790. // , username : selectedinstance.username, password : selectedinstance.password
  3791. // }
  3792. // , { repo : `chess-config`, owner : selectedinstance.username }
  3793. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  3794. // )
  3795. // return selectedinstance
  3796. }
  3797. function createInstance(target, source) {
  3798. var sourceinstance = source || target;
  3799. console.dir(sourceinstance)
  3800. var args = {
  3801. remotebase : sourceinstance.reposerver + '/chess/'
  3802. , sourcerepo : sourceinstance.repo || 'chess-config'
  3803. , targetrepo : `${target.instanceName}-config-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  3804. }
  3805. if(sourceinstance.local) {
  3806. var options = {
  3807. inherit: true, shell: true,
  3808. env: process.env
  3809. , cwd : instanceroot
  3810. , runas: processedArgs.runas
  3811. }
  3812. var cmdseq = [
  3813. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  3814. ]
  3815. return any(cmdseq.map(getshelltask)).then(() => { return true })
  3816. }
  3817. else {
  3818. // http://try.gitea.io/api/v1/org/{org}/repos
  3819. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  3820. throw 'createInstance is possible only within the same repository server.'
  3821. }
  3822. var server = new URL(target.reposerver);
  3823. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  3824. , username : target.username, password : target.password
  3825. }
  3826. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  3827. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  3828. return GITEA.repository.updateattributes( {
  3829. hostname : server.host, protocol : server.protocol
  3830. , username : target.username, password : target.password
  3831. }
  3832. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  3833. , { name : `${args.targetrepo}`}
  3834. )
  3835. }
  3836. )
  3837. }
  3838. // GITEA.repository.updateattributes( {
  3839. // hostname : server.host, protocol : server.protocol
  3840. // , username : selectedinstance.username, password : selectedinstance.password
  3841. // }
  3842. // , { repo : `chess-config`, owner : selectedinstance.username }
  3843. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  3844. // )
  3845. // return selectedinstance
  3846. }
  3847. var skipprerequisites = false;
  3848. function initinstances(selected_overrides) {
  3849. var root = selected_overrides.root // We should always have this coz we are running at some place which is fixed by detectLocalInstances.
  3850. var instanceName = selected_overrides.instanceName
  3851. || clioverrides.instanceName
  3852. // || processedArgs._[1]
  3853. || chessinstances.current_run.instanceName
  3854. var node_env = selected_overrides.node_env
  3855. || clioverrides.node_env
  3856. // || processedArgs.node_env
  3857. || chessinstances.current_run.node_env
  3858. var reposerver = selected_overrides.reposerver
  3859. || clioverrides.reposerver
  3860. // || processedArgs.node_env
  3861. || chessinstances.current_run.reposerver
  3862. if(!instanceName) {
  3863. promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  3864. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  3865. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  3866. }
  3867. if(!node_env) {
  3868. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  3869. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  3870. }
  3871. if(!reposerver) {
  3872. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  3873. }
  3874. chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
  3875. instanceName, node_env, root : selected_overrides.root, reposerver : selected_overrides.reposerver /* promptkeys['reposerver'] */ } );
  3876. chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root }
  3877. if(path.normalize(selected_overrides.root) !== path.normalize(chessinstances[instanceName][node_env].root)) {
  3878. 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
  3879. }
  3880. // Override sequence.
  3881. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  3882. // PB : TODO -- Undefined keys are overriding and deleting values. We should not allow that.
  3883. // This is ordinary utils.assign behavior. The key should not exist as undefined in the override.
  3884. // PB : TODO -- We now have options that can be passed into assign_core to control this behavior.
  3885. if(selected_overrides.node_env === undefined) delete selected_overrides.node_env
  3886. selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  3887. , __default
  3888. , chessinstances[instanceName][node_env]
  3889. , clioverrides
  3890. , selected_overrides
  3891. // , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
  3892. );
  3893. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  3894. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  3895. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  3896. // // Brand New.
  3897. // selectedinstance = Object.assign( __default, selectedinstance )
  3898. // }
  3899. if(selectedinstance?.repos && !selectedinstance?.repos[0]?.repo) {
  3900. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  3901. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  3902. }
  3903. if(selectedinstance?.elevated && !selectedinstance?.elevated[0]?.repo) {
  3904. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  3905. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  3906. }
  3907. // Config from server always override merges into selection except for the current selection.
  3908. // PB : TODO -- utils.assign Array merges are non-distinct...
  3909. chessinstances[instanceName][node_env] = selectedinstance;
  3910. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  3911. cacheWriteInstanceConfig(chessinstances)
  3912. // PB : TODO -- We should probably write the new server config also...
  3913. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  3914. return chessinstances
  3915. }
  3916. var skipprereqs = {}
  3917. var maintask = () => {
  3918. // Default cmd to run !
  3919. processedArgs._[0] === processedArgs._[0] || 'pull';
  3920. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  3921. if(!noprerequisites[processedArgs._[0]]
  3922. && !skipprereqs[processedArgs._[0]]
  3923. ) {
  3924. return prerequisites.git.verifyAndInstall().then(()=>{
  3925. var e = { message : 'verifyAndInstall', success : true}
  3926. var inittasks = []
  3927. var commontask = () => { preworkerconfig(); return elxrworker(true) }
  3928. if(!detection_state.localInstanceDetected) {
  3929. var t1 = ()=>{ return createInstance(selectedinstance) };
  3930. t1.statuslog = statuslog
  3931. var specifictask = shell_verse.getNonElevatedTask(t1)
  3932. }
  3933. else {
  3934. var t2 = ()=>{ return acquireConfig(selectedinstance) };
  3935. t2.statuslog = statuslog
  3936. var specifictask = shell_verse.getNonElevatedTask(t2)
  3937. }
  3938. inittasks.push( specifictask().catch((err) => {
  3939. e = err;
  3940. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  3941. console.error(err)
  3942. }).then( commontask )
  3943. // .finally(()=>{
  3944. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  3945. // if(!e.success) fs.writeFileSync('run.done', 'error');
  3946. // // return process.exit()
  3947. // }))
  3948. )
  3949. return any(inittasks)
  3950. })
  3951. }
  3952. else {
  3953. console.log('cmd has no preqs or has been configured to skip preqs')
  3954. preworkerconfig()
  3955. return elxrworker()
  3956. }
  3957. }
  3958. function generateDependencies(){
  3959. // PB : TODO -- Keep only the last n runs...
  3960. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  3961. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
  3962. fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
  3963. // PB : TODO include and build from files... using rollup..
  3964. var downloadbatch =
  3965. `::**************************************************************************
  3966. :Download_ <url> <File>
  3967. Powershell.exe ^
  3968. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  3969. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  3970. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  3971. exit /b
  3972. ::**************************************************************************`
  3973. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch)
  3974. var windowselevate =
  3975. `
  3976. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  3977. <script language="vbscript">
  3978. document.title = "elxr control panel"
  3979. self.ResizeTo 200,600
  3980. Sub Window_Onload
  3981. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  3982. End Sub
  3983. Set objShell = CreateObject("WScript.Shell")
  3984. Set objENV = objShell.Environment("Process")
  3985. dim NODE_ENV
  3986. NODE_ENV = objENV("NODE_ENV")
  3987. </script>
  3988. <script language="javascript">
  3989. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  3990. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  3991. // alert(windowselevate.commandLine)
  3992. var args = windowselevate.commandLine.split('"').slice(3);
  3993. // alert(args)
  3994. var processedArgs = { _ : [] }
  3995. var namedArgs = [];
  3996. namedArgs.push('--wd=' + objENV('wd'))
  3997. // alert(namedArgs)
  3998. for(var item in args){
  3999. if(args[item].charAt(0) === '-'){
  4000. namedArgs.push(args[item])
  4001. var split = args[item].split('=');
  4002. processedArgs[split[0].slice(2)] = split[1] || true;
  4003. }
  4004. else processedArgs._.push(args[item]);
  4005. }
  4006. // args = args.forEach(function(item){ })
  4007. // alert('processedArgs._ : ' + processedArgs._);
  4008. // alert(processedArgs.runas);
  4009. // alert(objENV('wd'))
  4010. // PB : TODO -- Convert all the cli args back to string.
  4011. // __filename will sure we are launhed using the same entry point.
  4012. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' ${__filename.replace(/\\/g, '\\\\')} ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  4013. var shell = new ActiveXObject('shell.application');
  4014. // alert('launching node privilged. ' + processedArgs['nodepath'])
  4015. // shell.ShellExecute('cmd.exe', '/k where node', '', '', 10);
  4016. // shell.ShellExecute('cmd.exe', '/k notepad.exe', '', 'runas', 1);
  4017. // shell.ShellExecute('cmd.exe ', '/k node ', '', 'runas', 1);
  4018. // shell.ShellExecute('cmd.exe ', '/k node ' + cargs + '', '', 'runas', 1);
  4019. shell.ShellExecute('node', cargs, '', 'runas', 1);
  4020. // alert('/k node ' + cargs + '')
  4021. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  4022. var fso = new ActiveXObject('Scripting.FileSystemObject');
  4023. window.onload = function() {
  4024. document.body.style.backgroundColor = 'black';
  4025. document.body.style.fontFamily = 'arial';
  4026. var log = document.createElement('div');
  4027. log.innerHTML='Please Wait';
  4028. function l(msg){ log.innerHTML+= msg; };
  4029. log.style.color = 'blue';
  4030. log.style.width = '95%';
  4031. log.id = 'log';
  4032. document.body.appendChild(log);
  4033. l('<Br/>Current config : ')
  4034. l('<Br/>NODE_ENV = ' + NODE_ENV)
  4035. l('<Br/>cmd = ' + processedArgs._[0])
  4036. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  4037. l('<Br/><Br/>')
  4038. // alert(fso.GetAbsolutePathName("."))
  4039. var timer = function(){
  4040. l('.');
  4041. if(fso.FileExists("run.done")) {
  4042. fso.DeleteFile('run.done')
  4043. close();
  4044. }
  4045. else window.setTimeout(timer, 1000);
  4046. };
  4047. window.setTimeout(timer, 3000);
  4048. };
  4049. </script>
  4050. </html>
  4051. `
  4052. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate)
  4053. }
  4054. var startElxr = function() {
  4055. const retaincount = 2
  4056. var min = runtimestamp;
  4057. var collect = []
  4058. if(reconfirmcmds[processedArgs.label || processedArgs._[0]]) {
  4059. reconfirm = getReconfirmAll()
  4060. }
  4061. return detectLocalInstances().then((detectedinstanceoptions)=>{
  4062. detectedinstanceoptions.splice(0,0, __default)
  4063. var cmdinstance = cmds[clioverrides.cmd]
  4064. var cmdprompts = cmdinstance.getPossiblePrompts()
  4065. selectedinstance.node_env ? selectedinstance.node_env : selectedinstance.node_env = clioverrides.node_env
  4066. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  4067. selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  4068. , ...detectedinstanceoptions.slice(-2), promptkeys )
  4069. // promptkeys = utils.assign(promptkeys, clioverrides)
  4070. // startElxr requires instance // Independent cmds should have already been bypassed.
  4071. // if(cmdprompts.instanceName) {
  4072. // not an instanceless cmd.
  4073. console.dir(selectedinstance)
  4074. try {
  4075. chessinstances = acquirelocalinstances(selectedinstance);
  4076. findlocalinstances(chessinstances, detectedinstanceoptions)
  4077. initinstances(selectedinstance) // use the local instances for defaults if at all possible.
  4078. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  4079. var inst = initinstances(selectedinstance)
  4080. detection_state.localInstanceDetected = true;
  4081. return inst;
  4082. })
  4083. }
  4084. catch (e) {
  4085. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  4086. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  4087. return initinstances(selectedinstance)
  4088. })
  4089. // if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  4090. // // Weve not been told what to do.
  4091. // todo = todo.then(() => { return acquireChoices(selectedinstance) })
  4092. // }
  4093. todo = todo.then(() => {
  4094. try {
  4095. chessinstances = acquirelocalinstances(selectedinstance)
  4096. findlocalinstances(chessinstances, detectedinstanceoptions)
  4097. detectedinstanceoptions.splice(0,0, __default)
  4098. initinstances(selectedinstance)
  4099. detection_state.localInstanceDetected = true;
  4100. }
  4101. catch (e) {
  4102. // console.error(e)
  4103. console.log('No local instances config found in current root = ' + selectedinstance.root);
  4104. console.log('A config will be createed with the instance and environment chosen...')
  4105. // return (async ()=>{return await __default.reposerver})().then(()=>{
  4106. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  4107. // return selectedinstance = Object.assign(__default, selectedinstance);
  4108. // })
  4109. detection_state.localInstanceDetected = false;
  4110. return selectedinstance
  4111. }
  4112. })
  4113. }
  4114. return todo.then( ()=>{
  4115. // PB : TODO -- Embed this in the build instead of inlining it.
  4116. // Also attepmt to load from ../chess-config/...
  4117. var __repo_manifest = (require(path.normalize(instanceroot + '/elxr/repo-manifest.js')))(
  4118. 'defaultmanifest' // name
  4119. , { utils, username : selectedinstance.username, instanceName : selectedinstance.instanceName
  4120. , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' } // options
  4121. )
  4122. __default = Object.assign(__default, __repo_manifest, {
  4123. // Common baseline repos for all chess instances.
  4124. repos : (()=> {
  4125. var __repos = [
  4126. { repo : 'ember-masonry-grid' /*, branch : master*/ } // Default need not be specified.
  4127. , { repo : 'bbhverse' }
  4128. , { repo : 'clientverse' }
  4129. , { repo : 'serververse' }
  4130. , { repo : 'elxr' }
  4131. , { repo : 'ember-searchable-select' }
  4132. , { repo : 'loopback-component-jsonapi' }
  4133. , { repo : 'loopback-jsonapi-model-serializer' }
  4134. , { repo : 'loopback-connector-mysql' }
  4135. , { repo : 'loopback-connector-ds' }
  4136. , { repo : 'ember-service-worker' }
  4137. , { repo : 'ember-service-worker-asset-cache' }
  4138. , { repo : 'ember-service-worker-cache-fallback' }
  4139. , { repo : 'ember-service-worker-index' }
  4140. , { repo : 'ember-sw-client-route' }
  4141. , { repo : 'global-this' }
  4142. ]
  4143. Array.prototype.push.apply( __repos, __repo_manifest.repos)
  4144. return __repos;
  4145. })()
  4146. // Requires elevation only in windows
  4147. , elevated : [ { repo : 'chess-server-lib', requiresElevation : true } ]
  4148. , exludeMergeRepos : { }
  4149. })
  4150. initinstances(selectedinstance)
  4151. return selectedinstance
  4152. })
  4153. // }
  4154. // else return Promise.resolve(true)
  4155. })
  4156. .then(()=>{
  4157. runconfig = { NODE_ENV: selectedinstance.node_env }
  4158. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  4159. generateDependencies();
  4160. if(noprerequisites[processedArgs._[0]]
  4161. || skipprereqs[processedArgs._[0]]
  4162. ) {
  4163. return elxrworker()
  4164. }
  4165. var neTask = ()=>{
  4166. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`)
  4167. // collect garbage
  4168. return dirs( (dir)=>{
  4169. var matches = /run-(.*)/gm.exec(dir.name)
  4170. if(matches) {
  4171. if(+(matches[1]) < min) {
  4172. min = matches[1]
  4173. collect.splice( 0, 0, matches[1] )
  4174. }
  4175. else collect.push(matches[1])
  4176. }
  4177. return Promise.resolve(collect);
  4178. }, `${selectedinstance.root}/.elxr` )
  4179. .then(()=>{
  4180. // delete garbage
  4181. if(collect.length > retaincount) {
  4182. var asyncs = [];
  4183. while((collect.length - asyncs.length) > retaincount) {
  4184. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  4185. }
  4186. return Promise.all(asyncs)
  4187. }
  4188. else return true
  4189. })
  4190. .catch(e => {
  4191. console.error
  4192. })
  4193. }
  4194. neTask.statuslog = statuslog
  4195. shell_verse.getNonElevatedTask( neTask )()
  4196. var commonTask = ()=>{
  4197. verifyAndInstallPrerequisites.statuslog = statuslog
  4198. if((!skipprerequisites || processedArgs.forceprereqs)) mainTasks.push(verifyAndInstallPrerequisites);
  4199. mainTasks.push(maintask)
  4200. return any(mainTasks);
  4201. }
  4202. return commonTask()
  4203. })
  4204. }
  4205. var __default = {}; // PB : TODO -- Use initialized instance instead of default everywhere.
  4206. // PB : TODO -- In windows if we are run from an elevated shell we never move forward and simply exits !?.
  4207. // -- Currently workaround in windows is to always run from a non-elevated shell.
  4208. shell_verse.acquireElevationState().then((elevationstate) => {
  4209. return detectInstanceRoot.then(()=>{
  4210. var cmdobj = cmds[clioverrides.cmd]
  4211. return Promise.all((cmdobj.requires || []).map( (r) => utils.promisify(null, r) ) ).then(()=>{
  4212. if(cmdobj.independentcmd) {
  4213. if(cmdobj.requiresElevation) {
  4214. return cmdobj.cmdFn()
  4215. }
  4216. else return cmdobj.cmdFn()
  4217. }
  4218. else return startElxr()
  4219. })
  4220. .catch(e => {
  4221. if(typeof e === 'symbol') console.log('error : ' + 'symbol')
  4222. else console.log('error : ' + e)
  4223. })
  4224. })
  4225. })
  4226. // .then( () => {
  4227. // console.log(process._getActiveHandles());
  4228. // console.log(process._getActiveRequests());
  4229. // })
  4230. // detect if alread installed -> Take no action.
  4231. // download if no installer avalable -> next()
  4232. // install
  4233. function chackandinstall(items) {
  4234. var tasks = []
  4235. items.forEach(item => {
  4236. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  4237. })
  4238. return Promise.all(tasks).then(existances => {
  4239. existances.forEach((exists, i) => {
  4240. if (!exists) {
  4241. return downloadandinstall([items[i]])
  4242. }
  4243. })
  4244. })
  4245. }
  4246. function downloadandinstall(items) {
  4247. var tasks = []
  4248. items.forEach(item => {
  4249. tasks.push(getTaskDownload(item))
  4250. })
  4251. return Promise.all(tasks)
  4252. }
  4253. // Sample instances config.
  4254. // var instances = {
  4255. // "elixir": {
  4256. // "production": {
  4257. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  4258. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  4259. // , "exludeMergeRepos": {
  4260. // "elixir-config-development": true, "elixir-config-test": true
  4261. // , "elixir-config-production": true, "elixir-data": true
  4262. // }
  4263. // , "instanceName": "elixir", "node_env": "production"
  4264. // }
  4265. // },
  4266. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  4267. // }
  4268. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...