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

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