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.

idxbak.js 265KB

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 gitops = {
  1152. getdiscoverbranchcmd : function(repodef){
  1153. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  1154. var cmd = [gitbash
  1155. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  1156. , { cwd: repodef.repodir + '/' + repodef.repo, title: 'discoverbranch for ' + repodef.repo + ' ' + parameters.join(' ') }]
  1157. return cmd
  1158. }
  1159. }
  1160. var getPullCmd = (repodef) => {
  1161. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  1162. // console.log(useGitPull)
  1163. var repo = repodef.repo
  1164. var pullCmd = []
  1165. var branch = repodef.branch
  1166. if(!branch) {
  1167. // console.warn('No branch was specified detecting from working client.')
  1168. // First check if working client exists.
  1169. // if (existsSync(instanceroot + '/' + repo)) {
  1170. pullCmd= gitops.getdiscoverbranchcmd(repodef)
  1171. // }
  1172. // else performPullOrClone
  1173. }
  1174. // var pullCmd = ['pullall', [], { cwd : repo }]
  1175. // if (useGitPull) by default... default should probably be pullall i.e. all remotes all branches...
  1176. // var pullCmd = [gitInstallDir
  1177. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  1178. // , { cwd: instanceroot + '/' + repo, title: 'pull all remotes for ' + repo }]
  1179. if(branch) {
  1180. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  1181. var pullCmd = [ gitbash
  1182. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  1183. , { cwd: repodef.repdir + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  1184. }
  1185. else pullCmd = ['git', ['pull'], {
  1186. inherit: true, shell: true,
  1187. cwd: repodef.repodir + '/' + repo
  1188. // , env: ENV
  1189. , runas: processedArgs.runas
  1190. , title: `git pull ${repo}`
  1191. }]
  1192. return pullCmd
  1193. }
  1194. var getPullOrCloneTask = (repodef, branch, owner, errHandler, elevatedBatch, regularBatch) => {
  1195. // PB : TODO -- Handle no branch passed in case.
  1196. // if(!branch) { throw 'No branch specified' }
  1197. var repo = repodef.repo;
  1198. repodef.repodir = repodef.repodir || instanceroot
  1199. repodef.branch = repodef.branch || branch
  1200. elevatedBatch = elevatedBatch || [];
  1201. regularBatch = regularBatch || [];
  1202. try{
  1203. // PB : TODO -- local repo folder named the same as the remote repository name is not enough to establish existence.
  1204. // This remote repo and branch may have been or may need to be added as a local tracking branch
  1205. // to any other local repo folder (with a different name)
  1206. var exists = existsSync(instanceroot + '/' + repo)
  1207. }
  1208. catch(e){
  1209. exists = false
  1210. console.log(e)
  1211. }
  1212. function initTask(etask){
  1213. etask.info = { repo }
  1214. etask.errHandler = errHandler
  1215. etask.statuslog = statuslog
  1216. etask.processedArgs = processedArgs
  1217. etask.selectedinstance = selectedinstance
  1218. etask.runtimestamp = runtimestamp
  1219. etask.ENV = ENV
  1220. }
  1221. function initElevatedBatch(){
  1222. elevatedBatch.info = { repo }
  1223. elevatedBatch.errHandler = errHandler
  1224. elevatedBatch.statuslog = statuslog
  1225. elevatedBatch.processedArgs = processedArgs
  1226. elevatedBatch.selectedinstance = selectedinstance
  1227. elevatedBatch.runtimestamp = runtimestamp
  1228. elevatedBatch.ENV = ENV
  1229. }
  1230. if (exists) {
  1231. var tasks = [];
  1232. return (()=>{
  1233. // 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.
  1234. if(selectedinstance.addremotes) {
  1235. return oplist['get-remotes']({repo}).then(( remotes )=>{
  1236. return oplist['get-upstream']({repo, remotes}).then(( upstream ) => {
  1237. return __addremotesandpull({ upstream, remotes})
  1238. })
  1239. })
  1240. }
  1241. else return __pull();
  1242. })()
  1243. function __pull(){
  1244. var branchprint = branch ? ' branch :' + branch : '';
  1245. var task = ()=>{
  1246. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  1247. return any(tasks).then( ()=>{
  1248. return nodeShellExec.apply(null, getPullCmd(repodef)).then(() => {
  1249. return true;
  1250. })
  1251. })
  1252. }
  1253. initTask(task)
  1254. if(repodef.requiresElevation) {
  1255. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  1256. 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
  1257. else initTask(elevatedBatch[elevatedBatch.length-1])
  1258. return elevatedBatch[elevatedBatch.length-1]
  1259. }
  1260. else {
  1261. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  1262. return regularBatch[regularBatch.length-1]
  1263. }
  1264. }
  1265. function __addremotesandpull(options){
  1266. // Add the remotes
  1267. var tasks = []
  1268. // selectedinstance.selectedremotes are optional and need not be enforced to be chosen. The selection for hte selected remotes
  1269. // could also be derived from a crossfilter of remote-type selected for this run and the current chosen and operating reposervers.
  1270. var selectedremotes = Array.from( new Set(selectedinstance.selectedremotes.concat(Object.keys(repodef.remotes || {}))));
  1271. if(selectedremotes.length > 0) var selectedremoteFilter = function(rs) { return selectedremotes.find( rs.server ) }
  1272. else var selectedremoteFilter = function(){ return true }
  1273. var repoRemotes = Object.assign( {}, selectedinstance.remotes, options.remotes, options.upstream, repodef.remotes );
  1274. // We need a most permissive filtered list to use as an efficient starting point to further reduce to whats actually needed.
  1275. // 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.
  1276. Object.keys(repoRemotes).forEach((remotename)=>{
  1277. // PB : TODO -- ai prefix for all apis that require an answer amongst many choices.
  1278. var ai_RemoteAddNeeded = (r)=>{
  1279. if(r.server === reposerver && selectedremoteFilter() && r.accessibility.find( selectedinstance[ 'remote-type' ] )){ // currently chosen remotetype...
  1280. var exists = false;
  1281. if(exists = (options.remotes[r.remotename] || Object.keys(options.remotes).find( lrn => {
  1282. var exists = options.remotes[lrn].server === r.server && !options.remotes[r.remotename]
  1283. if(exists) console.warn('Found duplicate remote with a different name for the same server...')
  1284. return exists
  1285. } )) ) {
  1286. return false // Already a remote not required.
  1287. }
  1288. return true // PB : TODO -- Sort and display highest priority target.remotes.sort( )
  1289. }
  1290. return false
  1291. };
  1292. tasks.push(
  1293. ()=>{
  1294. return oplist['remote exists']({
  1295. remotename, repo, benign : true, ignorefailures : true
  1296. , url : repoRemotes[remotename].url + repo
  1297. , branch : checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  1298. }).then( (r) => {
  1299. if(!r[1]) return false; // PB : TODO -- Not accessible skip for now probably should remove.
  1300. else if(r[0]) return true; // Already added nothing to do
  1301. else if(ai_RemoteAddNeeded( repoRemotes[remotename] )) return oplist['remote add']( { remotename,
  1302. 'set-upstream' : (selectedinstance['upstream'] || `${remotename}/${branch}`) // ??? when url accessible... in order of highest priority
  1303. , reponame : repo
  1304. , url : repoRemotes[remotename].url , branch : checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  1305. })
  1306. // else skipped as remote is not relevant for this repo...
  1307. })
  1308. }
  1309. )
  1310. })
  1311. utils.any(tasks).then(()=>{
  1312. __pull()
  1313. })
  1314. }
  1315. }
  1316. else {
  1317. // PB : TODO -- detect if a clonable repo exists within the context of currentGitAuthUser on remote reposerver...
  1318. console.log('cloning ' + repo)
  1319. // PB : TODO -- add additional remotes after cloning and pull again...
  1320. var task = ()=>{
  1321. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${repodef.owner || owner || defaultowner}/` + repo + '.git'],
  1322. {
  1323. inherit: true, shell: true,
  1324. env: ENV
  1325. , cwd : instanceroot
  1326. , runas: processedArgs.runas
  1327. }).then(() => {
  1328. var task = ()=>{
  1329. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  1330. {
  1331. inherit: true, shell: true,
  1332. env: ENV
  1333. , cwd: instanceroot + '/' + repo
  1334. , runas: processedArgs.runas
  1335. , title: `'git', ${['config', '--replace-all', 'core.symlinks', selectedinstance.username].join(' ')}`
  1336. })
  1337. }
  1338. initTask(task)
  1339. if(repodef.requiresElevation) {
  1340. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  1341. return elevatedBatch[elevatedBatch.length-1]
  1342. }
  1343. else {
  1344. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  1345. return regularBatch[regularBatch.length-1]
  1346. }
  1347. })
  1348. }
  1349. initTask(task)
  1350. if(repodef.requiresElevation) {
  1351. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  1352. return elevatedBatch[elevatedBatch.length-1]
  1353. }
  1354. else {
  1355. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  1356. return regularBatch[regularBatch.length-1]
  1357. }
  1358. }
  1359. }
  1360. var util = require('util');
  1361. var cliname = 'elxr';
  1362. var ver = '1.1';
  1363. var readme = `
  1364. Command syntax examples
  1365. elxr
  1366. Displays help. Same as elxr h
  1367. elxr i
  1368. Runs interactive propmts to help choose installation options.
  1369. NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
  1370. General command syntax.
  1371. Eg: NODE_ENV=development elxr pull elixir
  1372. Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
  1373. The specific cmd defines what the value is interpreted as.
  1374. There are several cmds that do not require an {{instancename}} parameter.
  1375. Eg: elxr remote remove origin
  1376. Git operations or passthrough external commands on all repository folders in you working directory.
  1377. Main objectives.
  1378. elxr cli is a wrapper around other shell commands and api based operations.
  1379. One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
  1380. Eg: A git operation like pull can be repeated consistently on a set of git repositories.
  1381. `;
  1382. var elxr = {
  1383. help() {
  1384. return chalk.cyanBright(`
  1385. -------------------------------------------------------------------------------
  1386. *** BBH Elixir ***
  1387. -------------------------------------------------------------------------------
  1388. elxr ${ver}
  1389. A cli tool for chess
  1390. ${help}
  1391. -------------------------------------------------------------------------------
  1392. `)
  1393. }
  1394. , info() {
  1395. return chalk.cyanBright(`
  1396. -------------------------------------------------------------------------------
  1397. *** BBH Elixir ***
  1398. -------------------------------------------------------------------------------
  1399. elxr ${ver}
  1400. A cli tool for chess
  1401. -------------------------------------------------------------------------------
  1402. `)
  1403. }
  1404. , getPullOrCloneTask(args){
  1405. // def can be an instance config
  1406. // Or an object with many repos and elevated repos
  1407. // Or a single repo ( Either Elevated or normal. )
  1408. // USAGE
  1409. // elxr pull elixir origin master
  1410. // elxr pull
  1411. // not all remote branches are setup to be tracked locally (respective remotes and branches).
  1412. // pull --all is useless. As it fetches all remotes and branches but only merges current branch.
  1413. // apart from remote tracking branches We are interested in pulling from all remotes and relavant branches.
  1414. // The branch pipline should feed back to master
  1415. // master -> test -> stage -> release[nnnn] -> production
  1416. // (master) <= git merge [all remotes] production && git merge [all remotes] release[nnnn]
  1417. // git merge [all remotes] stage && git merge [all remotes] test && git merge [all remotes] master
  1418. var __args = {
  1419. remotename : args.remotename|| processedArgs._[2]
  1420. , url : args.url || processedArgs._[3]
  1421. , branch : args.branch || processedArgs._[4] // If branch not specified opearte on the current branch of each working directorys
  1422. }
  1423. // var commands = [
  1424. // // ['git', ['checkout', __args.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]]
  1425. // ,
  1426. // ]
  1427. // var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  1428. // var pullCmd = [ gitbash
  1429. // , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  1430. // , { cwd: instanceroot + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  1431. var def = args || {
  1432. repos : selectedinstance.repos,
  1433. elevated : selectedinstance.elevated
  1434. }
  1435. var elevatedpulltasks = null;
  1436. if(def.repo) {
  1437. // Single repo case.
  1438. if(def.repo.requiresElevation) {
  1439. var t1 = function() {
  1440. return performPullOrClone(def).then(() => {
  1441. return true;
  1442. }).catch((e) => {
  1443. console.error(e)
  1444. }).finally(Traq.finally)
  1445. }
  1446. t1.statuslog = statuslog
  1447. t1.selectedinstance = selectedinstance
  1448. t1.processedArgs = processedArgs
  1449. elevatedpulltasks = shell_verse.getElevatedTask( t1 )
  1450. }
  1451. else {
  1452. var t2 = function(){
  1453. return performPullOrClone(def).then(() => {
  1454. console.log('pulled ' + JSON.stringify(def.repo))
  1455. return true;
  1456. }).catch((e) => {
  1457. console.error(e)
  1458. })
  1459. // .finally(Traq.finally)
  1460. }
  1461. t2.statuslog = statuslog
  1462. var regularpulltasks = shell_verse.getNonElevatedTask( t2 )
  1463. }
  1464. if(elevatedpulltasks) return elevatedpulltasks //getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1465. else return regularpulltasks // getTaskWithoutElevation({ regularpulltasks})
  1466. }
  1467. // console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  1468. console.dir(def)
  1469. console.log('Running exlr pull : ' + path.dirname(__dirname))
  1470. var useGitPull = processedArgs.useGitPull || false;
  1471. if(def.elevated || def.repos) {
  1472. if(def.elevated) def.requiresElevation = true;
  1473. else delete def.requiresElevation;
  1474. }
  1475. else {
  1476. if(def.requiresElevation) def.elevated = [def]
  1477. else def.repos = [def]
  1478. }
  1479. var regularpulltasks = function(){ return Promise.resolve(true) }
  1480. if(def.elevated){
  1481. elevatedpulltasks = function() {
  1482. var eBatch = []
  1483. def.elevated.map((def) => getPullOrCloneTask(def, null, null, null, eBatch))
  1484. if(eBatch.length<1) return Promise.resolve(true);
  1485. eBatch[0].processedArgs = processedArgs
  1486. return shell_verse.runElevatedBatch(eBatch).then(() => {
  1487. return true;
  1488. }).catch((e) => {
  1489. console.error(e)
  1490. })
  1491. }
  1492. elevatedpulltasks.statuslog = statuslog
  1493. }
  1494. if(def.repos) {
  1495. var regularpulltasks = function(){
  1496. var pendingpulls = [];
  1497. def.repos.forEach((def) => {
  1498. pendingpulls.push(
  1499. // PB : TODO serializing to prevent out of memory.
  1500. // Need to optimize as batches and streams...
  1501. function(){
  1502. // if(def.repo === 'setup') return;
  1503. // if(def.repo !== 'chess-client-lib') return;
  1504. return performPullOrClone(def).then(()=>{ console.log('pulled ' + JSON.stringify(def.repo)) })
  1505. .catch(e => {
  1506. console.error(util.inspect(e)); throw e })
  1507. }
  1508. )
  1509. })
  1510. return any(pendingpulls).finally(Traq.finally)
  1511. }
  1512. regularpulltasks.statuslog = statuslog
  1513. }
  1514. // if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1515. // else return getTaskWithoutElevation({ regularpulltasks})
  1516. return elevatedpulltasks().then(()=>{
  1517. if(isWin() && isElevated) return Promise.resolve(true);
  1518. return regularpulltasks()
  1519. })
  1520. }
  1521. }
  1522. // unbound. Bind before using.
  1523. var unbound_interactionpoints = function(selectedinstance){
  1524. var self = this;
  1525. var _interactionpoints = {
  1526. get runchoice() {
  1527. return {
  1528. label :
  1529. `Choose an option :
  1530. d) Install the default chess instance.
  1531. => elxr i chess node_env=development --default
  1532. n) Create your custom new instance interactively
  1533. => elxr i {{instanceName}} node_env={{environment}}
  1534. i) Choose an instance and environment to install
  1535. => elxr i {{instanceName}} node_env={{environment}}
  1536. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  1537. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  1538. h) Help
  1539. q) Quit
  1540. : `
  1541. , choices : []
  1542. , defaultchoice : 'c'
  1543. , selectedchoice : self.target.runchoice
  1544. , interpret : function(choice){
  1545. var interpret_map = {
  1546. d : function(){
  1547. processedArgs._[0] = 'i'
  1548. self.target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  1549. self.target.node_env = processedArgs.node_env = (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  1550. self.target.reposerver = 'https://git.bbh.org.in' // PB : TODO -- Read from global defaults...
  1551. }
  1552. , n : function() { processedArgs._[0] = 'i' }
  1553. , i : function() {
  1554. processedArgs._[0] = 'i'
  1555. // processedArgs._[1] = self.target.instanceName || processedArgs._[1] || 'chess';
  1556. }
  1557. , c : async function() {
  1558. // self here will always be the self.target.
  1559. Object.defineProperty(self, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  1560. label : `Enter cmd :
  1561. p) pull
  1562. Default <= p
  1563. : `
  1564. , defaultchoice : 'pull'
  1565. }
  1566. ));
  1567. var cmd = await self.target['cmd'];
  1568. if (!cmd || cmd === 'p') { self.target['cmd'] = processedArgs._[0] = 'pull' }
  1569. else self.target['cmd'] = processedArgs._[0] = cmd
  1570. return cmd;
  1571. }
  1572. , h : function() { console.log(elxr.help()); process.exit() } // PB : TODO -- Why do we need log.
  1573. , q : function() { process.exit() }
  1574. }
  1575. if(Promise.resolve(choice) === choice){
  1576. return choice.then( resolvedchoice => {
  1577. return (interpret_map[choice] || interpret_map['c']).call(self.target)
  1578. })
  1579. }
  1580. else return Promise.resolve( (interpret_map[choice] || interpret_map['c']).call(self.target) )
  1581. // var __interpreter = interpret_map[choice] || interpret_map['c']
  1582. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  1583. // if(interpret_map[choice]) __interpreter = interpret_map[choice];
  1584. // return __interpreter.call(self.target)
  1585. }
  1586. }
  1587. }
  1588. , get instanceName() {
  1589. return { label : `Enter Instance Name ( <= ${self.target.instanceName || 'chess'} ) : `
  1590. , choices : self.choices['instanceName'], defaultchoice : 'chess'
  1591. , selectedchoice : self.target.instanceName
  1592. }
  1593. }
  1594. , get instanceType() {
  1595. return { label : `Enter Instance Type ( <= ${self.target.instanceType || 'development'} ) : `
  1596. , choices : self.choices['instanceType'], defaultchoice : 'development'
  1597. , selectedchoice : self.target.instanceType || 'development'
  1598. }
  1599. }
  1600. , get reposerver() {
  1601. return { label : `Enter Repo Server Base Url ( <= ${self.target.reposerver || 'https://git.bbh.org.in'} ) : `
  1602. , get choices() {
  1603. // self.choices['reposerver'].forEach( rs => {
  1604. // var __rs = new URL(rs);
  1605. // __rs.hostname = __rs.host;
  1606. // __rs.path = '/'
  1607. // __rs.method = 'GET'
  1608. // RESTAPI.get(__rs, function(data){ rs.accessibility = 'accessible' }
  1609. // , function(error){ rs.accessibility = 'unaccessible' } )
  1610. // })
  1611. return self.choices['reposerver']
  1612. }
  1613. , set choices(cs) {
  1614. return self.choices['reposerver'].concat([selectedinstance.reposerver]).concat(cs)
  1615. }
  1616. , defaultchoice : selectedinstance.reposerver || 'https://git.bbh.org.in'
  1617. , selectedchoice : self.target.reposerver
  1618. }
  1619. }
  1620. // , 'upstream-remote' : { label : `Enter Remote Name ( <= ${self.target['upstream-remote'] || 'chess'} ) : `
  1621. // , get choices() {
  1622. // var reposerver = self.target['reposerver']
  1623. // var remotes = []
  1624. // var trs = self.target.reposervers || []
  1625. // trs.forEach(rs => {
  1626. // if(rs.server === reposerver){
  1627. // remotes.push(remote)
  1628. // // PB : TODO -- Sort and display highest priority self.target.remotes.sort( )
  1629. // }
  1630. // })
  1631. // return remotes
  1632. // }
  1633. // , set choices(addlchoices){
  1634. // var reposerver = self.target['reposerver']
  1635. // var remotes = []
  1636. // var trs = self.target.reposervers || []
  1637. // trs.forEach(rs => {
  1638. // if(rs.server === reposerver){
  1639. // remotes.push(remote)
  1640. // // PB : TODO -- Sort and display highest priority self.target.remotes.sort( )
  1641. // }
  1642. // })
  1643. // return remotes.concat(addlchoices)
  1644. // }
  1645. // , defaultchoice : 'userfork'
  1646. // , selectedchoice : self.target['upstream-remote'] || 'userfork'
  1647. // // Just using getters resolves dependencies..., dependencies : [ ()=>{ return self.target['reposerver'] } ]
  1648. // }
  1649. // , 'remote-type' : { label : `Enter Remote Type ( <= ${self.target['remote-type'] || 'public'} ) : `
  1650. // , get choices() {
  1651. // return ['external', 'public', 'private', 'github', 'unc']
  1652. // }
  1653. // , set choices(addlchoices){
  1654. // var reposerver = self.target['reposerver']
  1655. // var remotes = []
  1656. // var trs = self.target.reposervers || []
  1657. // trs.forEach(rs => {
  1658. // if(rs.server === reposerver){
  1659. // remotes.push(remote)
  1660. // // PB : TODO -- Sort and display highest priority self.target.remotes.sort( )
  1661. // }
  1662. // })
  1663. // return ['external', 'public', 'private', 'github', 'unc'].concat(addlchoices)
  1664. // }
  1665. // , defaultchoice : 'public'
  1666. // , selectedchoice : self.target['remote-type'] || 'public'
  1667. // // Just using getters resolves dependencies..., dependencies : [ ()=>{ return self.target['reposerver'] } ]
  1668. // }
  1669. // , 'selectedremotes' : { label : `Chose Remote Names ( <= ${self.target['selectedremotes'] || 'chess'} ) : `
  1670. // , get choices() {
  1671. // var reposerver = self.target['reposerver'] // PB : TODO -- We need options to work with multiple selected reposervers at the same time..
  1672. // var remotenames = []
  1673. // Object.entries(self.target.remotes || []).forEach( ([rname, r]) => {
  1674. // if(r.server === reposerver && r.accessibility.find( self.target[ 'remote-type' ] )){
  1675. // remotes.push(rname)
  1676. // // PB : TODO -- Sort and display highest priority self.target.remotes.sort( )
  1677. // }
  1678. // })
  1679. // // PB : TODO -- Need to generate all possible permuted choices nP( 1 -> n )
  1680. // // Currenty handles all combinations without any priority order.
  1681. // var _remotechoices = [] // Array of arrays of choices.
  1682. // remotenames.forEach( r => {
  1683. // var __rcs = []
  1684. // _remotechoices.forEach(rc => {
  1685. // __rcs.push( rc.concat(r) )
  1686. // })
  1687. // Array.prototype.push.apply( _remotechoices, __rcs)
  1688. // _remotechoices.push(r)
  1689. // })
  1690. // return _remotechoices
  1691. // }
  1692. // , defaultchoice : ['userfork', 'chess'] // userfork and chess should imlicitly point to userfork-external and chess-external when external connectivity is dtetected.
  1693. // , selectedchoice : self.target['selectedremotes'] || ['userfork-external', 'chess-external']
  1694. // // , defaultchoice : { 'userfork-external' : self.target.remotes['userfork-external'] , 'chess-external' : self.target.remotes['chess-external'] }
  1695. // // , selectedchoice : self.target['selectedremotes'] || { 'userfork-external' : self.target.remotes['userfork-external'] , 'chess-external' : self.target.remotes['chess-external'] }
  1696. // // Info : Just using getters resolves dependencies..., dependencies : [ ()=>{ return self.target['reposerver'] } ]
  1697. // }
  1698. , get username() { return { label : `Enter User Id for ${self.target.reposerver} ( <= ${self.target.username || 'chess'} ) : `
  1699. , choices : self.choices['username'], defaultchoice : self.target.username || 'chess', selectedchoice : self.target.username } }
  1700. , get password() { return { label : `Enter Password for ${self.target.username} @ ${self.target.reposerver} ( <= ${self.target.password || ''} ) : `
  1701. , choices : self.choices['password'], defaultchoice : '***', selectedchoice : self.target.password } }
  1702. , get email() { return { label : `Enter Email for ${self.target.username} @ ${self.target.reposerver} ( <= ${self.target.email || ''} ) : `
  1703. , choices : self.choices['email'], defaultchoice : 'guest@bbh.org.in', selectedchoice : self.target.email } }
  1704. }
  1705. return _interactionpoints
  1706. }
  1707. var get_interactionpoints_template = function(){
  1708. return {
  1709. instanceName : { label : `Enter Instance Name ( <= ${this.target.instanceName || 'chess'} ) : `
  1710. , choices : this.choices['instanceName'], defaultchoice : 'chess'
  1711. , selectedchoice : this.target.instanceName
  1712. }
  1713. }
  1714. }
  1715. var subcommandlabels = {
  1716. switch : (`switch ${processedArgs._[1] || ''}`).trim()
  1717. }
  1718. // The main elxr cli process
  1719. function elxrworker(oplist) {
  1720. var __runcmd = function (label, oplist) {
  1721. var distinquishedlabel = subcommandlabels[label] || label
  1722. return oplist[distinquishedlabel] ? oplist[distinquishedlabel].cmdFn ? oplist[distinquishedlabel].cmdFn(processedArgs) : oplist[distinquishedlabel](processedArgs) : null;
  1723. }
  1724. return __runcmd(processedArgs.label || clioverrides.cmd || processedArgs._[0] || 'undefined', oplist);
  1725. }
  1726. function resetgitconfig(){
  1727. // https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows
  1728. // use git config --edit --system to remove the helper = manager line so that it is no longer registered as a credential helper.
  1729. // For bonus points, use git config --edit --global and insert:
  1730. // [core]
  1731. // askpass =
  1732. // https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage
  1733. // Git Credential storage...
  1734. // git config --global credential.helper 'store --file ~/.elxrcredentials'
  1735. // git credential fill
  1736. // protocol=https
  1737. // host=git.bbh.org.in
  1738. // username=bob
  1739. // password=pppp
  1740. // git credential-store --file ~/.gitcredentials store
  1741. // // notepad C:/Program Files/Git/etc/gitconfig
  1742. // git config --edit --system
  1743. // git credential-store --file ~/git.store store
  1744. // Find system git config
  1745. // git config --global --edit
  1746. // git config --list --show-origin
  1747. // git config --list --show-origin --show-scope
  1748. // https://stackoverflow.com/questions/35942754/how-can-i-save-username-and-password-in-git
  1749. // Recipie
  1750. // git config --global --unset credentials.helper
  1751. // cd /path/to/my/repo
  1752. // git config --unset credential.helper
  1753. // git config credential.helper 'store --file ~/.git_repo_credentials'
  1754. // git config credential.*.username my_user_name
  1755. // git config credential.https://gitlab.com.username my_user_name
  1756. // git credential fill
  1757. // git config --global credential.modalprompt false // doesnst work.
  1758. // core askpass = ;;; https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows
  1759. var options = {
  1760. inherit: true, shell: true, env: ENV
  1761. , cwd: instanceroot
  1762. , runas: processedArgs.runas
  1763. }
  1764. var task = ['git', ['config'], options]
  1765. var tasklist = [
  1766. // ['--global', '--unset credentials.helper']
  1767. // ['--unset', 'credentials.helper']
  1768. // ,
  1769. // ['credential.helper', `'store --file git_repo_credentials'`]
  1770. ['--global', 'credential.helper', "'store --file ~/.git_repo_credentials'"]
  1771. , ['--global', '--replace-all', 'user.name', 'pb']
  1772. , ['--global', '--replace-all', 'user.email', 'pradeep@bbh.org.in']
  1773. // , ['--list']
  1774. // , ['credential', 'fill']
  1775. ]
  1776. var onEachError = e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n')
  1777. var shellT = (args) => { return getgitbashtask(args, onEachError)
  1778. // .catch(e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n' + tasq.toString()) )
  1779. }
  1780. execserial(tasklist, task, shellT, onEachError )
  1781. }
  1782. function reinit(){
  1783. sysAddPathVar('%AppData%\\npm')
  1784. resetgitconfig()
  1785. }
  1786. function init(){
  1787. sysAddPathVar('%AppData%\\npm')
  1788. resetgitconfig()
  1789. }
  1790. var getCmdString = function(args){ return `"${args[0]} ${args[1].join(' ')}"` }
  1791. var getgitbashtask = (args, onEachError) => { return () => {
  1792. return nodeShellExec( `"${gitbash}"`, ['-c', getCmdString(args)], args[2]).catch( onEachError || function(e){ console.error(e) }) }
  1793. }
  1794. var getshelltask = (args) => {
  1795. return args[0] === 'rm' ? getgitbashtask(args) : () => {
  1796. return nodeShellExec.apply(null, args).catch(function(e){
  1797. e.benign = args[2].benign;
  1798. if(!e.benign) { console.error( JSON.stringify(e) ); }
  1799. throw e
  1800. })
  1801. }
  1802. }
  1803. const GITSHELL = (function(){
  1804. const GITSHELL = function(){}
  1805. GITSHELL.bash = shell_verse.getbash()
  1806. GITSHELL.getdiscoverbranchcmd = function(repodef){
  1807. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  1808. var cmd = [GITSHELL.bash
  1809. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  1810. , { cwd: repodef.repodir + '/' + repodef.repo, title: 'discoverbranch for ' + repodef.repo + ' ' + parameters.join(' ') }]
  1811. return cmd
  1812. }
  1813. GITSHELL.getPullCmd = (repodef) => {
  1814. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  1815. // console.log(useGitPull)
  1816. var repo = repodef.repo
  1817. var pullCmd = []
  1818. var branch = repodef.branch
  1819. if(!branch) {
  1820. // console.warn('No branch was specified detecting from working client.')
  1821. // First check if working client exists.
  1822. // if (existsSync(instanceroot + '/' + repo)) {
  1823. pullCmd = GITSHELL.getdiscoverbranchcmd(repodef)
  1824. // }
  1825. // else performPullOrClone
  1826. }
  1827. // var pullCmd = ['pullall', [], { cwd : repo }]
  1828. // if (useGitPull) by default... default should probably be pullall i.e. all remotes all branches...
  1829. // var pullCmd = [gitInstallDir
  1830. // , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  1831. // , { cwd: instanceroot + '/' + repo, title: 'pull all remotes for ' + repo }]
  1832. if(branch) {
  1833. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  1834. var pullCmd = [ gitbash
  1835. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  1836. , { cwd: repodef.repodir + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  1837. }
  1838. else pullCmd = ['git', ['pull'], {
  1839. inherit: true, shell: true,
  1840. cwd: repodef.repodir + '/' + repo
  1841. // , env: ENV
  1842. , runas: processedArgs.runas
  1843. , title: `git pull ${repo}`
  1844. }]
  1845. return pullCmd
  1846. }
  1847. GITSHELL.pullORcloneSHELLCMD = ( repodef ) => {
  1848. // console.dir(repodef)
  1849. ARGUMENTVALIDATOR.validate( repodef, { repo : true, repodir : true, branch : true })
  1850. var repo = repodef.repo;
  1851. repodef.repodir = repodef.repodir || instanceroot
  1852. var branch = repodef.branch
  1853. var elevatedBatch = repodef.elevatedBatch || [];
  1854. var regularBatch = repodef.regularBatch || [];
  1855. var errorHandler = (e) => {
  1856. console.error(e)
  1857. throw e;
  1858. }
  1859. function initTask(etask){
  1860. etask.info = { repo }
  1861. etask.errHandler = elevatedBatch.errHandler || errorHandler
  1862. etask.statuslog = statuslog
  1863. etask.processedArgs = processedArgs
  1864. etask.selectedinstance = selectedinstance // utils.assign({}, selectedinstance, { root : repodef.repodir })
  1865. etask.runtimestamp = runtimestamp
  1866. etask.ENV = ENV
  1867. }
  1868. function initElevatedBatch(){
  1869. elevatedBatch.info = { repo }
  1870. elevatedBatch.errHandler = elevatedBatch.errHandler || errorHandler
  1871. elevatedBatch.statuslog = statuslog
  1872. elevatedBatch.processedArgs = processedArgs
  1873. elevatedBatch.selectedinstance = selectedinstance //utils.assign({}, selectedinstance, { root : repodef.repodir })
  1874. elevatedBatch.runtimestamp = runtimestamp
  1875. elevatedBatch.ENV = ENV
  1876. }
  1877. try{
  1878. // PB : TODO -- local repo folder named the same as the remote repository name is not enough to establish existence.
  1879. // This remote repo and branch may have been or may need to be added as a local tracking branch
  1880. // to any other local repo folder (with a different name) may yet be this repository...
  1881. var exists = existsSync(repodef.repodir + '/' + repo)
  1882. }
  1883. catch(e){
  1884. exists = false
  1885. console.log(e)
  1886. }
  1887. if (exists) {
  1888. var tasks = [];
  1889. return __pull();
  1890. function __pull(){
  1891. var branchprint = branch ? ' branch :' + branch : '';
  1892. var cmd = GITSHELL.getPullCmd(repodef)
  1893. // ['git', ['pull', '-c', 'core.symlinks=true', repodef.remotebase + `/${getowner(repodef)}/` + repo + ( repodef.localrepo ? '' : '.git') ],
  1894. // {
  1895. // inherit: true, shell: true,
  1896. // env: ENV
  1897. // , cwd : repodef.repodir
  1898. // , runas: repodef.requiresElevation || processedArgs.runas
  1899. // }]
  1900. var task = ()=>{
  1901. return any(tasks).then( ()=>{
  1902. console.log('pulling ' + repodef.repodir + '/' + repo + branchprint )
  1903. return nodeShellExec.apply(null, cmd).then(() => {
  1904. return true;
  1905. })
  1906. })
  1907. }
  1908. initTask(task)
  1909. if(repodef.requiresElevation) {
  1910. task.selectedinstance = selectedinstance // { root : repodef.repodir }
  1911. task.args = [cmd[0], [cmd[1].join(' ')], cmd[2]]
  1912. // task.args = GITSHELL.getPullCmd(repodef)
  1913. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  1914. 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
  1915. else initTask(elevatedBatch[elevatedBatch.length-1])
  1916. return elevatedBatch[elevatedBatch.length-1]
  1917. }
  1918. else {
  1919. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  1920. return regularBatch[regularBatch.length-1]
  1921. }
  1922. }
  1923. }
  1924. else {
  1925. // PB : TODO -- detect if a clonable repo exists within the context of currentGitAuthUser on remote reposerver...
  1926. // PB : TODO -- add additional remotes after cloning and pull again...
  1927. var cmd = ['git', ['clone', '-c', 'core.symlinks=true', repodef.remotebase + `/` + repo + ( repodef.localrepo ? '' : '.git') ],
  1928. {
  1929. inherit: true, shell: true,
  1930. env: ENV
  1931. , cwd : repodef.repodir
  1932. , runas: repodef.requiresElevation || processedArgs.runas
  1933. }]
  1934. var task = ()=>{
  1935. console.log('cloning ' + repo)
  1936. return nodeShellExec.apply( null, cmd).then(() => {
  1937. var task = ()=>{
  1938. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  1939. {
  1940. inherit: true, shell: true,
  1941. env: ENV
  1942. , cwd: repodef.repodir + '/' + repo
  1943. , runas: repodef.requiresElevation || processedArgs.runas
  1944. , title: `'git', ${['config', '--replace-all', 'core.symlinks', selectedinstance.username].join(' ')}`
  1945. })
  1946. }
  1947. initTask(task)
  1948. if(repodef.requiresElevation) {
  1949. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  1950. return elevatedBatch[elevatedBatch.length-1]
  1951. }
  1952. else {
  1953. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  1954. return regularBatch[regularBatch.length-1]
  1955. }
  1956. })
  1957. }
  1958. initTask(task)
  1959. if(repodef.requiresElevation) {
  1960. console.dir(cmd)
  1961. task.selectedinstance = selectedinstance // { root : repodef.repodir }
  1962. task.args = [cmd[0], [cmd[1].join(' ')], cmd[2]]
  1963. console.dir(task.args)
  1964. elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
  1965. return elevatedBatch[elevatedBatch.length-1]
  1966. }
  1967. else {
  1968. regularBatch.push(shell_verse.getNonElevatedTask( task ))
  1969. return regularBatch[regularBatch.length-1]
  1970. }
  1971. }
  1972. }
  1973. return GITSHELL
  1974. })()
  1975. shell_verse.cmds = cmds;
  1976. shell_verse.generateDependencies()
  1977. console.dir(Object.keys(shell_verse.cmds))
  1978. // ---------------
  1979. Tasq.addlistener(statuslog.statuslog)
  1980. if(clioverrides.noprerequisites) return elxrworker(cmds)
  1981. var pending = (function() {
  1982. // PB : TODO -- Override cli prefs and call with undefined selectedinstance only if there is no cli overide or selection.
  1983. acquirelocalinstances( { root : ENV.wd } )
  1984. function createLocalChessInstance( cfg ){
  1985. // return createInstance(cfg)
  1986. reconfirm = getReconfirmAll()
  1987. var inst = {};
  1988. var __new = Object.assign({}, __default, cfg)
  1989. inst[cfg.node_env] = __new; return inst;
  1990. }
  1991. if(chessinstances.error) {
  1992. delete chessinstances.error
  1993. // use installchoices only when we don't find chessinstances.
  1994. try { var installchoices = require(path.normalize(ENV.wd + '/installchoices.js'))
  1995. var instanceName = installchoices.instanceName;
  1996. var reposerver = installchoices.reposerver
  1997. var node_env = clioverrides.node_env || installchoices.node_env
  1998. var __instance = (chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
  1999. instanceName, node_env, root, reposerver /* promptkeys['reposerver'] */ } ))[node_env];
  2000. chessinstances['current_run'] = { instanceName, node_env, reposerver, root }
  2001. // if(path.normalize(selectedinstance.root) !== path.normalize(chessinstances[selectedinstance.instanceName][selectedinstance.node_env].root)) {
  2002. // 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
  2003. // }
  2004. // chessinstances[installchoices.instanceName] = chessinstances[installchoices.instanceName] || {}
  2005. // chessinstances[installchoices.instanceName][installchoices.node_env || clioverrides.node_env] = installchoices
  2006. __instance.username = installchoices.username = installchoices.gitUser
  2007. __instance.email = installchoices.email = installchoices.gitEmail
  2008. }
  2009. catch(e){
  2010. console.warn(e)
  2011. console.warn( 'Install choices not found. WIll prompt for choices' ) // This is not an error. A new fresh instance is probably being setup.
  2012. throw 'PROMPT FOR INSTLL CHOICES TO BE IMPLEMENTED'
  2013. // chessinstances[installchoices.instanceName] = chessinstances[installchoices.instanceName] || {}
  2014. // chessinstances[installchoices.instanceName][installchoices.node_env || clioverrides.node_env] = installchoices
  2015. }
  2016. }
  2017. // PB : chessinstances.js update if we are switching repo servers, username etc... Myabe always refresh on each run.
  2018. // root location for instance swithc ?? should not be allowd...
  2019. var instanceName = clioverrides.instanceName || chessinstances.current_run.instanceName
  2020. var instance = {}
  2021. function oninstanceName(instanceName) {
  2022. var instance_ = chessinstances[instanceName]
  2023. if(instance_) {
  2024. instance = instance_[clioverrides.node_env || chessinstances.current_run.node_env] || utils.assign(chessinstances['current_run'], clioverrides, { instanceName })
  2025. }
  2026. else instance = utils.assign(chessinstances['current_run'], clioverrides, { instanceName })
  2027. // PB : TODO We should promt like instanceName create a new one instad of undefined ??
  2028. return instance
  2029. }
  2030. if(!instanceName) {
  2031. var interactionpoints = (function() { return { instanceName : get_interactionpoints_template.bind({target : {}, choices : {}})()['instanceName'] } })()
  2032. var eachPrompt = getBoundEachPrompt(instance, utils.assign({}, interactionpoints), interactionpoints, {})
  2033. var pendingtasks = any( Object.keys(interactionpoints).reduce(eachPrompt, []) ).then(()=>{
  2034. return oninstanceName(instance.instanceName)
  2035. })
  2036. }
  2037. else {
  2038. var pendingtasks = Promise.resolve(oninstanceName(instanceName))
  2039. }
  2040. return pendingtasks.then((instance)=>{
  2041. // PB : TODO -- Embed defaults in the build instead of inlining here...
  2042. // PB : TODO -- All these values instanceName, node_env, username, reposervers should come from instace overridden by a finalized cliovrrides...
  2043. // Also attepmt to load preconfig specially for new chessinstances from ../chess-config/...
  2044. var __repo_manifest_elxr = loadmanifest( instance.root + '/elxr'
  2045. , { username : instance.username /** ??? TODO */ , instanceName : instance.instanceName /** ??? TODO */
  2046. , node_env : clioverrides.node_env, reposerver : instance.reposerver /** ??? TODO */ } // options
  2047. )
  2048. if(__repo_manifest_elxr.error) console.log(__repo_manifest_elxr.e.message)
  2049. var instance_specific_config_manifest = loadmanifest( instance.root + `/${instance.instanceName}-config-${clioverrides.node_env}`
  2050. , { username : instance.username /** ??? TODO */ , instanceName : instance.instanceName /** ??? TODO */
  2051. , node_env : clioverrides.node_env, reposerver : instance.reposerver /** ??? TODO */ } // options
  2052. )
  2053. if(instance_specific_config_manifest.error) console.log(instance_specific_config_manifest.e.message)
  2054. delete __repo_manifest_elxr.error
  2055. delete __repo_manifest_elxr.e
  2056. // delete __repo_manifest_elxr.utils
  2057. delete instance_specific_config_manifest.error
  2058. delete instance_specific_config_manifest.e
  2059. // delete instance_specific_config_manifest.utils
  2060. // selectedinstance is not complete until we load in the following order of priority...
  2061. // 1) inline defaults
  2062. // 2) elxr defaults & manifest
  2063. // 3) ../chess-config/... defaults TODO
  2064. // 4) local cached lastrun or cli selected instance from chessinstances
  2065. // 5) instance specific manifest from {{instanceName}}-config-{{node_env}} ( can work with stale or on demand currently pulled updated version )
  2066. // 5.5) runconfig ??? lastrun vs fixed runconfig for repetitive stuff. TODO -- runconfig overrides lastrun...
  2067. // 6) cli overrides from command promnt
  2068. // 7) promted selections and reconfirms.
  2069. var __pvt = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  2070. , __default, __repo_manifest_elxr, instance
  2071. , { root : ENV.wd, node_env : ENV.NODE_ENV
  2072. , get instanceName() {
  2073. // FInalize to prevent subsequent overrides...
  2074. return instance.instanceName
  2075. }
  2076. }
  2077. , instance_specific_config_manifest
  2078. , clioverrides
  2079. )
  2080. // console.dir(__pvt)
  2081. // Unmergable server overrides
  2082. Object.keys(instance_specific_config_manifest).forEach( key => {
  2083. __pvt[key] = instance_specific_config_manifest[key]
  2084. })
  2085. var __pub = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }, {}, __pvt
  2086. // Finalized immutables.
  2087. // We don't need pub to prevent immutability.
  2088. , { get root(){ return __pvt.root }
  2089. , get node_env(){ return __pvt.node_env }
  2090. , get instanceName() { return __pvt.instanceName }
  2091. , get reposindexed(){
  2092. // PB : TODO -- Implement -- One time gettor and then cached...
  2093. var indexed = {}
  2094. this.repos.forEach(r => { indexed[r.repo] = r })
  2095. this.elevated.forEach(r => { indexed[r.repo] = r })
  2096. Object.defineProperty(this, 'reposindexed', { value: indexed, writable: false });
  2097. return indexed;
  2098. }
  2099. , set root(val){
  2100. throw 'root changes not yet supported'
  2101. // if the root changes while we r invoked from somewhere else... we need to reload everything from that location...
  2102. if(__pvt.root === val){
  2103. return __pvt.root = val
  2104. }
  2105. else __pvt.root
  2106. }
  2107. }
  2108. )
  2109. chessinstances[__pub.instanceName] = chessinstances[__pub.instanceName] || {}
  2110. chessinstances[__pub.instanceName][__pub.instanceType] = __pub
  2111. // PB : TODO initinstances is now obselete relocated here
  2112. // Upgrade old formats..
  2113. if(__pub?.repos && !__pub?.repos[0]?.repo) {
  2114. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  2115. __pub.repos = __pub.repos.map(function(repo){ return { repo } })
  2116. }
  2117. if(__pub?.elevated && !__pub?.elevated[0]?.repo) {
  2118. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  2119. __pub.elevated = __pub.elevated.map(function(repo){ return { repo } })
  2120. }
  2121. // Config from server always override merges into selection except for the current selection.
  2122. // PB : TODO -- utils.assign Array merges are non-distinct...
  2123. // chessinstances[instanceName][node_env] = selectedinstance;
  2124. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  2125. // PB : TODO -- We should probably write the new server config also...
  2126. // PB : TODO -- Attempt first one that is available and online...
  2127. // PB : TODO -- system select may need a reconfirm...
  2128. if(!__pub.reposerver) reconfirm['reposerver'] = true
  2129. __pub.reposerver = __pub.reposerver || __pub.reposervers[0]
  2130. cacheWriteInstanceConfig(chessinstances, __pub.root, __pub )
  2131. Object.defineProperty(__g, 'selectedinstance', {
  2132. get(){ return __pub}
  2133. , set( inst ){
  2134. utils.assign(__pub, inst); return __pub
  2135. }
  2136. })
  2137. return __pub;
  2138. })
  2139. })()
  2140. return pending.then(( selectedinstance)=>{
  2141. // PB : TODO -- Maybe create a new instance so we can switch around for different values...
  2142. shell_verse.init({ statuslog, selectedinstance, processedArgs, runtimestamp, ENV })
  2143. shell_verse.cmds = cmds;
  2144. // Instead of waiting for the root to be establised we start working at the current locatoin and then relocate when root changes.
  2145. runlogjson = `${selectedinstance.root}/.elxr/run-${runtimestamp}/run.log`
  2146. ensureDirectoryExistence(runlogjson)
  2147. fs.writeFileSync(runlogjson, JSON.stringify( { message : `Started ${runtimestamp}`, success:true})) // Initialize a new log file with "logrotate" for every run
  2148. Tasq.addlistener((e)=>{ fs.writeFileSync(runlogjson, ', ' + JSON.stringify( e ), { 'flag': 'a+' }) })
  2149. var chalk = require('chalk')
  2150. const homedir = require('os').homedir();
  2151. function sysAddPathVar(addpath){
  2152. // Object.assign({
  2153. // inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  2154. // }, options)
  2155. // powershell $env:Path -split ';'
  2156. var etask = ()=>{
  2157. return nodeShellExec('Powershell.exe', [
  2158. `$path = [Environment]::GetEnvironmentVariable('PATH', 'Machine')
  2159. $newpath = $path + ';${addpath}'
  2160. [Environment]::SetEnvironmentVariable("PATH", $newpath, 'Machine')`
  2161. ]).then(() => {
  2162. fs.writeFileSync('run.done', 'success') // PB : TODO -- IPC through files is needed only for windows.
  2163. }).catch(() => {
  2164. fs.writeFileSync('run.done', 'error')
  2165. })
  2166. }
  2167. etask.statuslog = statuslog
  2168. etask.selectedinstance = selectedinstance
  2169. etask.processedArgs = processedArgs
  2170. etask.runtimestamp = runtimestamp
  2171. etask.ENV = ENV
  2172. return shell_verse.runElevated(etask)
  2173. // var newpath = addpath.split(';');
  2174. // newpath.push(addpath)
  2175. // newpath = Array.from(new Set(newpath)).join(';')
  2176. // // addpath.split(';').forEach(pel => { var kv = pel.split('='); kv[0] === key ? null : newpath.push(pel); } )
  2177. // // setx /M PATH "%PATH%;<path-to-executable-folder>"
  2178. // // %AppData%\npm
  2179. // return nodeShellExec('setx', ['/m', 'PATH', `%PATH%;${addpath}` ]);
  2180. }
  2181. // singleton one time lazy
  2182. var getCredentials = function(){
  2183. // try {
  2184. // First call
  2185. var creds = fs.readFileSync(path.normalize(`${homedir}/.elxrcredentials`), { encoding: 'utf8' });
  2186. var creds = creds.split('\n').map( c => c.trim() && new URL(c));
  2187. console.log(creds);
  2188. creds.forEach(cred => {console.log( cred.hostname ); console.log( cred.username )} );
  2189. // }
  2190. // catch(e){
  2191. // console.warn('Credentials not cached. You will be prompted for username and password.')
  2192. // }
  2193. // Subsequent calls
  2194. getCredentials = ()=>{ return creds }
  2195. return getCredentials();
  2196. }
  2197. // console.dir(processedArgs)
  2198. // PB : TODO -- defaults for valuless arguments if passed.
  2199. // Object.keys(processedArgs).forEach(a=>{
  2200. // if(Object.prototype.toString.call(processedArgs[a]) === '[object Undefined]' || !processedArgs[a]) || trim(processedArgs[a])) == '') {
  2201. // }
  2202. // })
  2203. const { readdir } = require("fs").promises
  2204. // Directory shallow walk and do perform on each dir.
  2205. const dirs = async (perform, src, target, options) => {
  2206. var rs = []
  2207. for (const dir of await readdir(src || selectedinstance.root, { withFileTypes: true })) {
  2208. if (dir.isDirectory()) rs.push( perform(dir, src, target, options) )
  2209. }
  2210. return any(rs)
  2211. }
  2212. var fsMove = async function(from, to, options) {
  2213. if(!options?.innernode) {
  2214. var exists = fs.existsSync(from);
  2215. var stats = exists && fs.statSync(from);
  2216. var isDirectory = exists && stats.isDirectory();
  2217. }
  2218. else {
  2219. var isDirectory = options.innernode.isDirectory()
  2220. }
  2221. if(!isDirectory) return fs.renameSync(from, to)
  2222. fs.mkdirSync(to, { recursive : true })
  2223. var rs = [];
  2224. for (const innernode of await readdir(from, { withFileTypes: true })) {
  2225. rs.push( fsMove( path.join(from, innernode.name), path.join(to, innernode.name), { innernode } ) )
  2226. }
  2227. return any(rs)
  2228. };
  2229. // PB : TODO -- Should return a bunch of promises to wait for...
  2230. var copyrecursive = async function(src, target, options) {
  2231. if(!options?.innernode) {
  2232. var exists = fs.existsSync(src);
  2233. var stats = exists && fs.statSync(src);
  2234. var isDirectory = exists && stats.isDirectory();
  2235. }
  2236. else {
  2237. var isDirectory = options.innernode.isDirectory()
  2238. }
  2239. if(!isDirectory) return fs.copyFileSync(src, target)
  2240. fs.mkdirSync(target, { recursive : true })
  2241. var rs = [];
  2242. for (const innernode of await readdir(src, { withFileTypes: true })) {
  2243. rs.push( copyrecursive( path.join(src, innernode.name), path.join(target, innernode.name), { innernode } )
  2244. // .then(()=>{
  2245. // return any(actions.map( a => ()=>a(dir, { isDirectory : true}) ))
  2246. // })
  2247. )
  2248. }
  2249. return any(rs)
  2250. // return fswalk( src, {}, [
  2251. // (src, options)=> {
  2252. // if(options.innernode.isDirectory()) fs.mkdirSync(options.target, { recursive : true })
  2253. // else fs.copyFileSync(src, options.target)
  2254. // }
  2255. // ])
  2256. // var exists = fs.existsSync(src);
  2257. // var stats = exists && fs.statSync(src);
  2258. // var isDirectory = exists && stats.isDirectory();
  2259. // if (isDirectory) {
  2260. // fs.mkdirSync(dest, { recursive : true });
  2261. // return dirs( function(childItemName) {
  2262. // return copyrecursive(path.join(src, childItemName.name),
  2263. // path.join(dest, childItemName.name));
  2264. // }, src )
  2265. // } else {
  2266. // fs.copyFileSync(src, dest);
  2267. // }
  2268. };
  2269. // var renamerecursive = function(from, to){
  2270. // var exists = fs.existsSync(from);
  2271. // var stats = exists && fs.statSync(from);
  2272. // var isDirectory = exists && stats.isDirectory();
  2273. // if (isDirectory) {
  2274. // fs.mkdirSync(to);
  2275. // dirs( function(childItemName) {
  2276. // renamerecursive(path.join(from, childItemName),
  2277. // path.join(to, childItemName));
  2278. // }, from )
  2279. // // fs.readdirSync(from).forEach(function(childItemName) {
  2280. // // copyrecursive(path.join(from, childItemName),
  2281. // // path.join(to, childItemName));
  2282. // // });
  2283. // } else {
  2284. // fsrename(from, to);
  2285. // }
  2286. // }
  2287. // filesystem walk
  2288. const fswalk = async (pathToWalk, options, actions) => {
  2289. // options = options || { depthfirst : true }
  2290. if(!options.innernode) {
  2291. var exists = fs.existsSync(pathToWalk);
  2292. var stats = exists && fs.statSync(pathToWalk);
  2293. var isDirectory = exists && stats.isDirectory();
  2294. }
  2295. else {
  2296. var isDirectory = options.innernode.isDirectory()
  2297. }
  2298. if(!isDirectory) return any(actions.map( a => ()=>a( pathToWalk, utils.assign({}, options
  2299. , { pathToWalk, innernode : options.innernode || { isDirectory : function(){ return true } } }) ) ))
  2300. var rs = [];
  2301. for (const innernode of await readdir(pathToWalk, { withFileTypes: true })) {
  2302. rs.push( fswalk( path.join(pathToWalk, innernode.name), utils.assign({}, options, {pathToWalk, innernode }), actions )
  2303. // .then(()=>{
  2304. // return any(actions.map( a => ()=>a(innernode, { isDirectory : true}) ))
  2305. // })
  2306. )
  2307. }
  2308. // Wait for the walk to complete before renaming directories.
  2309. Array.prototype.push.apply(rs, actions.map( a => ()=>a( pathToWalk, utils.assign({}, options
  2310. , { pathToWalk, innernode : options.innernode || { isDirectory : function(){ return true } } } ) ) ))
  2311. return any(rs)
  2312. }
  2313. var fsrecurse = function(target, options, actions, root) {
  2314. var exists = fs.existsSync(target);
  2315. var stats = exists && fs.statSync(target);
  2316. var isDirectory = exists && stats.isDirectory();
  2317. if (isDirectory) {
  2318. var tasks = []
  2319. tasks.push( dirs( function(childItemName) {
  2320. return fsrecurse(path.join(target, childItemName.name)
  2321. , options, actions, root);
  2322. }, target ))
  2323. return any(tasks)
  2324. } else {
  2325. var prevActionResult = null;
  2326. return any( actions.map( (action) => prevActionResult = action.apply(null, target, options) ))
  2327. }
  2328. };
  2329. // var fslink = function(to, options){ try { fs.linkSync( to, options.from ) } catch(e) { throw e } }
  2330. var fslink = function(to, options){ fs.symlinkSync( to, options.from /*, type = "junction"*/ ) }
  2331. var fsrename = function(target, options){
  2332. // PB : TODO -- streaming and async.. target could be a stream a string or a filesystem item or a tree node...
  2333. var targetname = options.innernode?.name || path.parse(target).base;
  2334. var replaced = targetname;
  2335. options.patternsubstitutions.forEach( ps => { replaced = regexreplaceall( replaced, ps ) })
  2336. if(replaced && replaced !== targetname) {
  2337. var tr = target.replace( targetname, replaced )
  2338. fs.renameSync(target, tr)
  2339. return tr;
  2340. }
  2341. else return replaced
  2342. }
  2343. var fscontentreplace = function( target, options ){
  2344. // do many replacements in one shot in the file.
  2345. if(options.processingtype === 'inplace' && options.sourcetype === 'filesystem' && !options.innernode.isDirectory() ) {
  2346. var content = fs.readFileSync(target, { encoding: 'utf8' }) // PB : TODO -- streaming and async..
  2347. options.patternsubstitutions.forEach( ps => { content = regexreplaceall( content, ps ) })
  2348. fs.writeFileSync(target, content)
  2349. }
  2350. }
  2351. var templatelink = function(target, options){
  2352. var targetSubPath = target.replace(options.workingtarget + '/', '' );
  2353. var targetSubPathsplit = targetSubPath.split("/")
  2354. var targetPathBaseDir = `${targetSubPathsplit[0]}/${targetSubPathsplit[1]}`
  2355. var linkToSubPathReplacement = `${options.base}-server-lib/common`
  2356. // var rgxp = new RegExp(`(__link__)${options.base}-server-lib`, "g")
  2357. var rgxp = new RegExp(`(__link__${options.base}-server-lib)`, "g")
  2358. var linkToSubPath = targetSubPath
  2359. var b = target.match(rgxp)
  2360. var linkFromName = regexreplaceall( target, { strOrregexp : rgxp, substitutes : [ '' ] } )
  2361. linkFromName = linkFromName.replace(options.workingtarget, options.destinationroot)
  2362. if( b ) {
  2363. // Only if the pattern matches which is link instruction.
  2364. linkToSubPath = regexreplaceall( linkToSubPath, { strOrregexp : rgxp, substitutes : [ '' ] } )
  2365. }
  2366. options.patternsubstitutions.forEach( ps => { linkToSubPath = regexreplaceall( linkToSubPath, ps ) })
  2367. var linkToName = `${options.destinationroot}/${linkToSubPath}`
  2368. if(b){
  2369. linkToSubPath = linkToSubPath.replace( targetPathBaseDir, linkToSubPathReplacement)
  2370. // PB : DONT DELETE EVERYTHING ??? Only the linkable ones... Or use an add strategy without deleting...
  2371. fs.unlinkSync( target );
  2372. fslink( `${options.destinationroot}/${linkToSubPath}`, { from : linkFromName } )
  2373. }
  2374. else {
  2375. fsMove( `${options.workingtarget}/${linkToSubPath}`, linkToName )
  2376. // fsMove( `${options.workingtarget}/${linkToSubPath}`, linkFromName )
  2377. }
  2378. }
  2379. // Source and Target are files or folders. We need another version or a unifed version for strings..
  2380. var processpatterns = function(target, options){
  2381. // Accept a set of patterns and substitutions and operate on a target and apply all patterns substitutions.
  2382. // options = options || { targettype : 'inplace', sourcetype : 'filesystem' }
  2383. // options.source, options.target sourcetype = 'string' | 'filesystem' options.targettype = 'inplace' | 'copy'
  2384. if(options.processingtype === 'inplace' && options.sourcetype === 'filesystem' ) {
  2385. options.patternsubstitutions.forEach( ps => {
  2386. // var replacement = regexreplaceall( from, ps.strOrregexp, ps.substitutes )
  2387. // if(targetname) { // Porcess all files. Even if file names dont have patterns the content needs to be replaced.
  2388. return options.tasks.map( t => { return t( target, ps ) } )
  2389. // }
  2390. // return str.replace(regex, function(match, key) {
  2391. // console.log(`Found match, group ${match}: ${key}`);
  2392. // return substitutes[key] || match;
  2393. // })
  2394. })
  2395. }
  2396. // while ((m = regex.exec(str)) !== null) {
  2397. // // This is necessary to avoid infinite loops with zero-width matches
  2398. // if (m.index === regex.lastIndex) {
  2399. // regex.lastIndex++;
  2400. // }
  2401. // var rstr = str;
  2402. // // The result can be accessed through the `m`-variable.
  2403. // m.forEach((match, groupIndex) => {
  2404. // // rstr = rstr.replace( groupIndex
  2405. // console.log(`Found match, group ${groupIndex}: ${match}`);
  2406. // if(groupIndex === 0) return
  2407. // });
  2408. // }
  2409. }
  2410. function copyFileSync( source, target , options) {
  2411. var targetFile = target;
  2412. // If target is a directory, a new file with the same name will be created
  2413. if ( fs.existsSync( target ) ) {
  2414. if ( fs.lstatSync( target ).isDirectory() ) {
  2415. targetFile = path.join( target, path.basename( source ) );
  2416. }
  2417. }
  2418. fs.writeFileSync(targetFile, fs.readFileSync(source));
  2419. }
  2420. function copyFolderRecursiveSync( source, target, options ) {
  2421. var files = [];
  2422. // Check if folder needs to be created or integrated
  2423. var targetfolder = path.join( target, path.basename( source ) );
  2424. if ( !fs.existsSync( targetfolder ) ) {
  2425. fs.mkdirSync( targetfolder );
  2426. }
  2427. // Copy
  2428. if ( fs.lstatSync( source ).isDirectory() ) {
  2429. files = fs.readdirSync( source );
  2430. files.forEach( function ( file ) {
  2431. var curSource = path.join( source, file );
  2432. if ( fs.lstatSync( curSource ).isDirectory() ) {
  2433. copyFolderRecursiveSync( curSource, targetfolder );
  2434. } else {
  2435. copyFileSync( curSource, targetfolder );
  2436. }
  2437. } );
  2438. }
  2439. }
  2440. var callshelltask = (args) => {
  2441. // console.dir(args)
  2442. if( Object.prototype.toString.call(args) === '[object Function]' ) {
  2443. return args;
  2444. }
  2445. return getshelltask(args)()
  2446. }
  2447. var getnodeshellexectask = (args) => { return () => { return nodeShellExec.apply(null, args) }}
  2448. var perform = function( serailtasks, taskvector ){ return any( serailtasks(taskvector).map(getnodeshellexectask)) }
  2449. var getTaskCheckExists = shell_verse.getTaskCheckExists
  2450. // var getTaskWithElevation = function(tasdef){ return shell_verse.getElevatedTask( tasdef.elevatedpulltasks ) }
  2451. // var getTaskWithoutElevation = function(tasdef){
  2452. // return ()=>{
  2453. // if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  2454. // else Promise.resolve(true)
  2455. // }
  2456. // }
  2457. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current GITEA username
  2458. var elevatedRunasRepos = null
  2459. var gitRepos = null
  2460. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  2461. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  2462. var dbForLabel = function (label) {
  2463. var dbsForLabel = {
  2464. devmysql: 'mysql'
  2465. , development: 'mssql'
  2466. , production: 'mssql'
  2467. }
  2468. return dbsForLabel[label] || 'mysql'
  2469. }
  2470. // Maps an environment to a branch. Not required if the branch is appropriately named.
  2471. var checkoutMap = { 'development': 'master' }
  2472. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  2473. // Relevant git repos
  2474. var exludeMergeRepos = [];
  2475. var useGitPull = processedArgs.useGitPull || false;
  2476. var configPromise = null
  2477. var reconfirmcmds = { create : true }
  2478. var independentcmd = function(){
  2479. return false;
  2480. }
  2481. function preworkerconfig(){
  2482. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  2483. gitRepos = selectedinstance.repos
  2484. // gitRepos = ['chess-server-lib'];
  2485. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  2486. elevatedRunasRepos = selectedinstance.elevated
  2487. // Repos that should excluded from merge for releases...
  2488. exludeMergeRepos = selectedinstance.exludeMergeRepos
  2489. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  2490. // mysql -u root -p db_name < drop_all_tables.sql
  2491. var mysql = '../xampp/mysql/bin/mysql'
  2492. var mysqldump = '../xampp/mysql/bin/mysqldump'
  2493. }
  2494. // function acquireChoices(selectedinstance) {
  2495. // var hasconfig = false;
  2496. // console.warn(chalk.cyan(`
  2497. // -------------------------------------------------------------------------------
  2498. // Could not locate your preferred configuration (you may not specified it)
  2499. // You should fork the default chess configuration to customize and make it
  2500. // your own instance with a named config as
  2501. // {{yourowninstancename}}-config-{{yourchosenenvironment}}
  2502. // And then run this tool as follows
  2503. // NODE_ENV={{yourchosenenvironment}} elxr i {{yourowninstancename}}
  2504. // OR
  2505. // Run this tool with the following command to use a quick start default.
  2506. // elxr --default
  2507. // OR
  2508. // Choose one of the options below to run interactively.
  2509. // We will run your choice at the next prompt.
  2510. // -------------------------------------------------------------------------------
  2511. // `))
  2512. // var choices = getInteractionPoints(detectedinstanceoptions, __interactive_prompts)
  2513. // var todo = any( __interactive_prompts(selectedinstance, choices) ).then(()=>{
  2514. // return initinstances(selectedinstance)
  2515. // })
  2516. // // var prompt = cli.prompter;
  2517. // // return prompt.ask(`Choose an option :
  2518. // // d) Install the default chess instance.
  2519. // // => elxr i chess node_env=development --default
  2520. // // n) Create your custom new instance interactively
  2521. // // => elxr i {{instanceName}} node_env={{environment}}
  2522. // // i) Choose an instance and environment to install
  2523. // // => elxr i {{instanceName}} node_env={{environment}}
  2524. // // c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  2525. // // => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  2526. // // h) Help
  2527. // // q) Quit
  2528. // // Default <= d
  2529. // // : `).then((choice) => {
  2530. // // if (choice && choice === 'd' || !choice) {
  2531. // // processedArgs._[0] = 'i'
  2532. // // selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  2533. // // selectedinstance.node_env = processedArgs.node_env = (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  2534. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  2535. // // }
  2536. // // else if (choice === 'h') {
  2537. // // processedArgs._[0] = 'h'
  2538. // // fs.writeFileSync('run.done', 'noop help');
  2539. // // console.log(elxr.help()); process.exit()
  2540. // // }
  2541. // // else if (choice === 'n' || choice === 'i') {
  2542. // // var p1 = cli.prompter;
  2543. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  2544. // // processedArgs._[0] = 'i'
  2545. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  2546. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  2547. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  2548. // // if (choice === 'n') {
  2549. // // selectedinstance.reposerver = 'https://git.bbh.org.in'
  2550. // // console.warn(
  2551. // // chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  2552. // // process.exit();
  2553. // // }
  2554. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  2555. // // selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  2556. // // })
  2557. // // })
  2558. // // })
  2559. // // } else if (choice === 'c') {
  2560. // // var p1 = cli.prompter;
  2561. // // return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  2562. // // selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  2563. // // return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  2564. // // selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  2565. // // return p1.ask(`Enter cmd :
  2566. // // p) pull
  2567. // // Default <= p
  2568. // // : `).then(function (cmd) {
  2569. // // if (!cmd || cmd === 'p') {
  2570. // // processedArgs._[0] = 'pull'
  2571. // // }
  2572. // // else processedArgs._[0] = cmd
  2573. // // return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  2574. // // selectedinstance.reposerver = reposerver || selectedinstance.reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  2575. // // })
  2576. // // })
  2577. // // })
  2578. // // })
  2579. // // } else {
  2580. // // 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.`));
  2581. // // fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  2582. // // fs.writeFileSync('run.done', 'noop quit');
  2583. // // process.exit()
  2584. // // }
  2585. // // })
  2586. // }
  2587. var os = require("os");
  2588. var hostname = os.hostname();
  2589. var clustername = null; // PB : TODO -- Prompt to acquire.
  2590. var configs = (function(){
  2591. // We need to discover and use the most specialized config available.
  2592. // Two passes are required as the config currently cloned may be switched by the discovery.
  2593. // If the repo name is the same but has different remotes the newly acquired config from multiple remotes may
  2594. // iteself redefine the remotes, repos and servers for the config which we need to honor..
  2595. return {
  2596. ownerClusterNodeConfig(selected) {
  2597. // Hostname and therefore clusternodename can be anything and can participate in many clusters.
  2598. // 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 )
  2599. var clusternodename = hostname || `CHESS0001${selected.username}`; // Cluster node names need to be unique accross all clusters to avoid collitions.
  2600. clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
  2601. return __acquireConfig(selected, { remote : 'userfork' } // PB : TODO -- accessiblity state should switch to public etc..
  2602. , selected.instanceName + '-config-' + selected.node_env + `-${clusternodename}`
  2603. , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
  2604. e.benign = true
  2605. return e; }
  2606. )
  2607. }
  2608. , ownerInstnace(selected) { return __acquireConfig(selected, { remote : 'userfork' }
  2609. , selected.instanceName + '-config-' + selected.node_env
  2610. , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
  2611. e.benign = true
  2612. return e }
  2613. )
  2614. }
  2615. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  2616. , commonInstance(selected) { return __acquireConfig(selected, { owner : defaultowner }
  2617. , undefined
  2618. , function(e){
  2619. // PB : TODO -- console.info('This is probably an error unless the user is asking to create a new instance with this name.')
  2620. statuslog.statuslog(e, e)
  2621. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  2622. utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  2623. , selectedinstance, require(manifestpath)( {utils}, null, { username : selectedinstance.username, instanceName : selectedinstance.instanceName
  2624. , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' } ))
  2625. console.dir(selectedinstance.repos)
  2626. // Config from server always override merges into selection except for the current selection.
  2627. // PB : TODO -- utils.assign Array merges are non-distinct...
  2628. if(selectedinstance?.repos && !selectedinstance.repos[0].repo) {
  2629. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  2630. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  2631. }
  2632. if(selectedinstance?.elevated && !selectedinstance.elevated[0]?.repo) {
  2633. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  2634. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  2635. }
  2636. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  2637. , selected, selectedinstance)
  2638. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  2639. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  2640. cacheWriteInstanceConfig(chessinstances, selectedinstance.root, selectedinstance)
  2641. // ENV.NODE_ENV = selectedinstance.node_env;
  2642. throw e
  2643. }
  2644. ) }
  2645. // , genericChessInstance(selected) { return __acquireConfig(selected, { owner : defaultowner }) }
  2646. }
  2647. })()
  2648. var eNotImplemented = function(){
  2649. console.error('Not yet implemented')
  2650. process.exit()
  2651. }
  2652. // PB : TODO -- accept additional arg - an array specifying custom configPriority.
  2653. var acquireConfig = function(slections){
  2654. var configPriority = [ 'ownerClusterNodeConfig', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  2655. return any(configPriority.map(cfg => { return function() { return configs[cfg](slections) } } ), true, true).then(()=>{
  2656. return acquireData(slections)
  2657. })
  2658. }
  2659. var instanceData = (function(){
  2660. return {
  2661. ownerClusterNodeData(selected) {
  2662. var clusternodename = hostname || `CHESS0001${selected.username}`; // Cluster node names need to be unique accross all clusters to avoid collitions.
  2663. clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
  2664. return __acquireData(selected, { remote : 'userfork' }
  2665. , selected.instanceName + '-data-' + selected.node_env + `-${clusternodename}`
  2666. , function(e){ console.info('Customized node level data not found. This is not an Error. Will attempt with owner level config.');
  2667. e.benign = true
  2668. return e; }
  2669. )
  2670. }
  2671. , ownerInstnace(selected) { return __acquireData(selected, { remote : 'userfork' }
  2672. , selected.instanceName + '-data-' + selected.node_env
  2673. , function(e){ console.info('Customized user level data not found. This is not an Error. Will attempt global common instance config.');
  2674. e.benign = true
  2675. return e }
  2676. )
  2677. }
  2678. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  2679. , commonInstance(selected) { return __acquireData(selected, { owner : defaultowner }
  2680. // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
  2681. ) }
  2682. , genericChessInstance(selected) { return __acquireData(selected, { owner : defaultowner }) }
  2683. }
  2684. })()
  2685. var acquireData = function(slections){
  2686. var configPriority = [ 'ownerClusterNodeData', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  2687. return any(configPriority.map(cfg => { return function() { return instanceData[cfg](slections) } } ), true, true)
  2688. }
  2689. var createTasq = (args, shellT, onEachError) => {
  2690. var tasq = shellT ? shellT(args) : (() => { return nodeShellExec.apply(null, args).catch( onEachError || function(e){ console.error(e) } ) })
  2691. tasq.toString = function(){ return JSON.stringify(args)}
  2692. return tasq;
  2693. }
  2694. var execserial = function(tasklist, task, shellT){
  2695. var exec = (taskArgs)=>{
  2696. var thistask = task.concat();
  2697. thistask[1] = thistask[1].concat()
  2698. thistask[1].push.apply(thistask[1], taskArgs)
  2699. return createTasq(thistask, shellT)
  2700. }
  2701. return any(tasklist.map(exec))
  2702. }
  2703. var execonce = function(taskArgs, task){ return any([task[1].push.apply(task[1], taskArgs)].map(createTasq)) }
  2704. var __acquireConfig = function (selected, options, configrepo, errHandler) {
  2705. configrepo = configrepo || selected.instanceName + '-config-' + selected.node_env;
  2706. var owner = options.owner || selected.username || options.defaultowner // getowner(repodef, remote) //
  2707. var errorHandler = (e) => {
  2708. 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`))){
  2709. // console.error('Could not connect to repo server. Timed Out')
  2710. 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 => {
  2711. if(propValue === 'y') {
  2712. reconfirm = getReconfirmAll()
  2713. return startElxr()
  2714. }
  2715. else if(propValue === 'r'){
  2716. return acquireConfig(selected)
  2717. }
  2718. else process.exit()
  2719. })
  2720. }
  2721. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${owner}/${configrepo}.git/' not found`))){
  2722. var choices = {
  2723. t : `install a new temporary local instance with this name ( will not persist ).
  2724. Use your own username for additional options. You can request for a username at chess@bbh.org.in )`
  2725. , e : 'exit' }
  2726. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  2727. choices = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  2728. , {
  2729. i : 'create a new instance with this name => will fork the default config under your username'
  2730. , f : 'fork a new instance with this name for yourself for this node from another instance'
  2731. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  2732. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  2733. , p : 'create a custom config for yourself '
  2734. }, choices)
  2735. }
  2736. return cli.prompt( choices
  2737. , 'Config for instance not found. Would you like to ', 'e' ).then(propValue => {
  2738. if(propValue === 't') {
  2739. selectedinstance.local = true; return createInstance(selectedinstance)
  2740. }
  2741. if(propValue === 'i') return eNotImplemented()
  2742. if(propValue === 'f') return eNotImplemented()
  2743. if(propValue === 'o') return eNotImplemented()
  2744. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  2745. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  2746. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  2747. else process.exit()
  2748. })
  2749. }
  2750. console.warn(e)
  2751. throw e; //('Config acquisition failed.')
  2752. }
  2753. var successHandler = () => {
  2754. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  2755. utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  2756. , selectedinstance, require(manifestpath)( {utils}, null, { username : selectedinstance.username, instanceName : selectedinstance.instanceName
  2757. , node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver }))
  2758. console.dir(selectedinstance.repos)
  2759. // Config from server always override merges into selection except for the current selection.
  2760. // PB : TODO -- utils.assign Array merges are non-distinct...
  2761. if(!selectedinstance.repos[0].repo) {
  2762. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  2763. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  2764. }
  2765. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  2766. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  2767. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  2768. }
  2769. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  2770. , selected, selectedinstance)
  2771. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  2772. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  2773. cacheWriteInstanceConfig(chessinstances, selectedinstance.root)
  2774. ENV.NODE_ENV = selectedinstance.node_env;
  2775. }
  2776. return performPullOrClone( selected.reposindexed[configrepo] || { repo : configrepo }
  2777. , null, owner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  2778. .catch( (e)=>{
  2779. // if(e){
  2780. if(Promise.resolve(e) === e) return e;
  2781. // console.error(e)
  2782. e.benign = true;
  2783. throw e; // Not a hard error but we need this for bcontinueonfailure as we still want to stop on firstsuccess.
  2784. // }
  2785. })
  2786. }
  2787. var __acquireData = function (selected, options, datarepo, errHandler) {
  2788. datarepo = datarepo || selected.instanceName + '-data';
  2789. var owner = options.owner || selected.username || options.defaultowner //getowner(repodef, remote) //
  2790. var errorHandler = (e) => {
  2791. 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`))){
  2792. // console.error('Could not connect to repo server. Timed Out')
  2793. 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 => {
  2794. if(propValue === 'y') {
  2795. reconfirm = getReconfirmAll()
  2796. return startElxr()
  2797. }
  2798. else if(propValue === 'r'){
  2799. return acquireConfig(selected)
  2800. }
  2801. else process.exit()
  2802. })
  2803. }
  2804. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${owner}/${datarepo}.git/' not found`))){
  2805. var choices = {
  2806. t : `install a temporary local data folder.
  2807. For more options. Request and use a personal username at chess@bbh.org.in )`
  2808. , e : 'exit' }
  2809. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  2810. choices = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  2811. , {
  2812. i : 'create a new instance with this name => will fork the default config under your username'
  2813. , f : 'fork a new instance with this name for yourself for this node from another instance'
  2814. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  2815. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  2816. , p : 'create a custom config for yourself '
  2817. }, choices)
  2818. }
  2819. return cli.prompt( choices
  2820. , 'Data repo for instance not found. Would you like to ', 'e' ).then(propValue => {
  2821. if(propValue === 't') {
  2822. selectedinstance.local = true; return createInstanceData(selectedinstance)
  2823. }
  2824. if(propValue === 'i') return eNotImplemented()
  2825. if(propValue === 'f') return eNotImplemented()
  2826. if(propValue === 'o') return eNotImplemented()
  2827. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  2828. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  2829. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  2830. else process.exit()
  2831. })
  2832. }
  2833. console.warn(e)
  2834. throw e; //('Config acquisition failed.')
  2835. }
  2836. var successHandler = () => {
  2837. }
  2838. return performPullOrClone( selected.reposindexed[datarepo] || { repo : datarepo }
  2839. , null, owner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  2840. .catch( (e)=>{
  2841. // if(e){
  2842. if(Promise.resolve(e) === e) return e;
  2843. // console.error(e)
  2844. e.benign = true;
  2845. throw e; // Not a hard error but we need this for bcontinueonfailure
  2846. // }
  2847. })
  2848. }
  2849. // ----------------------------------------------------------------
  2850. // PB : TODO -- Review and obsolete...
  2851. // ----------------------------------------------------------------
  2852. // var launchpath = path.resolve(path.normalize(ENV.wd))
  2853. var launchpath = selectedinstance.root
  2854. // // we were run.
  2855. // // The easisest would be to ask for a target directory and default to current dir....
  2856. // // path.dirname(launchpath).split(path.sep).pop()
  2857. // var parent = path.dirname(launchpath);
  2858. // var pp = launchpath;
  2859. // var instancediscoverytasks = [];
  2860. // while(parent !== pp){
  2861. // instancediscoverytasks.push(
  2862. // ((pa)=>{
  2863. // var p = pa;
  2864. // return function(){
  2865. // return hasElxr(p).then((value)=>{
  2866. // if(value) return p
  2867. // // PB : TODO -- Using throw like this is not friendly with any...
  2868. // throw Object.assign( new Error('Benign Failure in Batch')
  2869. // , { value : false, benign : true });
  2870. // })
  2871. // }
  2872. // })(pp)
  2873. // )
  2874. // pp = parent;
  2875. // parent = path.dirname(parent);
  2876. // }
  2877. // var instanceroot = null
  2878. // var detectInstanceRoot = any(instancediscoverytasks, true, true).then( ir => {
  2879. // if(ir.error) { instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ; }
  2880. // else instanceroot = ir.pVal
  2881. // return instanceroot
  2882. // }).catch(()=>{
  2883. // instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
  2884. // })
  2885. // We first load the default and then override with a runconfig if it exists else we override with the interactive prompts.
  2886. // Then acquire and reload and replace this default.
  2887. var __interactive_prompts = function( target, choices, promptsfilter ){
  2888. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  2889. var interactionpoints = unbound_interactionpoints.bind({target, choices})(selectedinstance)
  2890. function getPromptKeys() {
  2891. // PB : TODO -- get interactionpoints
  2892. if(! (processedArgs.label || processedArgs._[0]) ) return Object.assign({}, interactionpoints);
  2893. return promptkeys // PB : TODO __ Convert pormptkeys to filtered interactionpoints.
  2894. }
  2895. var eachPrompt = getBoundEachPrompt( target, getPromptKeys() , interactionpoints, choices, promptsfilter)
  2896. return Object.keys(promptsfilter || interactionpoints).reduce(eachPrompt, [])
  2897. }
  2898. var downloadsdir = shell_verse.downloadsdir;
  2899. var prerequisites = [
  2900. {
  2901. shellcmd: 'git',
  2902. name : 'git',
  2903. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  2904. , installer: 'Git-2.31.0-64-bit.exe'
  2905. , installcmd: ['cmd', ['/c', 'start',
  2906. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  2907. , '/VERYSILENT'
  2908. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  2909. ]]
  2910. , preinstallsteps: function() {
  2911. var steps = [
  2912. () => {
  2913. if (!existsSync(downloadsdir + '/' + this.installer)) {
  2914. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  2915. }
  2916. else return Promise.resolve(true)
  2917. }
  2918. ]
  2919. var prompts = this.getuser(null, ()=>{
  2920. // console.log('preinstallsteps')
  2921. // var gitUser = 'guest';
  2922. // var gitEmail = 'guest@bbh.org.in';
  2923. // var prompts = [];
  2924. // prompts.push( ()=>{ return cli.prompt(choices['username'], 'git user name').then(gituser => gitUser = gituser) } )
  2925. // prompts.push( ()=>{ return cli.prompt(choices['useremail'], 'git user email').then(gitemail => gitEmail = gitemail) } )
  2926. // console.log('prompting in preinstallsteps')
  2927. // return any(prompts).then(()=>{
  2928. // var steps = [
  2929. // ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  2930. // , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  2931. // ]
  2932. // return any(steps.map(getshelltask)).then(() => {
  2933. // })
  2934. // });
  2935. return Promise.resolve(true)
  2936. })
  2937. return any([any(steps), prompts])
  2938. }
  2939. , installsteps: function () {
  2940. return any([this.installcmd].map(getshelltask))
  2941. }
  2942. , postinstallsteps: function(err, users){
  2943. return this.getuser(null, (err, data)=>{
  2944. // ignore err and proceed with data as guest.
  2945. console.dir(data)
  2946. if(data && data.length === 1 && !shouldPrompt('username', promptkeys, selectedinstance) ) {
  2947. return username = data[0];
  2948. }
  2949. data = data || ['guest']
  2950. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  2951. console.log('prompting in postinstallsteps')
  2952. var username = 'guest';
  2953. var email = 'guest@bbh.org.in';
  2954. var password = '***';
  2955. return any( getInteractionPoints([selectedinstance], promptkeys, { username, password, email}) ).then(()=>{
  2956. if(!data.find(e => e === selectedinstance.username)) {
  2957. var steps = [
  2958. ['git', ['config', '--global', '--add', 'user.name', `${username}`]]
  2959. , ['git', ['config', '--global', '--add', 'user.email', `${email}`]]
  2960. ]
  2961. return any(steps.map(getshelltask)).then(() => {
  2962. })
  2963. }
  2964. else {
  2965. return Promise.resolve(true)
  2966. }
  2967. });
  2968. })
  2969. }
  2970. , install: function () {
  2971. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  2972. }
  2973. , verifyAndInstall : function(){
  2974. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  2975. if(exists) {
  2976. // return any(['git', ['config', '--global', '-l']].map(getshelltask))
  2977. return this.postinstallsteps.bind(this)()
  2978. }
  2979. return this.install();
  2980. });
  2981. }
  2982. , getuser : function(repo, onResult){
  2983. var __onResult = onResult || function(e, data){
  2984. data = data || []
  2985. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  2986. // console.dir(choices)
  2987. return data[0]
  2988. }
  2989. var globalOrLocal = '--global';
  2990. if(repo) globalOrLocal = '--local'
  2991. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(getshelltask)).then((result)=>{
  2992. // not yet configured.
  2993. if(!result.success) return __onResult(result)
  2994. else {
  2995. var users = result.messages[0].trim().split('\n');
  2996. if(users.length === 0 ||
  2997. users.length === 1 && users[0] === 'guest') {
  2998. return __onResult(result)
  2999. }
  3000. else {
  3001. return __onResult(null, Array.from( new Set( users ) ) ); }// PB : TODO == We should probably prompt with all the users available for selection !
  3002. }
  3003. })
  3004. .catch((e)=>{
  3005. console.error(e)
  3006. return __onResult(e)
  3007. })
  3008. }
  3009. }
  3010. ,
  3011. {
  3012. shellcmd: 'node',
  3013. name : 'node',
  3014. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  3015. , installer: 'node-v14.16.0-x64.msi'
  3016. , installcmd: ['MSIEXEC.exe', ['/i'
  3017. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  3018. , 'ACCEPT=YES', '/passive']]
  3019. , install : function() { return any([this.installcmd].map(getshelltask)).then(() => { }) }
  3020. }
  3021. ]
  3022. for(var i=0; i<prerequisites.length; i++) {
  3023. prerequisites[prerequisites[i].name] = prerequisites[i];
  3024. }
  3025. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  3026. var mainTasks = [];
  3027. function verifyAndInstallPrerequisites() {
  3028. var downloadtasks = [];
  3029. var installtasks = [];
  3030. prerequisites.forEach(preq => {
  3031. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  3032. if (exists) console.log(`${preq.shellcmd} exists`)
  3033. else {
  3034. console.log(`${preq.shellcmd} is not installed`)
  3035. return preq.preinstallsteps.call(preq).then(() => {
  3036. installtasks.push(preq.install.bind(preq))
  3037. })
  3038. }
  3039. }))
  3040. })
  3041. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  3042. }
  3043. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  3044. var runconfig = null;
  3045. // 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...)
  3046. var getShellTask = (command, args, options) => {
  3047. options = options || {}
  3048. var callshell = command === 'rm' ? getgitbashtask : getshelltask;
  3049. return () => {
  3050. var p = callshell( [command, args, Object.assign({
  3051. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  3052. }, options)
  3053. ])()
  3054. if (options.ignorefailures) {
  3055. return p.catch(e => {
  3056. // Ignore. Not a major error.
  3057. })
  3058. }
  3059. else return p;
  3060. }
  3061. }
  3062. var oplist = {
  3063. 'h': () => { console.log(elxr.help()); return '-h' }
  3064. , 'clean' : () => {
  3065. // delete all node_module folders and links.
  3066. var tasklist = [];
  3067. dirs( (dir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + dir.name })()), instanceroot )
  3068. return Promise.all(tasklist)
  3069. }
  3070. // , 'undefined': () => { return acquireChoices( {} ); }
  3071. , 'isurlaccessible' : function(args){
  3072. // args.url... .. PB : TODO -- Extract from url
  3073. args = args || {}
  3074. var u = new URL(args.url || selectedinstance.reposerver)
  3075. console.log(u)
  3076. var httpoptions = { hostname : u.host || 'git.bbh.org.in', protocol : u.protocol || 'https'
  3077. , method : 'GET'
  3078. , username : args.username || selectedinstance.username || 'chess'
  3079. , password : selectedinstance.password || 'chess'
  3080. }
  3081. httpoptions.path = args.path || `/`
  3082. return new Promise(function( resolve, reject ){
  3083. RESTAPI.get(httpoptions, function(){
  3084. console.log('URL is accessible')
  3085. resolve(true)
  3086. }, function(){
  3087. console.error('URL is not accessible')
  3088. resolve(false)
  3089. })
  3090. })
  3091. }
  3092. , 'reset': () => {
  3093. // Reset NPM packages semver so major versions can be updated.
  3094. const fs = require('fs')
  3095. const wipeDependencies = (__package) => {
  3096. const file = fs.readFileSync(__package + '/package.json')
  3097. const content = JSON.parse(file)
  3098. for (var devDep in content.devDependencies) {
  3099. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  3100. content.devDependencies[devDep] = '*';
  3101. }
  3102. }
  3103. for (var dep in content.dependencies) {
  3104. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  3105. content.dependencies[dep] = '*';
  3106. }
  3107. }
  3108. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  3109. }
  3110. var repos = ['client'];
  3111. // repos = gitRepos;
  3112. repos.forEach(wipeDependencies)
  3113. // if (require.main === module) {
  3114. // } else {
  3115. // module.exports = wipeDependencies
  3116. // }
  3117. }
  3118. , 'upgrade': () => {
  3119. console.log('upgrade.......')
  3120. var tasks = [
  3121. () => {
  3122. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  3123. inherit: true, shell: true
  3124. , env: ENV
  3125. }).catch((e) => { console.error(e) })
  3126. p.position = 1;
  3127. console.log('One')
  3128. return p;
  3129. }
  3130. , () => {
  3131. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  3132. inherit: true, shell: true
  3133. , env: ENV
  3134. }).catch((e) => { console.error(e) })
  3135. p.position = 2;
  3136. console.log('Two')
  3137. return p;
  3138. }
  3139. , () => {
  3140. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  3141. inherit: true, shell: true
  3142. , env: ENV
  3143. }).catch((e) => { console.error(e) })
  3144. p.position = 3;
  3145. console.log('Three')
  3146. return p;
  3147. }
  3148. , () => {
  3149. var p = nodeShellExec('n', ['latest'], {
  3150. inherit: true, shell: true
  3151. , env: ENV
  3152. }).catch((e) => { console.error(e) })
  3153. p.position = 4;
  3154. console.log('Four')
  3155. return p;
  3156. }
  3157. ]
  3158. any(tasks)
  3159. console.log('.......done')
  3160. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  3161. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  3162. console.info('Uninstalling existing ember globally');
  3163. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  3164. stdio: ['pipe', process.stdout, process.stderr],
  3165. inherit: true,
  3166. shell: true,
  3167. cwd: path.dirname(__dirname),
  3168. env: ENV
  3169. })
  3170. step1.on('close', () => {
  3171. console.info('Installing ember globally');
  3172. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  3173. stdio: ['pipe', process.stdout, process.stderr],
  3174. inherit: true,
  3175. shell: true,
  3176. cwd: path.dirname(__dirname),
  3177. env: ENV
  3178. })
  3179. step2.on('close', () => {
  3180. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  3181. stdio: ['pipe', process.stdout, process.stderr],
  3182. inherit: true,
  3183. shell: true,
  3184. cwd: path.dirname(__dirname),
  3185. env: ENV
  3186. })
  3187. })
  3188. })
  3189. }
  3190. , 'push': () => {
  3191. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  3192. // init remote bare from local
  3193. // pushandinitremotebare
  3194. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  3195. // connect to repo server -- net use 172.16.0.27
  3196. // cd 172.16.0.27/repos/
  3197. // mkdir repo.git
  3198. // cd repo.git
  3199. // git init --bare
  3200. // cd localrepo
  3201. // git remote rename origin githubclone
  3202. // git remote add origin //172.16.0.27/repos/repo.git
  3203. // git push origin master
  3204. var repo = processedArgs._[1];
  3205. var remote = 'origin'
  3206. var sequentialTaskShellCommands = [];
  3207. if (!existsSync(`Z:/${repo}.git`)) {
  3208. sequentialTaskShellCommands = [
  3209. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  3210. // inherit : true, shell: true
  3211. // , env: ENV
  3212. // }]
  3213. ['pwd', { cwd: 'Z:', inherit: true }]
  3214. , ['mkdir', [`${repo}.git`], {
  3215. cwd: `Z:`
  3216. , inherit: true, shell: true
  3217. , env: ENV
  3218. }]
  3219. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  3220. , ['git', ['init', '--bare'], {
  3221. cwd: `Z:/${repo}.git`
  3222. , inherit: true, shell: true
  3223. , env: ENV
  3224. }]
  3225. // PB : TODO -- Do this conditionally only...
  3226. , ['git', ['remote', 'rename', remote, 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  3227. console.log(`Ignoring ${remote} rename error : ` + err); return true; //return true to continue.
  3228. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  3229. , ['git', ['remote', 'add', remote, `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  3230. // PB : TODO -- If threre is a gitbubclone origin
  3231. // Set the master to pull from the local repo.
  3232. ]
  3233. if (!existsSync(`Z:`)) {
  3234. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  3235. inherit: true, shell: true
  3236. , env: ENV
  3237. }])
  3238. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  3239. // throw 'done'
  3240. }
  3241. }
  3242. sequentialTaskShellCommands.push(['git', ['push', remote, 'master'], { cwd: `${instanceroot + '/' + repo}` }])
  3243. // console.dir(sequentialTaskShellCommands);
  3244. var tasks = [];
  3245. sequentialTaskShellCommands.forEach(shellcmd => {
  3246. // console.log(shellcmd)
  3247. tasks.push(() => {
  3248. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
  3249. return p;
  3250. })
  3251. })
  3252. any(tasks);
  3253. }
  3254. , 'is-git-repo': (dir) => {
  3255. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  3256. }
  3257. // git remote equivalents...
  3258. // git branch --set-upstream-to=elixir-unc/master master
  3259. // git push --set-upstream elixir-unc branch..
  3260. , 'remote': (args) => {
  3261. // Subcommands!
  3262. // PB : TODO -- we can now pass in hypehnated args...
  3263. if(!processedArgs.v) return false; // Only -v is supported presently..
  3264. var serial_perform = (repo) => {
  3265. var options = { cwd: instanceroot + '/' + repo }
  3266. return [
  3267. ['git', ['remote', '-v'], options]
  3268. ]
  3269. }
  3270. var x = (args) => {
  3271. var tasq = () => {
  3272. // console.log(args)
  3273. return nodeShellExec.apply(null, args).catch(e => {
  3274. // We continue on failure.
  3275. console.error(tasq.toString())
  3276. })
  3277. }
  3278. tasq.toString = function(){
  3279. return JSON.stringify(args)
  3280. }
  3281. return tasq;
  3282. }
  3283. var perform = (dir) => {
  3284. return any(serial_perform(dir.name).map(x))
  3285. }
  3286. dirs(perform)
  3287. }
  3288. , 'remote set-url': (args) => {
  3289. // git remote set-url elixir-unc //10.10.5.60/gitrepo/chess/bbhverse
  3290. var __args = {
  3291. remotename : args.remotename || processedArgs._[2]
  3292. , url : args.url || processedArgs._[3]
  3293. , branch : args.branch || processedArgs._[4] || 'master'
  3294. }
  3295. __args.upstream = args['upstream'] || processedArgs._[5] || `${__args.remotename}/${__args.branch}`
  3296. // pushable doesn't mean the remote doesn't support being pushed to.
  3297. // 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.
  3298. // PB : TODO -- change this to enablepushing.
  3299. // By default pushing should be disabled. Also developers permissions on the remote is a secondary check for pushing.
  3300. var pushable = processedArgs.pushable || (args.remote ? args.remote.pushable : false) || args.pushable;
  3301. var remotename = __args.remotename
  3302. var url = __args.url
  3303. var branch = __args.branch
  3304. var upstream = __args.upstream
  3305. console.log('remotename : ' + args.remotename)
  3306. var serial_perform_git_seturl = (reponame) => {
  3307. var options = { cwd: instanceroot + '/' + reponame }
  3308. // console.log(reponame)
  3309. var serialcmds = [
  3310. ['git', ['remote', 'set-url', remotename, url + '/' + reponame], { cwd: instanceroot + '/' + reponame }]
  3311. ]
  3312. if (!pushable) {
  3313. serialcmds.push(['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + reponame }])
  3314. }
  3315. var requiresElevation = selectedinstance.elevated.find( r => r.repo === reponame)
  3316. serialcmds.push(['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + reponame, requiresElevation }]) // requires elevation based on repo
  3317. serialcmds.push(['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }])
  3318. return serialcmds
  3319. }
  3320. var x = (xargs) => {
  3321. var tasq = () => {
  3322. // console.log(args)
  3323. var task = (onsuccess, onerror)=>{
  3324. return ()=>{
  3325. return nodeShellExec.apply(null, xargs).then( onsuccess ).catch(e => {
  3326. // We continue on failure.
  3327. // No such remote
  3328. if(e.messages[0].search('No such remote') > -1 ){
  3329. console.log(remotename + ' Remote doesnt exist will add.')
  3330. return oplist['remote add']( args )
  3331. }
  3332. console.error(util.inspect(e) + ' ' + tasq.toString())
  3333. })
  3334. }
  3335. }
  3336. if(xargs[2].requiresElevation){
  3337. if(!isElevated) {
  3338. var etask = task( ()=>{ return remotename } )
  3339. etask.statuslog = statuslog
  3340. etask.selectedinstance = selectedinstance
  3341. etask.processedArgs = processedArgs
  3342. etask.runtimestamp = runtimestamp
  3343. etask.ENV = ENV
  3344. return shell_verse.runElevated(etask)
  3345. }
  3346. }
  3347. return task(
  3348. () => { fs.writeFileSync('run.done', 'success')}
  3349. , () => { fs.writeFileSync('run.done', 'error') }
  3350. )()
  3351. }
  3352. tasq.toString = function(){ return JSON.stringify(args) }
  3353. return tasq;
  3354. }
  3355. var perform_git_seturl = (dir) => {
  3356. return oplist['is-git-repo'](dir).then((logEntry) => {
  3357. return any(serial_perform_git_seturl(dir.name).map(x))
  3358. }).catch((e) => {
  3359. console.log(e + ' Failed not recognized as a git repo : ' + dir.name)
  3360. })
  3361. }
  3362. if(args.dir) return perform_git_seturl(args.dir) // do this for a specific repo
  3363. else return dirs(perform_git_seturl) // Do for all
  3364. }
  3365. // , 'reset' : ()=>{
  3366. // PB : TODO -- Cant have 2 resets !! | There is an npm reset that should be bundled.
  3367. // // Reset the whole installation pertaining to this elxr folder.
  3368. // }
  3369. , 'remote exists': (args) => {
  3370. var __args = {
  3371. remotename : args.remotename|| processedArgs._[2]
  3372. , url : args.url || processedArgs._[3]
  3373. , branch : args.branch || processedArgs._[4]
  3374. }
  3375. var options = args.repo ? { cwd: instanceroot + '/' + args.repo } : {}
  3376. // PB : TODO -- We should evaluate a whole list of remotes passed in from args instead of just one.
  3377. var commands = [
  3378. // git remote -v| while read remote; do "${remote#origin/}" "$remote"; done
  3379. // ['git', ['remote', '-v', '| while read remote; do "${remote#origin/}" "$remote"; done'], utils.assign( {
  3380. [
  3381. // 'git', ['remote', '-v']
  3382. 'git', ['config', `remote.${__args.remotename}.url`]
  3383. , utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  3384. , {
  3385. benign : args.benign, ignorefailures : args.ignorefailures,
  3386. evaluateResult : function(err, result){
  3387. return [
  3388. +result.code === 0
  3389. , result
  3390. ]
  3391. }
  3392. } , options) ]
  3393. ]
  3394. var mapped = commands.map(getshelltask) //.map( p => p.catch(e => e)) // Handle errors later.
  3395. mapped.push( function(prevserialtaskresult) {
  3396. var pt = [false , null]
  3397. if(prevserialtaskresult.error) {
  3398. // Previous task has failed.
  3399. pt[1] = prevserialtaskresult.error[1]
  3400. }
  3401. else pt = prevserialtaskresult;
  3402. console.dir(prevserialtaskresult)
  3403. return getshelltask(['git', ['ls-remote', `${__args.url}`], utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  3404. , {
  3405. benign : args.benign, ignorefailures : args.ignorefailures,
  3406. evaluateResult : function(err, result){
  3407. if(+result.code !== 0) return [pt, [ false, result]]
  3408. // var hasfailed = /^fatal: .*/.test(result.messages.join(' '))
  3409. return [pt, [true, result] ]
  3410. }
  3411. } , options) ])().catch( e => {
  3412. console.error(e)
  3413. return [pt, [ false, null]]
  3414. })
  3415. })
  3416. return any(mapped, true, false, { accumulatedresults : [] }).then( allresolved => {
  3417. console.dir(allresolved)
  3418. !allresolved[0][0] && !allresolved[1][0] ? console.log('was not added as a remote and url is currently inaccessible.')
  3419. : allresolved[0][0] && allresolved[1][0] ? console.log('was added as a remote and url is accessible.')
  3420. : allresolved[0][0] && !allresolved[1][0] ? console.log('was added as a remote but url is currently inaccessible.')
  3421. : console.log('was not added as a remote but url is currently accessible.')
  3422. return !allresolved[0][0] && !allresolved[1][0] ? [0, 0]
  3423. : allresolved[0][0] && allresolved[1][0] ? [1, 1] // => was added as a remote and url is accessible.
  3424. : allresolved[0][0] && !allresolved[1][0] ? [1, 0] // => was added as a remote but url is currently inaccessible.
  3425. : [0, 1] // => was not added and remote and url is accessible.
  3426. }).catch(e => {
  3427. console.log(e)
  3428. return [0, 0]
  3429. })
  3430. }
  3431. , 'remote refresh' : (args) => {
  3432. var url = args._[2] || selectedinstance.reposerver
  3433. return oplist['isurlaccessible']({ url }).then(( baccess )=>{
  3434. if(!baccess) {
  3435. var reposerver = selectedinstance.reposerverinstances[url]
  3436. if(!reposerver.external) {
  3437. // Internal server not accessible ask to switch to external.
  3438. console.log('Internal server not accsssible. Will switch to external')
  3439. // console.dir(selectedinstance.reposerverinstances)
  3440. url = reposerver.externalreposervers[0]
  3441. }
  3442. else {
  3443. console.log('External server not accsssible. Will switch to interal')
  3444. // PB : TODO -- Prompt and then switch.
  3445. url = reposerver.internalreposervers[0]
  3446. }
  3447. return oplist['isurlaccessible']({ url }).then(( baccess )=>{
  3448. if(!baccess) {
  3449. console.log('Neither internal nor external servers are accessible.... Presenting choices...')
  3450. console.log('PB : TODO -- Present appropriate choices...')
  3451. // Redo whole command...
  3452. }
  3453. return dorefresh()
  3454. })
  3455. }
  3456. dorefresh()
  3457. console.log(baccess)
  3458. }).catch((err)=>{ console.error(err) })
  3459. function dorefresh(){
  3460. // if(args.url === selectedinstance.reposerver) {
  3461. // // 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.
  3462. // }
  3463. // else {
  3464. // // Also refreshs anyway
  3465. // }
  3466. args = args || {}
  3467. var __args = {
  3468. url : args.url || processedArgs._[2] || selectedinstance.reposerver
  3469. // , branch : args.branch || processedArgs._[4]
  3470. }
  3471. var serial_perform = (repo) => {
  3472. // if(repo === 'setup' || repo === 'chess-server-lib'){
  3473. var options = { cwd: instanceroot + '/' + repo }
  3474. console.log('serial_perform : ' + repo)
  3475. return [
  3476. ['git', ['remote', '-v'], options]
  3477. ]
  3478. // }
  3479. // else return []
  3480. }
  3481. var x = (args) => {
  3482. // console.log('MapX was called')
  3483. var tasq = () => {
  3484. console.log('--------------------------')
  3485. console.log(args)
  3486. return nodeShellExec.apply(null, args).catch(e => {
  3487. console.log('caught error ------------------------' + JSON.stringify(e))
  3488. // We continue on failure.
  3489. console.error(tasq.toString() + args[2].cwd)
  3490. })
  3491. }
  3492. tasq.toString = function(){
  3493. // console.log('sadfasdf------------------------')
  3494. return JSON.stringify(args) // PB : TODO -- Is this needed ?
  3495. }
  3496. return tasq;
  3497. }
  3498. var remotenames = (selectedinstance.selectedremotes || []).concat( selectedinstance.permanentremotes )
  3499. var remotes = selectedinstance.reposerverinstances[__args.url].remotes
  3500. // use the repo manifest to create missing remotes.
  3501. function perform_remote_refresh(dir){
  3502. var repo = dir.name
  3503. var ___args = {url : __args.url, repo}
  3504. if(repo === '.elxr') return Promise.resolve(true)
  3505. if(repo === '.git') return Promise.resolve(true)
  3506. if(repo === 'Downloads') return Promise.resolve(true)
  3507. // PB : TODO -- pick up remote definitions per repository...
  3508. var reposmanfiest = utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  3509. , {}, selectedinstance, loadmanifest( selectedinstance.root + '/' + repo
  3510. , { username : selectedinstance.username, instanceName : selectedinstance.instanceName
  3511. , node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver }
  3512. ))
  3513. if( !reposmanfiest.error ) {
  3514. var reporemotenames = remotenames.concat(reposmanfiest.selectedremotes || []).concat( reposmanfiest.permanentremotes || [] )
  3515. var reporemotes = utils.assign([], remotes, reposmanfiest.reposerverinstances[___args.url].remotes)
  3516. }
  3517. else {
  3518. var reporemotenames = remotenames
  3519. var reporemotes = remotes
  3520. }
  3521. return (()=>{
  3522. var promises = []
  3523. return any(serial_perform(repo).map(x)).then(()=>{
  3524. var branch = args.branch || 'master' // PB : TODO -- Dont default branch here.. Let each repos current state define this... ???
  3525. reporemotenames.forEach(rm =>{
  3526. console.log('Processing : ' + rm + ' ' + dir.name)
  3527. // if(repo != 'elxr') return //test
  3528. // if(repo != 'elixir-config-development') return //test
  3529. // if(repo != 'elixir-server') return //test
  3530. promises.push( ((rm) => {
  3531. var remotename = rm
  3532. var repodef = selectedinstance.reposindexed[repo];
  3533. if(!repodef) return
  3534. // if( repo !== 'cihsr-data') return
  3535. // 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.
  3536. // 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.
  3537. var remote = reporemotes[remotename]
  3538. // console.log(repodef)
  3539. // console.log(remote)
  3540. var owner = getowner(repodef, remote)
  3541. var reposerver = repodef.server || remote.server || selectedinstance.reposerver
  3542. // selectedinstance.reposerverinstances[reposerver]
  3543. var auth = repodef.username ? repodef : remote.username ? remote : selectedinstance.reposerverinstances[reposerver].username ? reposerver : selectedinstance;
  3544. var httpoptions = new URL(reposerver);
  3545. httpoptions = {
  3546. hostname: httpoptions.hostname
  3547. , method: 'GET'
  3548. , protocol : httpoptions.protocol
  3549. }
  3550. httpoptions.username = auth.username // PB : TODO -- Handle remotes with different username. Also cache git credentials either globally or per repo...
  3551. 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.
  3552. // console.log(___args)
  3553. var repourl = reporemotes[remotename].url + '/' + repo
  3554. // PB : TOOD -- USE GITTEA API
  3555. // oplist['isurlaccessible']({ url : repourl }).then((baccess)=>{
  3556. return GITEA.repository.exists( httpoptions, repo, owner ).then((bexists)=>{
  3557. console.log(remotename + ' ' + repourl)
  3558. if(bexists) {
  3559. console.log(remotename + ' ' + repourl + ' is accessible')
  3560. return ((remotename)=>{
  3561. return oplist['remote set-url']( { dir, remotename, url : reporemotes[remotename].url, remote
  3562. , repodef : selectedinstance.reposindexed[repo] } ) // PB : TODO -- Handle add-url
  3563. })(remotename)
  3564. // get upstream remote choice from user !!!
  3565. // PB : TODO -- Set upstream , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  3566. }
  3567. }).catch(e => {
  3568. console.warn(remotename + ' ' + repourl + ' ' + e) // Skip nonexistant not necessarily quietly
  3569. })
  3570. })(rm)
  3571. )
  3572. })
  3573. return Promise.all(promises).then( accessibleremotes => {
  3574. while(!accessibleremotes[accessibleremotes.length -1] && accessibleremotes.length) accessibleremotes.splice(accessibleremotes.length -1, 1)
  3575. if(accessibleremotes.length) {
  3576. ((remotename)=>{
  3577. var upstream = `${remotename}/${branch}`
  3578. var remote = reporemotes[remotename]
  3579. return oplist['remote set-url']( { dir, remotename, url : reporemotes[remotename].url, remote
  3580. , upstream
  3581. , repodef : selectedinstance.reposindexed[repo] } ) // PB : TODO -- Handle add-url
  3582. })( accessibleremotes[accessibleremotes.length -1] )
  3583. }
  3584. }).catch((e) => { console.log('Processing Error : ' + dir.name); console.error(e); return { error: true, message: repo } })
  3585. })
  3586. })()
  3587. }
  3588. if(isElevated) {
  3589. var elevatedpromises = []
  3590. selectedinstance.elevated.forEach( r => { elevatedpromises.push(perform_remote_refresh({ name : r.repo })) } )
  3591. return Promise.all(elevatedpromises)
  3592. }
  3593. else return dirs(perform_remote_refresh)
  3594. }
  3595. }
  3596. , 'remote add': (args) => {
  3597. // PB : TODO -- set-upstream-to should be chosen and intentionally switched. Coz we can have multiple upstream remotes.
  3598. // Also each upstream remote may need to have is own branch to switch to. We therefore need a branch nomenclature
  3599. // That explicitly has a remote name prefix.
  3600. // git branch branch_name --set-upstream-to your_new_remote/branch_name
  3601. // git branch branch_name -u your_new_remote/branch_name -- older versions
  3602. // git branch -vv -- Detect which branch are we tracking.
  3603. // default upstream should be users own fork.
  3604. // Also need alias branches to
  3605. // define a git alias which would git pull master from one repo, and then git pull master from other remotes.
  3606. // probably git merge from all remotes... and relevant branches...
  3607. // alias pushall='for i in `git remote`; do git push $i; done;'
  3608. // alias pullall='for i in `git remote`; do git pull $i; done;'
  3609. // args === processedArgs ? args = {} : null;
  3610. var __args = {
  3611. remotename : args.remotename|| processedArgs._[2]
  3612. , reponame : args.reponame || (args.repodef ? args.repodef.repo : undefined)
  3613. , url : args.url || processedArgs._[3]
  3614. , branch : args.branch || processedArgs._[4] || 'master'
  3615. }
  3616. __args.upstream = args['upstream'] || processedArgs._[5] || `${remotename}/${branch}`
  3617. var remotename = __args.remotename
  3618. var url = __args.url
  3619. var branch = __args.branch
  3620. var upstream = __args.upstream
  3621. var pushable = processedArgs.pushable || (args.remote ? args.remote.pushable : false) || args.pushable;
  3622. var serial_perform_git_add = (reponame) => {
  3623. var options = { cwd: instanceroot + '/' + reponame }
  3624. // console.log(reponame)
  3625. if (pushable) {
  3626. var gacmds = [
  3627. ['git', ['remote', 'add', remotename, url + '/' + reponame], { cwd: instanceroot + '/' + reponame }]
  3628. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + reponame }]
  3629. // , ['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }]
  3630. ]
  3631. }
  3632. else {
  3633. var gacmds = [
  3634. ['git', ['remote', 'add', remotename, url + '/' + reponame], { cwd: instanceroot + '/' + reponame }]
  3635. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + reponame }]
  3636. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + reponame }]
  3637. // When we add a remote it should not automatically become the upstream. The upstream should be a chosen remote else we do not change
  3638. // , ['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }]
  3639. ]
  3640. }
  3641. if(__args['upstream']) gacmds.push(['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }])
  3642. return gacmds
  3643. }
  3644. // PB : TODO -- Accumulate using yield... and finally return a set of tasks or promises...
  3645. var perform_git_add = (dir) => {
  3646. return oplist['is-git-repo'](dir).then((logEntry) => {
  3647. // console.log(code)
  3648. if (logEntry.success) {
  3649. return nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  3650. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  3651. return remotename;
  3652. })
  3653. .catch((e) => {
  3654. return perform( serial_perform_git_add, dir.name ).then(()=>{
  3655. return remotename
  3656. })
  3657. })
  3658. }
  3659. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  3660. }).catch((e) => {
  3661. console.log('Failed : ' + dir.name)
  3662. })
  3663. }
  3664. if(__args.reponame) { return perform_git_add( { name : __args.reponame} ) }
  3665. else return dirs(perform_git_add)
  3666. }
  3667. , 'remote remove': (args) => {
  3668. var __args = {
  3669. remotename : args.remotename|| processedArgs._[2]
  3670. }
  3671. var remotename = __args.remotename
  3672. var serial_perform_git_remove = (repo) => {
  3673. var options = { cwd: instanceroot + '/' + repo }
  3674. // console.log(repo)
  3675. return [
  3676. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  3677. ]
  3678. }
  3679. var perform_git_remove = (dir) => {
  3680. oplist['is-git-repo'](dir).then((logEntry) => {
  3681. // console.log(code)
  3682. if (logEntry.success) {
  3683. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  3684. any(serial_perform_git_remove(dir.name).map(getnodeshellexectask))
  3685. })
  3686. .catch((e) => {
  3687. console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`)
  3688. })
  3689. }
  3690. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  3691. }).catch((e) => {
  3692. // console.log('Failed : ' + dir.name)
  3693. })
  3694. }
  3695. dirs(perform_git_remove)
  3696. }
  3697. , 'get-remotes' : (args) => {
  3698. // var __args = {
  3699. // repo : args?.repo || processedArgs._[1]
  3700. // }
  3701. var repo = args.repo
  3702. var serial_perform = (repo) => {
  3703. return [
  3704. ['git', ['remote', '-vvvv'], { cwd: instanceroot + '/' + repo,
  3705. evaluateResult : function( issuccess, result){
  3706. if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
  3707. var lines = result.messages.join('').split('\n')
  3708. var remotes = {}
  3709. lines.forEach(line => {
  3710. // pattern = origin https://git.bbh.org.in/chess/elxr (fetch)
  3711. var match = new RegExp(`(\\S+)\\s(\\S+)/${repo}.git\\s\\((\\S+)\\)`).exec(line)
  3712. if(match) {
  3713. var r = remotes[match[1]] || (remotes[match[1]] = { title : match[1] })
  3714. if(match[3] === 'push') { r.push = match[2] }
  3715. else r.url = match[2]
  3716. }
  3717. })
  3718. return remotes
  3719. }}]
  3720. ]
  3721. }
  3722. return perform( serial_perform, repo )
  3723. }
  3724. , 'get-remote' : (upstream) => {
  3725. // var __args = {
  3726. // repo : args?.repo || processedArgs._[1]
  3727. // }
  3728. var repo = upstream.repo
  3729. var serial_perform = (repo) => {
  3730. return [
  3731. ['git', ['remote', '-vvvv'], { cwd: instanceroot + '/' + repo,
  3732. evaluateResult : function( issuccess, result){
  3733. if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
  3734. // origin https://git.bbh.org.in/chess/elxr (fetch)
  3735. var match = new RegExp(`${upstream.remotename}\\\s(\\S+)/${repo}.git\\s\\(fetch\\)`).exec(result.messages.join(' '))
  3736. if(match) { upstream.url = match[1] }
  3737. else throw Object.assign( new Error('No upstream found for active branch'), result)
  3738. return upstream
  3739. }}]
  3740. ]
  3741. }
  3742. return perform( serial_perform, repo )
  3743. }
  3744. , 'get-upstream' : (args) => {
  3745. var __args = {
  3746. repo : args?.repo || processedArgs._[1]
  3747. }
  3748. var repo = __args.repo
  3749. var serial_perform = (repo) => {
  3750. return [
  3751. ['git', ['branch', '-vvvv'], { cwd: instanceroot + '/' + repo,
  3752. evaluateResult : function( issuccess, result){
  3753. if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
  3754. var match = /\*\s(\S+)\s\S+\s\[(\S+)\/(\S+).*?\].*?/.exec(result.messages.join(' '))
  3755. if(match) { var upstream = { remotename : match[2], branch : match[1], remotebranch : match[3] } }
  3756. else throw Object.assign( new Error('No upstream found for active branch'), result)
  3757. if(args?.remotes) {
  3758. var r = args.remotes[upstream.remotename];
  3759. if(!r) return oplist['get-remote'](upstream)
  3760. r.branch = upstream.branch
  3761. r.remotebranch = upstream.remotebranch
  3762. return r
  3763. }
  3764. return oplist['get-remote'](upstream)
  3765. }}]
  3766. ]
  3767. }
  3768. return perform( serial_perform, repo )
  3769. }
  3770. , 'init-gitea': (username) => {
  3771. // Change user to an object that has user.username and use here..
  3772. username = username || processedArgs._[1]
  3773. if (!username) throw 'User name required'
  3774. var serial_perform_init_gitea = (repo) => {
  3775. var options = { cwd: instanceroot + '/' + repo }
  3776. // console.log(repo)
  3777. return [
  3778. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${username}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  3779. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  3780. , ['git', ['remote', 'set-url', 'userfork', `${selectedinstance.reposerver}/${username}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  3781. ]
  3782. }
  3783. var perform_init_gitea = (dir) => {
  3784. oplist['is-git-repo'](dir).then((logEntry) => {
  3785. // console.log(code)
  3786. if (logEntry.success) {
  3787. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  3788. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  3789. })
  3790. .catch((e) => {
  3791. perform( serial_perform_init_gitea, dir.name )
  3792. })
  3793. }
  3794. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  3795. }).catch((e) => {
  3796. // console.log('Failed : ' + dir.name)
  3797. })
  3798. }
  3799. dirs(perform_init_gitea)
  3800. }
  3801. , 'syncmaster': (label) => {
  3802. // Usage :
  3803. // elxr pull -- Defaults to run config
  3804. console.log('Running exlr pull : ' + path.dirname(__dirname))
  3805. if (!processedArgs.runas) gitRepos.map((def) => {
  3806. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  3807. else performPullOrClone(def, def.branch || 'master')
  3808. })
  3809. var etask = ()=>{
  3810. return any(elevatedRunasRepos.map((def) =>
  3811. {
  3812. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  3813. else performPullOrClone(def, def.branch || 'master')
  3814. })).then(() => {
  3815. fs.writeFileSync('run.done', 'success')
  3816. }).catch(() => {
  3817. fs.writeFileSync('run.done', 'error')
  3818. })
  3819. }
  3820. etask.statuslog = statuslog
  3821. etask.selectedinstance = selectedinstance
  3822. etask.processedArgs = processedArgs
  3823. etask.runtimestamp = runtimestamp
  3824. etask.ENV = ENV
  3825. return shell_verse.runElevated(etask)
  3826. }
  3827. , 'repo-relocate' : function(args){
  3828. // relocate a subfolder in source repo to same subfolder in target repo with history.
  3829. args = ARGUMENTVALIDATOR.validate( args, { sourcerepo : true, targetrepo : true, remotebase : true }, {}, {
  3830. remotebase : processedArgs._[5] || 'http://git.bbh'
  3831. , folder : processedArgs._[3] || '' //|| 'server'
  3832. , targetfolder : processedArgs._[4] || ''
  3833. , sourcerepo : processedArgs._[2]
  3834. , targetrepo : processedArgs._[1]
  3835. , repodir : `${processedArgs._[6] || instanceroot}` /*workingroot for this command...*/ || `${instanceroot}/relocate` // Default workingroot figure out a way to pass it in.
  3836. , branch : 'master'
  3837. } )
  3838. var sourcerepooptions = { cwd: args.repodir
  3839. // , stdio: ['pipe', process.stdout, process.stderr]
  3840. , inherit: true,
  3841. shell: true,
  3842. env: ENV
  3843. , runas: processedArgs.runas
  3844. }
  3845. return oplist['repo-split'](args).then(()=>{
  3846. return oplist['repo-merge'](args).then(()=>{
  3847. // cleanup folder from source.
  3848. var cmdseq = [
  3849. // ['rm', ['-rf', `${args.repodir}`], sourcerepooptions ]
  3850. // ['rm', ['-rf', `${args.sourcerepo}`], sourcerepooptions ]
  3851. // commits have to be intentional...
  3852. // , ['git', ['commit', '-a', '-m', `relocate folder ${args.folder} to ${targetrepo}`], sourcerepooptions ]
  3853. ]
  3854. return any(cmdseq.map(getshelltask))
  3855. })
  3856. }).catch(e=>{console.error(e)})
  3857. }
  3858. , 'repo-split' : function(args) {
  3859. // https://gist.github.com/smdabdoub/17065c348289158277b5
  3860. /**
  3861. * Eg : folder, remotebase, sourcerepo, targetrepo
  3862. * args.folder = 'server'
  3863. * args.remotebase = 'https://git.bbh/chess/'
  3864. * args.sourcerepo = 'client'
  3865. * args.targetrepo = 'elixir-server'
  3866. */
  3867. var currentargs = ARGUMENTVALIDATOR.validate( args, { repodir : true, remotebase : true }, {}, {
  3868. // remotebase : 'http://git.bbh' + `/${getowner(args)}`
  3869. folder : '' //'server' // Do all folders by default.
  3870. , targetfolder : ''
  3871. , sourcerepo : undefined
  3872. , targetrepo : undefined
  3873. // , repodir : .. should be passed in.
  3874. } )
  3875. // var options = { cwd: args.repodir
  3876. // // , stdio: ['pipe', process.stdout, process.stderr]
  3877. // , inherit: true,
  3878. // shell: true,
  3879. // env: ENV
  3880. // , runas: processedArgs.runas
  3881. // }
  3882. currentargs.sourceloc = args.folder ? `relocatesource-${args.sourcerepo}-${args.folder}` : `relocatesource-${args.sourcerepo}`
  3883. currentargs.targetloc = args.targetfolder ? `relocatetarget-${args.targetrepo}-${args.targetfolder}` : `relocatetarget-${args.targetrepo}`
  3884. currentargs.repodir = args.repodir + '/relocate/' + currentargs.sourceloc + `/${args.owner || defaultowner}`
  3885. currentargs.repo = args.sourcerepo
  3886. currentargs = utils.assign({}, args, currentargs)
  3887. currentargs.remotebase = (args.remotebase || 'http://git.bbh') + `/${getowner(args)}`
  3888. // console.dir(GITSHELL.pullORcloneSHELLCMD( currentargs ))
  3889. var cmdseq = [
  3890. // create a temporary working dir in current folder where we started execution.
  3891. getshelltask([`"${gitbash}"`, ['-c', getCmdString(['mkdir', [' -p', 'relocate/' + currentargs.sourceloc + `/${getowner(args)}`] ]) ]
  3892. , { cwd: args.repodir
  3893. // , stdio: ['pipe', process.stdout, process.stderr]
  3894. , inherit: true, shell: true, benign : true, env: ENV, runas: processedArgs.runas
  3895. }])
  3896. // This copy is needed to manually delete the relocated folder / repo and commit. ( Tool will not autocommit )
  3897. // , ['git', ['clone', `${args.remotebase}${args.sourcerepo}`], options ]
  3898. , GITSHELL.pullORcloneSHELLCMD( currentargs )
  3899. // This is where the source will get split.
  3900. , getshelltask([`"${gitbash}"`, ['-c', getCmdString(['mkdir', [' -p', currentargs.sourceloc + '-split' + `/${getowner(args)}` ] ]) ]
  3901. , { cwd: args.repodir + '/relocate'
  3902. // , stdio: ['pipe', process.stdout, process.stderr]
  3903. , inherit: true, shell: true, benign : true, env: ENV, runas: processedArgs.runas
  3904. }])
  3905. // , ['git', ['clone', `${args.sourcerepo}`, args.sourceloc], utils.assign({}, options, {cwd: args.sourceloc} ) ]
  3906. , GITSHELL.pullORcloneSHELLCMD( utils.assign({}, currentargs, { remotebase : '../../' + currentargs.sourceloc + `/${getowner(args)}`
  3907. , targetloc : '.'
  3908. , repodir : args.repodir + '/relocate/' + currentargs.sourceloc + '-split' + `/${getowner(args)}`
  3909. , localrepo :true
  3910. }))
  3911. // This is where the target will have the merged folder. ( Tool will not autocommit )
  3912. // // , ['git', ['clone', `${args.remotebase}${args.targetrepo}`], utils.assign({}, options, {cwd: args.targetloc} )]
  3913. , getshelltask([`"${gitbash}"`, ['-c', getCmdString(['mkdir', [' -p', currentargs.targetloc + `/${getowner(args)}`] ]) ]
  3914. , { cwd: args.repodir + '/relocate'
  3915. // , stdio: ['pipe', process.stdout, process.stderr]
  3916. , inherit: true, shell: true, benign : true, env: ENV, runas: processedArgs.runas
  3917. }])
  3918. , GITSHELL.pullORcloneSHELLCMD( utils.assign({ requiresElevation : true }, currentargs, { repo : args.targetrepo
  3919. , repodir : path.normalize(args.repodir + '/relocate/' + currentargs.targetloc) + `/${getowner(args)}` }) )
  3920. ]
  3921. return any(cmdseq).then(() => {
  3922. // , ['git', ['subtree', 'split', '-P', `${args.folder}`, '-b', `relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  3923. // split doesnt retain folder structure we need to move and commit ourselves through a branch to retain history...
  3924. // , ['git', [`checkout relocate-${args.sourcerepo}-${args.folder}`], sourcerepooptions]
  3925. // , ['mkdir', [`${args.folder}`], sourcerepooptions]
  3926. // , ['git', ['mv', `!(${args.folder})`, `${args.folder}`], sourcerepooptions ] // requires shopt -s extglob
  3927. // , ['git', ['commit', `-m`, 'Moved to same subfolder after subtree split in branch'] , sourcerepooptions]
  3928. // subtree split and filter-branch are options. We currently use repo-filter.
  3929. currentargs.repodir = args.repodir + '/relocate/' + currentargs.sourceloc + '-split' + `/${getowner(args)}/${currentargs.repo}`
  3930. return oplist['filter-repo'](currentargs)
  3931. }).catch(e=>{
  3932. console.error(e);
  3933. throw 'failed'
  3934. })
  3935. }
  3936. , 'repo-merge' : function(args) {
  3937. // Merge source repo into target repo
  3938. var currentargs = ARGUMENTVALIDATOR.validate( args, { repodir : true, remotebase : true }, {}, {
  3939. remotebase : 'http://git.bbh'
  3940. , folder : '' //'server' // Do all folders by default.
  3941. , targetfolder : ''
  3942. , sourcerepo : undefined
  3943. , targetrepo : undefined
  3944. // , repodir : .. should be passed in.
  3945. } )
  3946. // var options = { cwd: args.repodir
  3947. // // , stdio: ['pipe', process.stdout, process.stderr]
  3948. // , inherit: true,
  3949. // shell: true,
  3950. // env: ENV
  3951. // , runas: processedArgs.runas
  3952. // }
  3953. currentargs.sourceloc = args.folder ? `relocatesource-${args.sourcerepo}-${args.folder}` : `relocatesource-${args.sourcerepo}`
  3954. currentargs.targetloc = args.targetfolder ? `relocatetarget-${args.targetrepo}-${args.targetfolder}` : `relocatetarget-${args.targetrepo}`
  3955. currentargs.repodir = args.repodir + '/' + currentargs.sourceloc
  3956. currentargs.repo = args.sourcerepo
  3957. currentargs = utils.assign({}, args, currentargs)
  3958. var targetrepooptions = { cwd: args.repodir + '/relocate/' + currentargs.targetloc + `/${args.owner || defaultowner}` + `/${args.targetrepo}`
  3959. // , stdio: ['pipe', process.stdout, process.stderr]
  3960. , inherit: true,
  3961. shell: true,
  3962. env: ENV
  3963. , runas: processedArgs.runas
  3964. }
  3965. // git pull ../../../relocatesource-client-split/chess/client master --allow-unrelated-histories
  3966. var cmdseq = [
  3967. ['git', ['pull', `../../../` + currentargs.sourceloc + '-split' + `/${args.owner || defaultowner}` + `/${args.sourcerepo}`, `master`, '--allow-unrelated-histories']
  3968. , targetrepooptions ]
  3969. // , ['git', ['push', targetrepooptions ] // manual push for now..
  3970. ]
  3971. return any(cmdseq.map(getshelltask)).catch(e=>{console.error( JSON.stringify(e) ) })
  3972. }
  3973. , 'filter-repo' : function(args){
  3974. // 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.
  3975. var args = args || {
  3976. folder : '' // 'server'
  3977. , targetfolder : ''
  3978. , remotebase : 'http://git.bbh'
  3979. , targetrepo : undefined
  3980. }
  3981. args = ARGUMENTVALIDATOR.validate( args, { sourcerepo : true, repodir : true, sourceloc : true }, {}, {
  3982. remotebase : 'http://git.bbh'
  3983. , folder : '' //'server' // Do all folders by default.
  3984. , targetfolder : ''
  3985. , sourcerepo : undefined
  3986. , targetrepo : undefined
  3987. // , repodir : .. should be passed in.
  3988. } )
  3989. var sourcerepooptions = { cwd: args.repodir
  3990. // , stdio: ['pipe', process.stdout, process.stderr]
  3991. , inherit: true, shell: true, env: ENV
  3992. , runas: processedArgs.runas
  3993. }
  3994. var cmdargs = (args.targetfolder && args.folder) ? ['filter-repo', '--force', '--path', `${args.folder}` , `--path-rename :${args.targetfolder}/` ]
  3995. : args.targetfolder ? ['filter-repo', '--force',`--path-rename :${args.targetfolder}/` ]
  3996. : args.folder ? ['filter-repo', '--force','--path', `${args.folder}` ] : ['filter-repo', '--force']
  3997. var cmdseq = [
  3998. // git checkout -b feature/merge-old-project
  3999. // git remote add src-project ../src-project
  4000. ['git', cmdargs, sourcerepooptions ]
  4001. ]
  4002. console.dir(args.targetfolder)
  4003. return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e); throw 'failed' })
  4004. }
  4005. , 'filter-branch' : function(preservefolder, repo){
  4006. // https://stackoverflow.com/questions/359424/detach-move-subdirectory-into-separate-git-repository
  4007. // git subtree split -P <name-of-folder> -b <name-of-new-branch>
  4008. // Preserve a specific folder.
  4009. // PB : TODO -- filter-branch has known issues. Explore subtree and filter-repo...
  4010. /*
  4011. git clone repo reposplit
  4012. git filter-branch --tag-name-filter cat --prune-empty --subdirectory-filter {{folder}} -- --all
  4013. git remote rm origin
  4014. */
  4015. throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
  4016. }
  4017. // , 'repo-merge-folder' : function(mergetarget, mergesource, mergefolder){
  4018. // // Merge repo2 into a subfolder in repo1
  4019. // // https://alexharv074.github.io/puppet/2017/10/04/merge-a-git-repository-and-its-history-into-a-subdirectory-of-a-second-git-repository.html
  4020. // // https://thoughts.t37.net/merging-2-different-git-repositories-without-losing-your-history-de7a06bba804
  4021. // /*
  4022. // cd repo1
  4023. // git remote add -f tempmergesource ../{{mergesource}}/.git
  4024. // git merge -s ours --no-commit tempmergesource/master --allow-unrelated-histories
  4025. // git read-tree --prefix={{mergefolder}} -u tempmergesource/master:
  4026. // git commit
  4027. // // Repair History
  4028. // // === git filter-branch --tree-filter '(echo === $GIT_COMMIT:; git ls-tree $GIT_COMMIT) >> /tmp/tree.log'
  4029. // #!/usr/bin/env bash
  4030. // first=ed4f16becc2f03820c164e0617bb98f12ff49ef0
  4031. // last=038e26e21bd60fa265d6637261f3bc918780d2e8
  4032. // subdir=server
  4033. // git filter-branch --tree-filter '
  4034. // first='"$first"'
  4035. // last='"$last"'
  4036. // subdir='"$subdir"'
  4037. // log_file=/tmp/filter.log
  4038. // [ "$GIT_COMMIT" = "$first" ] && seen_first=true
  4039. // if [ "$seen_first" = "true" ] && [ "$seen_last" != "true" ]; then
  4040. // echo "=== $GIT_COMMIT: making changes"
  4041. // files=$(git ls-tree --name-only $GIT_COMMIT)y
  4042. // mkdir -p $subdir
  4043. // for i in $files; do
  4044. // mv $i $subdir || echo "ERR: mv $i $subdir failed"
  4045. // done
  4046. // else
  4047. // echo "=== $GIT_COMMIT: ignoring"
  4048. // fi \
  4049. // >> $log_file
  4050. // [ "$GIT_COMMIT" = "$last" ] && seen_last=true
  4051. // status=0 # tell tree-filter never to fail
  4052. // '
  4053. // git remote rm tempmergesource
  4054. // */
  4055. // // better alternative for history
  4056. // /**
  4057. // *
  4058. // git clone git@server.com:old-project.git
  4059. // git clone git@server.com:new-project.git
  4060. // cd old-project
  4061. // mkdir old-project
  4062. // git mv !(old-project) old-project
  4063. // ls -la and gt mv hidden files ....
  4064. // git commit -a -S -m “Moving old project into its own subdirectory”
  4065. // cd ../new-project
  4066. // git remote add old-project ../old-project
  4067. // git fetch old-project
  4068. // git checkout -b feature/merge-old-project
  4069. // git merge -S --allow-unrelated-histories old-project/master
  4070. // git push origin feature/merge-old-project
  4071. // git remote rm old-project
  4072. // */
  4073. // throw 'merge-repos not yet implmented pls refer to manual commands in code.'
  4074. // }
  4075. , 'clone' : (label) =>{
  4076. return elxr.getPullOrCloneTask(selectedinstance)
  4077. }
  4078. , 'pull' : (label) => {
  4079. // Usage :
  4080. // elxr pull -- Defaults to run config
  4081. return elxr.getPullOrCloneTask(selectedinstance)
  4082. }
  4083. , 'isInstalled': () => {
  4084. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  4085. console.log(processedArgs._[1] + ' exists.')
  4086. return true;
  4087. });
  4088. }
  4089. , 'c' : ()=>{
  4090. }
  4091. , 'i' : () => {
  4092. var tasks = []
  4093. // tasks.push(oplist['pull']);
  4094. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
  4095. tasks.push(oplist['use']) // Will pull repos...
  4096. oplist['npmi'].statuslog = statuslog
  4097. tasks.push(shell_verse.getNonElevatedTask(oplist['npmi'])) // We do not run npm i with elevated privilege for security reasons.
  4098. // var tasksdefs = [
  4099. // ['elxr', ['pull']]
  4100. // , ['elxr', ['use', 'elixir']]
  4101. // , ['elxr', ['npmi']]
  4102. // ]
  4103. // tasksdefs.forEach(tasksdef=>{
  4104. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  4105. // })
  4106. return any(tasks);
  4107. }
  4108. , 'npmi': () => {
  4109. var tasks = [];
  4110. // Build fails without babel...
  4111. tasks.push(getShellTask(
  4112. 'npm',[ 'i', '-g', 'babel-cli' ]
  4113. ) )
  4114. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  4115. // npmbuildrepos = []
  4116. npmbuildrepos.forEach(repo => {
  4117. tasks.push(() => {
  4118. return nodeShellExec('npm', ['i --force'], {
  4119. inherit: true, shell: true
  4120. , cwd: instanceroot + '/' + repo
  4121. , env: ENV
  4122. , title: `npm i for ${repo}`
  4123. }).catch((e) => {
  4124. console.error('Ignoring Benign Error'); console.error(e);
  4125. }).then(() => {
  4126. console.log(`--npm run build for ${repo}--------------------`)
  4127. return nodeShellExec('npm', ['run build'], {
  4128. inherit: true, shell: true
  4129. , cwd: instanceroot + '/' + repo
  4130. , env: ENV
  4131. , title: `npm run build for ${repo}`
  4132. }).then(Tasq.then).catch(Tasq.catch)
  4133. })
  4134. })
  4135. })
  4136. return any(tasks).then(() => {
  4137. gitRepos.push({ repo : 'chess-server-lib/server'});
  4138. gitRepos = gitRepos.concat(elevatedRunasRepos);
  4139. // console.dir(gitRepos)
  4140. // throw ""
  4141. // gitRepos = [
  4142. // // 'bbhverse', 'serververse', 'elixir-server',
  4143. // // 'clientverse',
  4144. // 'client'
  4145. // ];
  4146. var rmtasks = []
  4147. var repotasks = []
  4148. var env = Object.assign({}, ENV)
  4149. delete env.NODE_ENV // PB : TODO -- Why delete ??? npm i fails with NODE_ENV...
  4150. gitRepos.forEach(repodef => {
  4151. rmtasks.push(
  4152. // () => {
  4153. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  4154. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  4155. callshelltask(['rm', ['package-lock.json'], {
  4156. inherit: true, shell: true
  4157. , cwd: instanceroot + '/' + repodef.repo
  4158. , env: ENV
  4159. , title: `rm 'package-lock.json' for ${repodef.repo}`
  4160. }])
  4161. .then(()=>{
  4162. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  4163. }).catch((e) => { console.error(e) })
  4164. // }
  4165. )
  4166. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  4167. repotasks.push(
  4168. () => {
  4169. console.log(`--npm i for ${repodef.repo}--------------------`)
  4170. var p = nodeShellExec('npm', ['i', '--force'], {
  4171. inherit: true, shell: true
  4172. , cwd: instanceroot + '/' + repodef.repo
  4173. , env
  4174. , title: `npm i for ${repodef.repo}`
  4175. }).then(Tasq.then).catch(Tasq.catch)
  4176. return p;
  4177. })
  4178. }
  4179. })
  4180. // NODE_ENV=development DEBUG=loopback:connector:mssql node --tls-min-v1.0 --inspect elixir/server.js
  4181. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  4182. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  4183. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  4184. // PB : TODO -- Investigate why NODE_ENV has an impact on npm i !??
  4185. // Second time try also doesnt work.
  4186. // repotasks.push(
  4187. // () => {
  4188. // var env = Object.assign({}, process.env)
  4189. // delete env.NODE_ENV
  4190. // console.log(`--------------------second time npm i for client--------------------`)
  4191. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  4192. // // return nodeShellExec('npm', ['i --force'], {
  4193. // inherit: true, shell: true
  4194. // , cwd: instanceroot + '/' + 'client'
  4195. // , env
  4196. // , title: `npm i for client`
  4197. // }).then(Tasq.then).catch(Tasq.catch)
  4198. // })
  4199. var bowerRepos = [{ repo : 'elixir-client'}];
  4200. var bowertasks = []
  4201. bowerRepos.forEach(repodef => {
  4202. bowertasks.push(() => {
  4203. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
  4204. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  4205. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  4206. inherit: true, shell: true
  4207. , cwd: instanceroot + '/' + repodef.repo
  4208. , env: ENV
  4209. , title: `bower i for ${repodef.repo}`
  4210. }).then(Tasq.then).catch(Tasq.catch)
  4211. return p;
  4212. })
  4213. })
  4214. // console.log('rmtasks.length : ' + rmtasks.length)
  4215. return Promise.all(rmtasks).then(() => any(repotasks)).then(()=>any(bowertasks));
  4216. }).catch(e => {
  4217. console.error(e)
  4218. }).finally(statuslog.finally)
  4219. }
  4220. , 'start': (args) => {
  4221. // Usage : elxr start {{instanceName=elixir}} {{all||server||client||{{microserviceName=elixir||express}}}}
  4222. var label = clioverrides.cmd
  4223. var env = Object.assign({}, ENV); // Shallow clone it.
  4224. var nodecmd = clioverrides.node_env === 'development' ? 'nodemon' : 'node';
  4225. function startFn( o ){
  4226. var cmd = [nodecmd, [`--inspect=${o.debugport}`, '--preserve-symlinks', o.script]]
  4227. console.log(`Starting ${o.name}.`);
  4228. if(shell_verse.iswin()){
  4229. var __cmd = 'cmd'
  4230. var a1 = '/k'
  4231. }
  4232. else if(shell_verse.islin()) {
  4233. var __cmd = 'sh'
  4234. var a1 = '-c'
  4235. }
  4236. if(o.cmd) {
  4237. cmd = o.cmd
  4238. var childPromise = nodeShellExec(...o.cmd, {
  4239. // inherit : true,
  4240. shell: true,
  4241. detached: true,
  4242. stdio: 'ignore',
  4243. cwd: instanceroot + o.path
  4244. , env
  4245. })
  4246. }
  4247. else {
  4248. var childPromise = nodeShellExec(__cmd, [a1, getCmdString(cmd) ], {
  4249. // inherit : true,
  4250. shell: true,
  4251. detached: true,
  4252. stdio: 'ignore',
  4253. cwd: instanceroot + o.path
  4254. , env
  4255. })
  4256. }
  4257. var child = childPromise.process;
  4258. var cpid = child.pid
  4259. childPromise.then(()=>{
  4260. console.log(` *** started ${o.name} PID(${cpid}) ${cmd}`);
  4261. fs.writeFileSync(o.pidstore, '' + cpid)
  4262. })
  4263. .catch(e => console.error(e) )
  4264. }
  4265. if(clioverrides.node_env === 'development') {
  4266. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  4267. if(!processedArgs._[2]) processedArgs._[2] = 'all'
  4268. if(processedArgs._[2] === 'server' || processedArgs._[2] === 'all'
  4269. || processedArgs._[2] === 'elixir' // specific microservice name.
  4270. ) {
  4271. startFn( { debugport : 9228, script : 'elixir/server.js', name : 'Elixir Loopback Server', path : '/' + 'elixir-server'
  4272. , pidstore : '.elixir-server.elixir.server.pid'
  4273. } )
  4274. }
  4275. if(processedArgs._[2] === 'server' || processedArgs._[2] === 'all'
  4276. || processedArgs._[2] === 'express' // specific microservice name.
  4277. ) {
  4278. startFn( { debugport : 9227, script : 'bin/www', name : 'Express Server', path : '/' + 'chess-server-lib/server'
  4279. , pidstore : '.express.server.pid'
  4280. } )
  4281. }
  4282. if(processedArgs._[2] === 'client' || processedArgs._[2] === 'all') {
  4283. startFn( {
  4284. name : 'Elixir Ember Client', path : '/elixir-client/' + 'client'
  4285. , cmd : ['node_modules/ember-cli/bin/ember', ['s']]
  4286. , pidstore : '.client.server.pid'
  4287. } )
  4288. }
  4289. }
  4290. }
  4291. , 'stop': (label) => {
  4292. const kill = require('tree-kill');
  4293. try{
  4294. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', { encoding: 'utf8'})
  4295. fs.unlinkSync('.elixir-server.elixir.server.pid')
  4296. console.log(serverPid)
  4297. kill(serverPid)
  4298. }
  4299. catch(e){ console.error(e) }
  4300. try{
  4301. serverPid = fs.readFileSync('.express.server.pid', { encoding: 'utf8' })
  4302. fs.unlinkSync('.express.server.pid')
  4303. console.log(serverPid)
  4304. kill(serverPid)
  4305. }
  4306. catch(e){ console.error(e) }
  4307. try{
  4308. serverPid = fs.readFileSync('.client.server.pid', { encoding: 'utf8' })
  4309. fs.unlinkSync('.client.server.pid')
  4310. console.log(serverPid)
  4311. kill(serverPid)
  4312. }
  4313. catch(e){ console.error(e) }
  4314. }
  4315. , 'model' : () => {
  4316. var etask = ()=>{
  4317. var tasks = [
  4318. () => {
  4319. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  4320. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  4321. inherit: true, shell: true
  4322. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  4323. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  4324. , env: ENV
  4325. }).catch((e) => { console.error(e) })
  4326. return p;
  4327. }
  4328. ];
  4329. return any(tasks).then(() => {
  4330. fs.writeFileSync('run.done', 'success') // PB : TODO -- IPC through files is needed only for windows.
  4331. }).catch(() => {
  4332. fs.writeFileSync('run.done', 'error')
  4333. })
  4334. }
  4335. etask.statuslog = statuslog
  4336. etask.selectedinstance = selectedinstance
  4337. etask.processedArgs = processedArgs
  4338. etask.runtimestamp = runtimestamp
  4339. etask.ENV = ENV
  4340. return shell_verse.runElevated(etask)
  4341. }
  4342. , 'use' : () => {
  4343. // use a certain named instance.
  4344. // Eg :
  4345. // 1) elxr use elixir
  4346. // 2) elxr use cihsr
  4347. // If environment is not specified defaults to development.
  4348. // 1) NODE=test elxr use elixir
  4349. /*// Steps
  4350. 1) Delete Config and Data symlinks
  4351. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  4352. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  4353. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  4354. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  4355. */
  4356. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  4357. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  4358. runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
  4359. selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
  4360. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  4361. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') } // PB : TODO -- IPC through files is needed only for windows.
  4362. if (existsSync('config') && existsSync('data')){
  4363. return
  4364. }
  4365. }
  4366. var tasks = [
  4367. () => {
  4368. var promise = new Promise((resolve, reject)=>{
  4369. existslink('config', function(err, data){
  4370. if(data) {
  4371. var p = shell_verse.removeJuncionOrLink('config')
  4372. .then(()=>{resolve(true)})
  4373. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
  4374. }
  4375. else resolve(false)
  4376. })
  4377. })
  4378. return promise;
  4379. },
  4380. () => {
  4381. var promise = new Promise((resolve, reject)=>{
  4382. existslink('data', function(err, data){
  4383. if(data) {
  4384. var p = shell_verse.removeJuncionOrLink('data')
  4385. .then(()=>{resolve(true)})
  4386. .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
  4387. }
  4388. else resolve(false)
  4389. })
  4390. })
  4391. return promise;
  4392. },
  4393. ];
  4394. runconfig.NODE_ENV = ENV.NODE_ENV = ENV.NODE_ENV || runconfig.NODE_ENV || 'development';
  4395. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  4396. if (!runconfig.use && selectedinstance.instanceName) runconfig.use = selectedinstance.instanceName;
  4397. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  4398. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  4399. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  4400. var performPullOrCloneOrCloneForBranch = (def)=>{
  4401. var promise = Promise.resolve(true)
  4402. if (!branch) {
  4403. var dscoverbranchcmd = gitops.getdiscoverbranchcmd({ repo, repodir : instanceroot})
  4404. promise = nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{ branch = __branch})
  4405. .catch((e) => { console.error(e); return { error: true, message: repo } })
  4406. }
  4407. return promise.then(()=>{ return elxr.getPullOrCloneTask(def)() }).catch(e => { console.error( 'performPullOrCloneOrCloneForBranch : Failed ' + e )})
  4408. }
  4409. var performCloneAndCheckout = null;
  4410. // cant use git checkout -b it fails when branch already exists.
  4411. var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  4412. return performPullOrCloneOrCloneForBranch(def).then(()=>{
  4413. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  4414. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  4415. // inherit : true, shell: true,
  4416. cwd: instanceroot + '/' + def.repo
  4417. // , stdio : ignore // Use when we want to silence output completely.
  4418. , runas: processedArgs.runas
  4419. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  4420. }).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 } })
  4421. })
  4422. }
  4423. // var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  4424. // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  4425. var elevatedqueue = [];
  4426. var enqueueOnce = (queue, task, def) => {
  4427. var found = queue.find(element => {
  4428. var keys = Object.keys( element )
  4429. for(var k=0; k < keys.length; k++) {
  4430. if(element[keys[k]] !== def[k]) return false;
  4431. }
  4432. })
  4433. queue.push(function(){ return task(this)}.bind(def));
  4434. }
  4435. var enqueue = (queue, task, def) => {
  4436. queue.push(function(){ return task(def)}.bind(def));
  4437. }
  4438. var mergeSources = {
  4439. 'development': null,
  4440. 'test': 'master',
  4441. 'production': 'master'
  4442. }
  4443. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  4444. // Checkout is reduced to pull provided the current branch is the targetbranch
  4445. if(branch === mergesource) performCheckout = (def) => {
  4446. var dscoverbranchcmd = gitops.getdiscoverbranchcmd({ repo, repodir : instanceroot})
  4447. return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
  4448. if(branch === __branch) return performCloneAndCheckout(def)
  4449. return performPullOrCloneOrCloneForBranch(def)
  4450. })
  4451. .catch((e) => { console.error(e); return { error: true, message: repo } })
  4452. }
  4453. // else performCheckout = (def) => { return performPullOrCloneOrCloneForBranch(def) }
  4454. var performPullOrCloneAll = (def) => {
  4455. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  4456. return nodeShellExec('git', ['pull', '--all'], {
  4457. // inherit : true, shell: true,
  4458. cwd: instanceroot + '/' + def.repo
  4459. , runas: processedArgs.runas
  4460. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  4461. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  4462. }
  4463. var excludeCheckouts = Object.assign(exludeMergeRepos)
  4464. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  4465. // delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  4466. var performMerge = (def) => {
  4467. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  4468. return nodeShellExec('git', ['merge', mergesource], {
  4469. inherit: true, shell: true,
  4470. cwd: instanceroot + '/' + def.repo
  4471. , runas: processedArgs.runas
  4472. }).catch((e) => { console.error(e) })
  4473. }
  4474. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
  4475. // var performRepoOperation = function(def) {
  4476. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  4477. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  4478. // }
  4479. return any(tasks).then(() => {
  4480. var task = ()=>{
  4481. // 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..
  4482. //Switch to target branch
  4483. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  4484. // pull or clone target branch
  4485. .then(() => {
  4486. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  4487. return any(gitRepos.map((repo) => performPullOrCloneAll(repo)))
  4488. })
  4489. // switch to source branch
  4490. .then( () => {
  4491. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  4492. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  4493. })
  4494. //Pull on merge source branch
  4495. .then( () => {
  4496. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  4497. return any(gitRepos.map((repo) => performPullOrCloneAll(repo)))
  4498. })
  4499. //Switch to target branch
  4500. .then( () => {
  4501. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  4502. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  4503. })
  4504. .then( //Merge source branch to target branch
  4505. () => {
  4506. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  4507. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
  4508. })
  4509. }
  4510. task.statuslog = statuslog
  4511. var netask = shell_verse.getNonElevatedTask(task)
  4512. var eltask = ()=> {
  4513. var opts = {
  4514. inherit: true, shell: true
  4515. , cwd : instanceroot
  4516. , env: ENV
  4517. }
  4518. var tasks = [
  4519. () => {
  4520. // Use junctions to avoid npm package issues
  4521. var target = runconfig.use + '-' + 'config' + '-' + ENV.NODE_ENV
  4522. var p = shell_verse.createJuntionOrLink('config', target, opts)
  4523. return p;
  4524. }
  4525. ];
  4526. // if (processedArgs._[1]) {
  4527. tasks = tasks.concat( [
  4528. () => {
  4529. var dataToLink = runconfig.use + '-data' + '-' + ENV.NODE_ENV
  4530. if(!existsSync(dataToLink)) dataToLink = runconfig.use + '-data';
  4531. var p = shell_verse.createJuntionOrLink('data', dataToLink, opts)
  4532. return p;
  4533. }
  4534. ]
  4535. )
  4536. tasks = tasks.concat( [
  4537. () => {
  4538. var dataToLink = runconfig.use + '-clientconfig' + '-' + ENV.NODE_ENV
  4539. if(!existsSync(dataToLink)) dataToLink = runconfig.use + '-clientconfig';
  4540. var p = shell_verse.createJuntionOrLink('clientconfig', dataToLink, opts)
  4541. return p;
  4542. }
  4543. ]
  4544. )
  4545. // }
  4546. return any(tasks).then(()=>{
  4547. // checkout target branch
  4548. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  4549. // pull or clone target branch
  4550. .then(() => {
  4551. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  4552. return any(elevatedRunasRepos.map((repo) => performPullOrCloneAll(repo)))
  4553. })
  4554. // switch to source branch
  4555. .then( () => {
  4556. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  4557. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  4558. })
  4559. //Pull on merge source branch
  4560. .then( () => {
  4561. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  4562. return any(elevatedRunasRepos.map((repodef) => performPullOrCloneAll({repo : repodef.repo, requiresElevation : true })))
  4563. })
  4564. //Switch to target branch
  4565. .then( () => {
  4566. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  4567. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  4568. })
  4569. .then( //Merge source branch to target branch
  4570. () => {
  4571. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  4572. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
  4573. })
  4574. .then(() => {
  4575. fs.writeFileSync('run.done', 'success')
  4576. }).catch(() => {
  4577. fs.writeFileSync('run.done', 'error')
  4578. })
  4579. })
  4580. }
  4581. eltask.statuslog = statuslog
  4582. eltask.selectedinstance = selectedinstance
  4583. eltask.processedArgs = processedArgs
  4584. eltask.runtimestamp = runtimestamp
  4585. var eltask = shell_verse.getElevatedTask(eltask)
  4586. return eltask().then( ()=>{ return netask() })
  4587. }).catch((e) => {
  4588. fs.writeFileSync('run.done', 'error : ' + e)
  4589. })
  4590. // Antibiotic stewardship program.
  4591. // 1st use is fine.
  4592. // Max vials dispense
  4593. // 2nd use Pharmacy needs justification Form.
  4594. // Approval after a certain period of time.
  4595. }
  4596. , 'g' : () => {
  4597. if (processedArgs.h) {
  4598. console.log('elxr g model [modelname] => generate a model named [modelname]');
  4599. console.log('elxr g vmodel [modelname] => generate a model named [modelname]');
  4600. console.log('elxr g vmodel [modelname] --server=true => generate only a server model named [modelname]');
  4601. console.log('elxr g vmodel [modelname] --all=true => default generate server and client model named [modelname]');
  4602. console.log('elxr g => regenerate all known models');
  4603. return
  4604. }
  4605. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  4606. // try {
  4607. // child = child.on('close', () => { process.chdir(label) } );
  4608. // }
  4609. // catch (err) {
  4610. // console.log('chdir: ' + err);
  4611. // }
  4612. // child.on('close', function(){
  4613. // var options = {
  4614. // shell : true
  4615. // , inherit : true
  4616. // // , cwd : '' + process.cwd
  4617. // // , env : ENV
  4618. // };
  4619. // nodeShellExec('git', ['init'], { inherit : true});
  4620. if (0) {
  4621. // PB : TODO -- Special google chrome profile for tests etc.
  4622. nodeShellExec('pwd', { inherit: true });
  4623. // /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"
  4624. // "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
  4625. // "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
  4626. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  4627. "--profile-directory=Profile 1"
  4628. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  4629. }
  4630. // nodeShellExec('npm', ['init', '-y'], options);
  4631. // nodeShellExec('npm', ['init', '-y'], options);
  4632. // })
  4633. var g = {
  4634. 'client': () => {
  4635. // ember new --skip-bower --no-welcome --skip-git -b {{blueprint}}
  4636. console.info('Creating new ember client named : ' + processedArgs._[2]);
  4637. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  4638. stdio: ['pipe', process.stdout, process.stderr],
  4639. inherit: true,
  4640. shell: true,
  4641. cwd: path.dirname(__dirname),
  4642. env : ENV
  4643. })
  4644. },
  4645. 'modelr': () => {
  4646. var tasks = [
  4647. () => {
  4648. var p = nodeShellExec('"ember"', [
  4649. 'g'
  4650. , 'modelr'
  4651. , processedArgs._[2]], {
  4652. inherit: true, shell: true, env: ENV
  4653. }).then(() => {
  4654. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  4655. return true;
  4656. }).catch((e) => { console.error(e) })
  4657. return p;
  4658. },
  4659. () => {
  4660. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  4661. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  4662. chromeprefs = JSON.parse(chromeprefs)
  4663. var previous = chromeprefs.download.default_directory;
  4664. var parentDir = path.dirname(__dirname);
  4665. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  4666. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  4667. // PB : TODO -- detect where chrome is installed.
  4668. // PB : TODO -- set the download dir to the place where files are needed.
  4669. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  4670. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  4671. , '--profile-directory="chess"'
  4672. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  4673. inherit: true, shell: true
  4674. , env: ENV
  4675. }).then(() => {
  4676. chromeprefs.download.default_directory = previous;
  4677. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  4678. return true;
  4679. }).catch((e) => { console.error(e) })
  4680. return p;
  4681. }
  4682. ,
  4683. () => {
  4684. console.log('Browser process should have closed here....')
  4685. return true;
  4686. }
  4687. ]
  4688. any(tasks)
  4689. }
  4690. , 'undefined' : ()=>{
  4691. console.warn('Are you sure you want to refresh all the models.');
  4692. throw 'NOT YET IMPLMENTED'
  4693. }
  4694. , 'vmodel' : (options)=>{
  4695. // node --inspect-brk elxr/index.js g vmodel qlabresults --server=true
  4696. options = options || {
  4697. generate : processedArgs['all'] ? 'all' : processedArgs['server'] ? 'server' : processedArgs['client'] ? 'client' : null
  4698. }
  4699. if(!options.generate) return 'Nothing specified for generation'
  4700. var name = processedArgs._[2];
  4701. if(!name) return 'No name specified for generation'
  4702. var templateverse = `${selectedinstance.root}/bbhverse/__universe__/vmodel`
  4703. // var templateverse = `${selectedinstance.root}/bbhverse/__universe__/vmodel/__base__-server-lib/common/lib`
  4704. var workingtarget = `${selectedinstance.root}/.elxr/run-${runtimestamp}/temp/vmodelworkingdir`
  4705. var destination = `${selectedinstance.root}`
  4706. // Create a tmp working copy for staging the changes.
  4707. return copyrecursive(templateverse, workingtarget).then( r => {
  4708. var base = 'chess' // -- The server base from where this instance was dervied from.
  4709. var patternsubstitutions = [
  4710. { strOrregexp : /(__name__)/g, substitutes : [name]}
  4711. , { strOrregexp : /(__instance__)/g, substitutes : [selectedinstance.instanceName]}
  4712. , { strOrregexp : /(__base__)/g, substitutes : [base]}
  4713. , { strOrregexp : /(__microservice__)/g, substitutes : [selectedinstance.microservice || selectedinstance.instanceName]}
  4714. , { strOrregexp : /(__microclient__)/g, substitutes : [selectedinstance.microclient || `${selectedinstance.instanceName}-client` || 'client']} // PB : TODO -- elixir-client etc... use a config to find the microclient..
  4715. ]
  4716. var options = { source : templateverse, target : workingtarget
  4717. , base , destinationroot : destination, workingtarget
  4718. , processingtype : 'inplace', sourcetype : 'filesystem', patternsubstitutions }
  4719. var actions = [
  4720. fswalk( workingtarget, options
  4721. , [ function(t, o){
  4722. // A series of tasks to be executed on each pattern in patternsubstitutions.
  4723. return any([
  4724. // PB : TODO -- Contentreplace is better addressed in memory instead of file IO so do all regexps in sequence in one shot and then rename.
  4725. ()=>{ return fscontentreplace( t, o ) }
  4726. , ()=>{ return fsrename( t, o ) }
  4727. ])
  4728. }] )
  4729. // Post process links in place.
  4730. , () => dirs((innernode, s, t, o ) => fswalk( path.join(workingtarget, innernode.name), utils.assign({}, o, { innernode }), [ templatelink ] )
  4731. , workingtarget, null, options)
  4732. // Move to the final destination. Whole tree should move only top level folders are required.
  4733. // , () => fswalk( workingtarget, options, [ fsrename ])
  4734. // , () => dirs( ( child, src, target, options )=>{ return fs.renameSync(path.join(src, child.name), path.join(target, child.name) ) }
  4735. // , workingtarget, destination )
  4736. ]
  4737. return any(actions);
  4738. })
  4739. }
  4740. }
  4741. g[processedArgs._[1]]();
  4742. }
  4743. , 'launchui' : () => {
  4744. console.log('-----------------------------')
  4745. console.log('Launching Elxir Admin Console')
  4746. console.log('-----------------------------')
  4747. // shell_verse.getchrome()
  4748. processedArgs.awaitrun = true;
  4749. return shell_verse.launchui()
  4750. // shell_verse.getchrome().then( chrome => {
  4751. // nodeShellExec( `"${chrome}"`, [
  4752. // '--profile-directory="chess"'
  4753. // , `${selectedinstance.root}/elixir-client/elxr-admin-console/html/index.html`], {
  4754. // inherit: true, shell: true
  4755. // , env: ENV
  4756. // })
  4757. // .catch(e => console.dir(e))
  4758. // })
  4759. }
  4760. , 'create' : () => { return createInstance(selectedinstance) }
  4761. , 'httpget' : () => {
  4762. // RESTAPI.get({
  4763. // hostname: 'git.bbh',
  4764. // // port: 443,
  4765. // protocol : 'http:',
  4766. // path: '/',
  4767. // method: 'GET'
  4768. // }, function(data){ console.log(data)}, function(error){ console.log(error)} )
  4769. return createInstance(selectedinstance)
  4770. }
  4771. , 'getuser' : ()=>{ return prerequisites.git.getuser().then(u=>{ console.log(u)}) }
  4772. , 'switch user' : (tousername)=>{ return GIT['switch user'](tousername) }
  4773. }
  4774. var elxrcmd = (function(){
  4775. var __cmdprototype = function(){}
  4776. function subcommandlabelFor(cmd, sub){ return (`${cmd} ${sub || ''}`).trim() }
  4777. var __cmd = {
  4778. interpret() {
  4779. var interpreted = {}
  4780. // Non custom command has universal positiona args.
  4781. processedArgs._[1] ? interpreted.instanceName = processedArgs._[1] : null;
  4782. interpreted.runchoice = processedArgs._[0] || selectedinstance.runchoice;
  4783. // return clioverrides
  4784. // cmds[cmd] = {
  4785. // interpret() {
  4786. // return Object.assign(clioverrides, { cmd, runchoice : 'c' })
  4787. // }
  4788. // , getPossiblePrompts(){ return { cmd, username : true, password : true,
  4789. // instanceName : true, instanceType : true, reposerver : true } }
  4790. // }
  4791. // ... PB : TODO -- use cmd.toArgs
  4792. interpreted.cmd = this.cmd
  4793. return interpreted
  4794. }
  4795. , getPossiblePrompts(){ return { username : true, password : true, instanceName : true, instanceType : true, reposerver : true } }
  4796. , cmdFn : ()=>{ throw "Elxr Unknown command."}
  4797. , finalized : true
  4798. , toArgs : function( o ){
  4799. // PB : TODO -- need to call this before selectedinstance is built. The instanceName is dependent on the specific cmd.
  4800. return o }
  4801. }
  4802. function __createO(o){
  4803. if(o.finalized) return o;
  4804. var subs = Object.keys(cmds[o.cmd].subcommands || {})
  4805. // console.log(subs)
  4806. // console.log(o)
  4807. subs.forEach(sub=>elxrcmd.create( cmds[subcommandlabelFor(o.cmd, sub)] ))
  4808. var created = utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  4809. , {}, __cmd, cmds[o.cmd], o)
  4810. cmds[o.cmd] = created;
  4811. created.cmdFn = oplist[o.cmd] || o.cmdFn || created.cmdFn
  4812. oplist[o.cmd] = created.cmdFn;
  4813. noprerequisites[o.cmd] = created.noprerequisites
  4814. return created.cmdFn;
  4815. }
  4816. function create(o){ return __createO(o) }
  4817. __cmdprototype.create = create;
  4818. return __cmdprototype;
  4819. })()
  4820. Object.keys(oplist).forEach( oper => {
  4821. if(cmds[oper]) return
  4822. cmds[oper] = {}
  4823. // cmds[oper] = {
  4824. // // return a interpreted set of arguments for this cmd run context.
  4825. // interpret() { return { cmd : oper, runchoice : 'c' } }
  4826. // }
  4827. })
  4828. var cmdFns = {
  4829. resetgitconfig, reinit, init, g : oplist['g'], 'get-upstream' : oplist['get-upstream']
  4830. }
  4831. Object.entries(cmds).forEach( ca => {
  4832. ca[1].cmd = ca[0]
  4833. ca[1].cmdFn = ca[1].cmdFn || cmdFns[ca[0]]
  4834. ca[1].noprerequisites = noprerequisites[ca[1].cmd]
  4835. elxrcmd.create( ca[1] )
  4836. })
  4837. var help = `
  4838. ${readme}
  4839. # list of commands... please refer dveloper documentation for ${cliname}
  4840. \r\n\t${
  4841. Object.keys(oplist).join('\r\n\t')
  4842. }
  4843. `;
  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...