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

index.js 226KB

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