Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

index.js 192KB

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