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

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