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

index.js 262KB

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