Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

index.js 226KB

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