555
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

index.js 185KB

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