|
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014 |
-
-
-
- "use strict";
-
-
- var __g = require('global-this');
- var ENV = Object.assign({}, process.env);
- __g.env = ENV
- ENV.NODE_ENV = (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || 'development'
- const fs = require('fs')
- var path = require('path');
- var utils = require('bbhverse');
- var any = utils.any;
- var Tasq = utils.Tasq
- var statuslog = utils.Traq
- var Traq = utils.Traq
-
- var util = require('util')
-
- var ENV = Object.assign({}, process.env);
-
- var cli = require('./cliverse')
- var nodeShellExec = cli.nodeShellExec;
- const cliargs = utils.cliargs;
- const processedArgs = cliargs(process.argv.slice(2));
-
- const __ALIAS__STAMP__ = '9e7bebe0-1f57-11ec-8f88-778ffeea9d1b'
- const BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
- const runtimestamp = processedArgs.runtimestamp ? (new Date(processedArgs.runtimestamp)).getTime() : (new Date()).getTime();
- function getVersion() { return BUILD_VERSION; }
-
- var defaultowner = 'chess';
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- const https = require('https')
- const http = require('http');
- const { Console } = require('console');
- const { env } = require('process');
- const { validate } = require('uuid');
- const PATTERNAPI = require('serververse').PATTERNAPI
-
- const RESTAPI = (function(){
-
-
- function RESTAPI(){}
-
-
-
-
-
-
-
-
-
-
-
-
- RESTAPI.method = function(options, resolve, reject){
- options.headers = options.headers || { 'Content-Type': 'application/json' }
-
- const data = options.payload ? new TextEncoder().encode( JSON.stringify(options.payload) ) : null
- options.headers = options.payload ? (options.headers || {
- 'Content-Type': 'application/json',
- 'Content-Length': data.length
- }) : (options.headers || {})
- !options.headers.Authorization && usertokens[options.username] ? (()=>{
- options.headers.Authorization = `token ${usertokens[options.username]}`
- delete options.username
- onauthenticated()
- })() : (()=>{
- if(!usertokens[options.username] && !options.isAuthCall) {
- RESTAPI.authenticate( utils.assign( {isAuthCall : true}, options ) , onauthenticated, function(err){
-
- console.error('Auth failed or not accessible')
- reject(err)
- })
- }
- else onauthenticated()
- })()
-
- function onauthenticated(){
-
- var acquirer = getHTTPorS(options)
- const req = acquirer.request(options, res => {
- if (res.statusCode < 200 || res.statusCode >= 300) {
-
- return reject('statusCode = ' + res.statusCode);
- }
- var body = [];
-
- res.on('data', (chunk)=>{ body.push(chunk); });
- res.on('end', ()=>{
- try {
- if(res.headers['content-type'] && res.headers['content-type'].split(';').find( (i)=> i.trim() === 'application/json' )) body = JSON.parse(Buffer.concat(body).toString());
- else body = Buffer.concat(body).toString();
- } catch(e) { return reject(e); }
- resolve(body);
- });
- });
-
- req.on('error', error => { reject(error) })
- if(options.payload) req.write(data)
- req.end()
- }
- }
-
- var usertokens = {}
-
- RESTAPI.authenticate = function(options, resolve, reject){
- options.headers = options.headers || { 'Content-Type': 'application/json' }
-
- if(!usertokens[options.username]) {
-
-
-
- var _options = Object.assign({}, options)
-
-
- _options.method = 'POST'
- _options.headers.Authorization = `Basic ${Buffer.from(`${_options.username}:${_options.password}`).toString('base64')}`
- _options.path = `/api/v1/users/${_options.username}/tokens`
-
- var postoptions = { name : _options.username }
- delete _options.username
- delete _options.password
- _options.payload = postoptions
- RESTAPI.post( _options, function(tokenresp){
-
- usertokens[options.username] = tokenresp.sha1
- resolve(tokenresp)
- },
- function(err){ reject(err) }
- )
- }
- else resolve(tokenresp.sha1)
- }
-
- RESTAPI.put = RESTAPI.get = RESTAPI.post = RESTAPI.method
-
- return RESTAPI
- })();
-
- var getHTTPorS = function(options){ return options.protocol.startsWith('https') ? https : http; }
-
- const ARGUMENTVALIDATOR = (function(){
- const ARGUMENTVALIDATOR = function(){}
- ARGUMENTVALIDATOR.validate = function( tovalidate, assertions, exclusions, defaults ) {
- exclusions = exclusions || {}
- defaults = defaults || {}
-
-
-
-
-
-
-
- tovalidate = utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }, {}, defaults, tovalidate );
- var validator = function(v, mv){
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- const typegroupValidators = {
- '[Primitive]' : function(v, mv){
- var nt = utils.js.nativeType(mv)
-
-
- if(nt !== '[object Boolean]') return mv === v
- else {
- return typeValidators[nt](v, mv)}
- }
- , 'undefined' : function(v, mv){
-
-
-
-
-
-
-
- return typeValidators[utils.js.nativeType(mv)](v, mv)
- }
- }
-
- const typeValidators = {
- '[object Function]' : function(v, mv){ return mv(v) }
- , '[object RegExp]' : function(v, mv) {
- if(mv.g || mv.m) throw 'MULTINLINE and GLOBAL MULTIPLE OCCURENCES NOT YET SUPPORTED'
- return mv.exec(v)
- }
-
-
- , 'arrayany' : function(v, mv){
-
- for(var tm in mv ) {
-
- if(utils.js.nativeType(mv) === ['[object Array]'] && typeValidators['[object Array All Or None]'](v, mv)) return true
- else if(typegroupValidators[utils.js.typeGroup(mv)](v, mv)) return true
- }
- }
- , 'arrayall' : function(v, mv) {
-
- for(var tm in mv ) {
-
-
- if(!typegroupValidators[utils.js.typeGroup(mv)](v, mv)) return false
- }
- return true
- }
- , '[object Symbol]' : function(v, mv) { throw "SYMBOL VALIDATOR NOT YET IMPLEMENTED" }
- , '[object Boolean]' : function(v, mv) {
-
-
- if(mv === true && v === undefined ) { throw `for ${key} value is required but received ${v}` }
- else return true
- }
- , 'undefined' : function(v, mv){ return mv === v }
- }
-
-
- typeValidators['[object Array]'] = typeValidators.arrayany
- typeValidators['[object Array All Or None]'] = typeValidators.arrayall
-
- return typegroupValidators[utils.js.typeGroup(mv)](v, mv)
- };
- Object.keys(assertions).forEach( key => {
- if( tovalidate[key] === undefined && assertions[key]) throw `Improper value for ${key} property value must be present`
- if(!validator( tovalidate[key], assertions[key] )) throw `Improper value ${tovalidate[key]} for ${key} value should be like ${JSON.stringify(assertions[key])}`
-
-
-
-
-
-
-
-
-
-
-
-
- })
- Object.keys(exclusions).forEach( key => {
- if(tovalidate[key] && exclusions[key] ) throw `ARGUMENTVALIDATOR Improper value for ${key} property must value not be present. `
- if(validator( tovalidate[key], exclusions[key] )) throw `ARGUMENTVALIDATOR Improper value ${tovalidate[key]} for ${key} varlue should be like ${JSON.stringify(assertions[key])}`
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- })
- return tovalidate
- }
- return ARGUMENTVALIDATOR
- })()
-
-
- const GITEA = (function(){
-
- function GITEA(){}
- GITEA.APIROOT = '/api/v1'
- GITEA.repository = {
- fork( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
-
-
-
-
-
-
- httpoptions.path = `${GITEA.APIROOT}/repos/${cmdoptions.owner}/${cmdoptions.repo}/forks`
- httpoptions.method = 'POST'
- httpoptions.payload = giteaoptions;
- return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
- }
- , updateattributes( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
- httpoptions.path = `${GITEA.APIROOT}/repos/${cmdoptions.owner}/${cmdoptions.repo}`
- httpoptions.method = 'PATCH'
- httpoptions.payload = giteaoptions;
- return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
- }
- , exists( httpoptions, repo, owner ) {
-
- httpoptions.path = `${GITEA.APIROOT}/repos/${owner}/${repo}`
- httpoptions.method = 'GET'
- return new Promise( (resolve, reject) => {
- RESTAPI.get(httpoptions, function(o){
- if(o.id) return resolve(true)
- return resolve(false) }, reject || function(){ return false } )
- })
- }
- , addcollaborator( httpoptions, repodef, owner, collaborator, permission ) {
- permission = permission || 'Read'
- httpoptions.payload = { permission }
- httpoptions.path = `${GITEA.APIROOT}/repos/${owner}/${repodef.repo}/collaborators/${collaborator}`
- httpoptions.method = 'PUT'
- return new Promise( (resolve, reject) => {
- RESTAPI.put(httpoptions, function(o){
-
- if(o === "") return resolve(true)
- return resolve(false) }, reject || function(){ return false } )
- })
- }
- }
-
- GITEA.user = {
- getuser( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
-
- httpoptions.path = `${GITEA.APIROOT}/users/${httpoptions.username}`
- httpoptions.method = 'GET'
- return RESTAPI.get(httpoptions, giteaoptions, resolve || function(){}, reject || function(){} )
- }
- }
-
- return GITEA
- })();
-
-
- const GIT = (function(){
- function GIT(){}
-
- Object.assign(GIT, {
- 'switch user'(username){
- var httpoptions = new URL(selectedinstance.reposerver);
- httpoptions.username = selectedinstance.username
- httpoptions.password = selectedinstance.password
-
- return GITEA.user.getuser(httpoptions).then(()=>{
- return nodeShellExec('git', ['config', '--replace-all', 'user.name', username],
- {
- inherit: true, shell: true,
- env: ENV
- , cwd: instanceroot + '/' + repo
- , runas: processedArgs.runas
- , title: `'git', ${['config', '--replace-all', 'user.name', username].join(' ')}`
- })
- }
- )
- .catch(e => {
- console.error(e + 'Could not switch. Probably no such user.')
- })
-
- }
- })
-
- return GIT
- })();
-
-
-
-
- (function () {
- "use strict";
- if (!Array.prototype.earlyreduce) {
- Array.prototype.earlyreduce = function(eachcallback, initialValue, donecallback){
- var iterable = this;
- var donecallback = donecallback || (a=>a)
- var result = { value : initialValue === undefined ? iterable[0] : initialValue };
- initialValue === undefined ? null : result = eachcallback(result, element, i, iterable);
-
- for(var i = initialValue === undefined ? 0 : 1; i < iterable.length; i++){
- var element = iterable[i]
- result = eachcallback(result, element, i, iterable)
- if(result.done) return donecallback(result)
- }
-
- return donecallback(result)
- }
- }
- }());
-
- function isWin(){ return /^win/.test(process.platform) }
- if(isWin()) {
- var win_verse = require('./win_verse')
- var shell_verse = win_verse;
- shell_verse.getVersion = getVersion
- }
- else {
- var lin_verse = require('./lin_verse')
- var shell_verse = lin_verse;
- }
-
-
- var gitbash = shell_verse.getbash()
-
-
-
- shell_verse.acquireElevationState().then((isElevated) => {
-
-
- const { existsSync } = require('fs');
- const existslink = function(name, cb){
- fs.lstat(name, (error, stats) => {
- if (error) {
- console.log(error);
- cb(error)
- }
- else {
- console.log("Stats object for: example_directory.txt");
- console.log(stats);
-
-
- console.log("Path is file:", stats.isFile());
- console.log("Path is directory:", stats.isDirectory());
- cb(null, true)
- }
- });
- }
- const existsFolderSync = existsSync;
-
- var hasElxr = function(path, options, cb) {
-
- options = options || {};
-
- var tasks = [
- '/elxr'
- , '/elxr/.git'
-
- , '/elxr/' + __ALIAS__STAMP__
- ]
-
- if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
- var value = existsFolderSync(path + tpath);
- return { value, done : acc && !value };
- }).value }
-
- if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
- var value = existsFolderSync(path + tpath);
- return { value, done : acc && !value };
- }).value );
-
- return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
- var value = existsFolderSync(path + tpath);
- return { value, done : acc && !value };
- }).value);
- }
-
- var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); }
- var uselauncdirasdefaultroot = false;
- if( ENV.NODE_ENV === 'production') uselauncdirasdefaultroot = true;
-
- var thisscriptdir = path.normalize(__dirname);
- var root = undefined
-
-
-
-
-
-
-
-
- console.log('----------------------------------------------------------------')
- console.log('BEFORE DISCOVERY')
- console.log('version : ' + getVersion());
- console.log('process.env.wd : ' + process.env.wd)
- console.log('processedArgs.root : ' + processedArgs.root)
- console.log('----------------------------------------------------------------')
- console.log('wd :' + ENV.wd)
- console.log('PWD :' + ENV.PWD)
- console.log('cwd : ' + process.cwd())
- console.log(`thisscriptdir = ${thisscriptdir}`)
- console.log(`root = ${root}`)
- console.log(`instanceroot = ${instanceroot}`)
- console.log('----------------------------------------------------------------')
-
- if(!processedArgs.root){
- console.log('discovery')
-
-
-
- var launchdir = process.cwd()
- var parentdir = path.dirname( launchdir )
- var parentFolderHasElxr = hasElxrSync(parentdir)
- var launchFolderHasElxr = hasElxrSync(launchdir)
- if( path.normalize(launchdir + '/elxr') === thisscriptdir ) {
-
- if(!launchFolderHasElxr) {
- console.warn('Warning : detected thisscriptdir as subfolder but did not recognize launchdir as a proper root. elxr may not autoupdate...')
-
-
-
- }
- root = ENV.wd = launchdir;
- }
- else if( path.normalize(parentdir + '/elxr') === thisscriptdir ) {
- if(!parentFolderHasElxr) {
- console.warn('Warning : detected thisscriptdir as subfolder but did not recognize parentdir as a proper root. elxr may not autoupdate...')
- }
-
- root = ENV.wd = parentdir;
- }
- else {
- if (launchdir === thisscriptdir) {
-
-
-
-
- if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
-
- root = ENV.wd = parentdir;
-
-
-
-
- }
- else if(!parentFolderHasElxr) {
-
-
-
-
-
-
-
-
-
-
- console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.')
- root = ENV.wd = launchdir;
- }
- else {
-
- root = ENV.wd = parentdir;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- }
-
- }
- else if(launchFolderHasElxr) {
- root = ENV.wd = launchdir;
-
-
- }
- else {
-
-
-
- if(uselauncdirasdefaultroot) {
-
- if(!process.env.wd){
-
- root = ENV.wd = launchdir;
- }
- else root = ENV.wd = process.env.wd
- }
- else {
- var scriptparent = path.dirname( thisscriptdir )
- root = ENV.wd = scriptparent;
- }
- }
- }
- }
- else {
- if(process.env.wd && process.env.wd !== processedArgs.root) throw 'wd and root must match.'
- root = ENV.wd = process.env.wd = processedArgs.root
- }
- var instanceroot = root
- ENV.PWD = ENV.wd
- ENV.NODE_ENV = processedArgs.node_env || (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || 'development'
-
- console.log('----------------------------------------------------------------')
- console.log('AFTER DISCOVERY')
- console.log('version : ' + getVersion());
- console.log('process.env.wd : ' + process.env.wd)
- console.log('processedArgs.root : ' + processedArgs.root)
- console.log('----------------------------------------------------------------')
- console.log('wd :' + ENV.wd)
-
- console.log('PWD :' + ENV.PWD)
- console.log('cwd : ' + process.cwd())
- console.log(`thisscriptdir = ${thisscriptdir}`)
- console.log(`root = ${root}`)
- console.log(`instanceroot = ${instanceroot}`)
- console.log('----------------------------------------------------------------')
-
- function ensureDirectoryExistence(filePath) { return shell_verse.ensureDirectoryExistence(filePath) }
- shell_verse.init({ statuslog, selectedinstance : { root : processedArgs.root }, processedArgs, runtimestamp, ENV })
-
-
- var runlogjson = `${processedArgs.root}/.elxr/run-${runtimestamp}/run.log`
- ensureDirectoryExistence(runlogjson)
- fs.writeFileSync(runlogjson, JSON.stringify( { message : `Started ${runtimestamp}`, success:true}))
- Tasq.addlistener((e)=>{ fs.writeFileSync(runlogjson, ', ' + JSON.stringify( e ), { 'flag': 'a+' }) })
-
-
-
-
-
-
-
-
-
- var noprerequisites = {
- add : true, 'set-url' : true, 'repo-relocate' : true
- , remote : true, 'c' : true, 'h' : true
- , httpget : true, getuser : true
- , 'switch user' : true
- , 'switch' : true
-
- }
-
-
- var getowner = (args, selectedremote) => {
- selectedremote = selectedremote || {}
- return args.owner || selectedremote.owner || defaultowner
- }
- var __default = {
-
- repos : [
- { repo : 'ember-masonry-grid' }
- , { repo : 'bbhverse' }
- , { repo : 'clientverse' }
- , { repo : 'serververse' }
- , { repo : 'elxr' }
- , { repo : 'ember-searchable-select' }
- , { repo : 'loopback-component-jsonapi' }
- , { repo : 'loopback-jsonapi-model-serializer' }
- , { repo : 'loopback-connector-mysql' }
- , { repo : 'loopback-connector-ds' }
- , { repo : 'ember-service-worker' }
- , { repo : 'ember-service-worker-asset-cache' }
- , { repo : 'ember-service-worker-cache-fallback' }
- , { repo : 'ember-service-worker-index' }
- , { repo : 'ember-sw-client-route' }
- , { repo : 'global-this' }
- ]
-
- , elevated : [ { repo : 'chess-server-lib', requiresElevation : true } ]
- , exludeMergeRepos : { }
- };
-
- var regexreplaceall = function(content, ps){
- var repmatches
- var replaced = content;
- while (repmatches = ps.strOrregexp.exec(content)) {
-
- if(content.length > 0) {
- var replacement = repmatches[0]
- for(var m = 1; m < repmatches.length; m++) {
- replacement = replacement.replace(repmatches[m], ps.substitutes[m-1])
- }
- replaced = replaced.replace( repmatches[0], replacement )
- }
- }
- return replaced
- }
-
- var cmds = {
- sqlpreprocess : {
- noprerequisites : true
- , cmdFn : function(args){
-
-
-
- return PATTERNAPI.includesql('', args._[1]).then(sqlquery => {
-
-
- fs.writeFileSync(args._[1].replace('.i', ''), sqlquery + "\n" , { encoding: 'utf8'})
-
- return sqlquery
- })
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- }
- , toArgs : function( o ){ return o }
- , interpret() { return { cmd : processedArgs._.slice(0, 1) } }
- }
- , remote : {
- interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
- , { cmd : processedArgs._.slice(0, 2).join(' '), runchoice : 'c' }) }
- , noprerequisites : true
- , independentcmd : true
- }
- , start : {
- interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
- , { cmd : 'start', runchoice : 'c'
- , node_env : ENV.NODE_ENV, root : ENV.wd, instanceType : ENV.NODE_ENV
- })}
- , toArgs : function( o ){
- return o
- }
- }
- , 'remote refresh' : {
-
- interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
- , { cmd : 'remote refresh', runchoice : 'c' }) }
- , noprerequisites : true
- , independentcmd : true
-
- , toArgs : function( o ){
- return o
- }
- }
- , 'remote set-url' : {
-
- interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
- , { cmd : 'remote set-url', runchoice : 'c' }) }
- , noprerequisites : true
- , independentcmd : true
-
- }
- , 'remote add' : {
-
- interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
- , { cmd : 'remote add', runchoice : 'c' }) }
- , noprerequisites : true
- , independentcmd : true
-
- }
- , 'remote remove' : {
-
- interpret() { return utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
- , { cmd : 'remote remove', runchoice : 'c' }) }
- , noprerequisites : true
- , independentcmd : true
- }
- , 'addcollaborator' : {
-
-
- cmdFn : function(args){
-
- var __each = function(args){
- var collaborator = args.collaborator;
- if(!collaborator) {console.error('Error : collaborator required'); throw 'Error : collaborator required' }
- var repo = args.repo
- var repodef = selectedinstance.reposindexed[repo];
- var remotename = 'chess'
- if(!repodef) return
-
- var remotenames = (selectedinstance.selectedremotes || []).concat( selectedinstance.permanentremotes )
- var remotes = selectedinstance.reposerverinstances[selectedinstance.reposerver].remotes
-
-
-
-
-
-
- var reposmanfiest = utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
- , {}, selectedinstance, loadmanifest( selectedinstance.root + '/' + repo
- , { username : selectedinstance.username, instanceName : selectedinstance.instanceName
- , node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver }
- ))
-
- if( !reposmanfiest.error ) {
- var reporemotenames = remotenames.concat(reposmanfiest.selectedremotes || []).concat( reposmanfiest.permanentremotes || [] )
- var reporemotes = utils.assign(remotes, reposmanfiest.reposerverinstances[selectedinstance.reposerver].remotes)
- }
- else {
- var reporemotenames = remotenames
- var reporemotes = remotes
- }
-
- var remote = reporemotes[remotename]
- var reposerver = repodef.server || remote.server || selectedinstance.reposerver
-
-
- var auth = repodef.username ? repodef : remote.username ? remote : selectedinstance.reposerverinstances[reposerver].username ? reposerver : selectedinstance;
- var httpoptions = new URL(reposerver);
- httpoptions = {
- hostname: httpoptions.hostname
- , protocol : httpoptions.protocol
- }
- httpoptions.username = auth.username
-
- httpoptions.password = (auth.password || selectedinstance.password || '')
-
-
- return GITEA.repository.addcollaborator(httpoptions, repodef, remote.owner, collaborator).then( v => {
- if(v === true) {
- console.log('-----------------------------------------------------')
- console.log('addcollaborator successful for ' + repo + ' ' + collaborator)
- console.log('-----------------------------------------------------')
- }
- } )
- }
-
- var promises = []
- var repos = Object.keys(selectedinstance.reposindexed)
- repos.forEach(repo => { promises.push(__each({ repo, collaborator : args._[2]})) })
- return Promise.all(promises).then(pr => { console.log('addcollaborator done') })
- }
- }
- , 'isurlaccessible' : {
- noprerequisites : true
- , independentcmd : true
- , toArgs : function( o ){
- return { url : o._[1] }
- }
- }
- , resetgitconfig : {
-
-
- interpret() { return { cmd : 'resetgitconfig' } }
- , noprerequisites : true
- , independentcmd : true
- }
- , reinit : {
-
-
-
- interpret() { return { cmd : 'reinit' } }
- , noprerequisites : true
- , independentcmd : true
- , requiresElevation : true
-
- }
- , init : {
-
-
-
- interpret() { return { cmd : 'init' } }
- , noprerequisites : true
- , independentcmd : true
- , requiresElevation : true
-
- }
- , switch : {
- interpret() {
- return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2]
- , reposerver : __default.reposerver
- }
- }
- , getPossiblePrompts(){ return { username : true, reposerver : 'http://git.bbh' } }
- }
- , 'switch user' : {
- interpret() {
- return { cmd : subcommandlabels['switch'], runchoice : 'c', username : processedArgs._[2] }
- }
- , getPossiblePrompts(){ return { username : true } }
- }
-
-
- , 'users' : {
-
- subcommands : { list : {} }
- , cmdFn : ()=>getCredentials()
- , cmd : 'users'
- , noprerequisites : true
- }
- , 'users list' : {
- cmdFn : ()=>getCredentials()
- , cmd : 'users list'
- , noprerequisites : true
- }
- , 'get-upstream' :{
-
-
- cmd : 'get-upstream'
- , noprerequisites : true
- , independentcmd : true
- , interpret() { return { cmd : 'get-upstream' } }
- }
- , 'g' : {
- cmd : 'g'
- , noprerequisites : true
- }
- , 'link' : {
- 'cmd' : 'link'
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- , cmdFn : function( cmdopts ){
-
- targetfilename = cmdopts.targetfilename || processedArgs._[1]
-
- if(!targetfilename) return Promise.reject('error no file provided for linking')
- targetdir = cmdopts.targetdir || ENV.wd
- sourecpathandfile = cmdopts.sourecpathandfile || path.normalize(`../../node_modules/chess-server-lib/common/models/${targetfilename}`)
-
- var tasks = [
- () => {
-
- var p = nodeShellExec('mklink', [path.normalize(`${targetdir + '/' + targetfilename}`), sourecpathandfile], {
- inherit: true, shell: true
- , cwd : targetdir
- , env: ENV
- }).catch((e) => { console.error(e) })
- return p;
- }
- ];
- var etask = ()=>{
- return any(tasks).then(() => {
- fs.writeFileSync('run.done', 'success')
- }).catch(() => {
- fs.writeFileSync('run.done', 'error')
- })
- }
- etask.statuslog = statuslog
- etask.selectedinstance = selectedinstance
- etask.processedArgs = processedArgs
- etask.runtimestamp = runtimestamp
- etask.ENV = ENV
- return shell_verse.runElevated(etask)
- }
- , noprerequisites : true
- , privileged : true
- }
- , 'tshell' : {
-
- toArgs : function( o ){ return o }
- , cmdFn : function( cmdopts ){
-
- var tasks = [
- () => {
- return nodeShellExec(`"${gitbash}"`, ['-c', `"${processedArgs._.join(' ')}"` ]
- , {
-
-
-
- inherit: true, shell: true, benign : true, env: ENV, runas: processedArgs.runas
- }
- ).catch(function(e){
- console.error( JSON.stringify(e) );
- throw e
- })
- }
- ];
-
- var etask = ()=>{
- return any(tasks).then(() => {
- fs.writeFileSync('run.done', 'success')
- }).catch(() => {
- fs.writeFileSync('run.done', 'error')
- })
- }
- etask.statuslog = statuslog
- etask.selectedinstance = { root : processedArgs.root }
- etask.processedArgs = processedArgs
- etask.runtimestamp = runtimestamp
- etask.ENV = ENV
-
-
- if(cmdopts.runas) {
- return shell_verse.runElevated(etask)
- }
- else return shell_verse.runNonElevated(etask)
- }
- }
- }
-
- function interpret() {
- var interpreted = this
-
- processedArgs._[1] ? interpreted.instanceName = processedArgs._[1] : null;
- interpreted.runchoice = interpreted.cmd ? 'c' : null
-
-
-
-
-
-
-
-
-
-
-
- return interpreted
- }
-
- var interpretrun = function(){
- var cmd = processedArgs._[0];
-
- var interpretations = {
- 'git' : function transparentshell(){
-
- return { cmd : 'tshell', noprerequisites : true }
- }
- }
- var tshell = interpretations[cmd];
- if(tshell) return tshell();
- return cmds[cmd] && cmds[cmd].interpret ? cmds[cmd].interpret() : (function(){
- return cmds[cmd] = utils.assign(cmds[cmd] || {}, interpret.call({ cmd, toArgs : function( o ){
-
- return o } }))
- })()
- }
-
- var chessinstances = { current_run : {} };
- var clioverrides = interpretrun()
- clioverrides = utils.assign( { cmd : processedArgs._[0], node_env : ENV.NODE_ENV, root : ENV.wd, instanceType : ENV.NODE_ENV }
- , clioverrides, cmds[clioverrides.cmd].toArgs(processedArgs), { root : ENV.wd } )
- function acquirelocalinstances(selected){
-
-
-
- try { var existinglocalinstances = require(path.normalize(selected.root + '/chessinstances.js'))}
- catch(e){
- console.warn( 'Local instances not found.' )
- var existinglocalinstances = { current_run : {}, error : true }
- }
-
- chessinstances = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }, existinglocalinstances);
-
- return chessinstances
- }
-
- function findlocalinstances(chessinstances, instanceoptions){
-
- ['' , '../' , '../../' ].
- earlyreduce( ( reduced, p, i, a )=>{
- var localinstancesPath = `${instanceroot}/${p}.elxr`;
- if(existsSync( localinstancesPath )) {
- try {
- acquirelocalinstances( { root : `${instanceroot}/${p}` } )
- if(chessinstances.error) {
- delete chessinstances.error; delete chessinstances.e
- return {}
- }
- return Object.keys(chessinstances).earlyreduce( ( reduced, instanceName) => {
- return Object.keys(chessinstances[instanceName]).earlyreduce( (reduced, instanceType) => {
-
- if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize( instanceroot) ) {
- instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType])
- return {
- value : chessinstances[instanceName][instanceType]
- , done : true
- };
- }
- })
- })
- }
- catch(e){
- return { }
- }
- }
- else return { }
- }
- )
- }
-
- var mergeObjByKey = function(arrOfObjs, keyName) {
-
- var keyedDistinct = {}
- var distinctArrOfObjs = []
-
- arrOfObjs.forEach( o => {
- if(o) (keyedDistinct[o[keyName]] || (keyedDistinct[o[keyName]] = []) ).push(o)
- })
- Object.keys(keyedDistinct).forEach(key => {
- distinctArrOfObjs.push( utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
- , ...keyedDistinct[key] ) )
- })
-
- return distinctArrOfObjs;
- }
-
- var cacheWriteInstanceConfig = function(chessinstances, instanceroot, selectedinstance){
- if(selectedinstance) {
-
- var instanceName = selectedinstance.instanceName ;
- var node_env = selectedinstance.node_env;
-
-
-
- chessinstances[instanceName][node_env].repos = mergeObjByKey(chessinstances[instanceName][node_env].repos || [], 'repo') ;
- chessinstances[instanceName][node_env].elevated = mergeObjByKey(chessinstances[instanceName][node_env].elevated || [], 'repo') ;
- }
- fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
- }
-
- var loadmanifest = function( mpath, moverrides ){
- try {
-
- return utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
- , {}, require(path.normalize( mpath + '/repo-manifest'))( {utils}, null, moverrides ))
-
- }
- catch(e){
-
- return utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }, { error : true, e }, moverrides)
- }
- }
- var getReconfirmAll = ()=>{return { instanceName : true, instanceType : true, reposerver : true, username : true, password : true } }
-
- if(clioverrides.reconfirm) {
- var reconfirm = getReconfirmAll()
- }
- else { var reconfirm = {}; }
-
- var shouldPrompt = function(k, possiblePrompts, target){
- return ((possiblePrompts[k] !== undefined && possiblePrompts[k] !== null) && target[k] !== possiblePrompts[k]
- || (possiblePrompts[k] === undefined || possiblePrompts[k] === null) && (target[k] === undefined || target[k] === null)
- || reconfirm[k])
- }
-
- var getPromptableAsyncPropDescriptor = function(propName, promptable){
- return {
- get (){
- return any( promptable.dependencies || [] ).then(()=>{
-
- return cli.prompt( promptable.choices, promptable.label, promptable.defaultchoice, promptable.selectedchoice ).then(propValue => {
-
- var asyncprop = Promise.resolve(propValue)
- if(promptable.interpret){
- asyncprop = promptable.interpret(propValue)
- }
-
- return asyncprop.then(
- ()=>{
- Object.defineProperty(this, propName, {
- value: propValue,
- writable: true,
- configurable : true,
- enumerable : true
- });
- return propValue
- }
- )
- })
- } )
-
- }
-
-
-
-
-
-
-
-
-
- , configurable : true
- , enumerable : true
- }
- }
-
- var getBoundEachPrompt = function(target, possiblePrompts, promptables, choices, promptsfilter) {
- return function(prompts, k, i, a){
-
-
-
-
-
- if( shouldPrompt(k, possiblePrompts, target) ) {
- delete reconfirm[k];
-
-
- prompts.push(async ()=>{
-
-
-
-
- console.log('----------------------------------------------------')
- console.log(k)
- console.dir(choices[k])
- if(!promptables[k]) promptables[k] = {}
- promptables[k].choices = choices[k]
- Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
- return await target[k]
- })
- }
- delete possiblePrompts[k]
- return prompts
- }
- }
-
-
- var performPullOrClone = (repodef, branch, owner, errHandler, elevatedBatch, regularBatch) => {
- var __inelevatedBatch = elevatedBatch, __inregularBatch = regularBatch;
- var pT = getPullOrCloneTask(repodef, branch, owner, errHandler, elevatedBatch, regularBatch)
-
-
-
-
-
-
- return pT()
- }
-
- var oplist = {
- 'h': () => { console.log(elxr.help()); return '-h' }
- , 'clean' : () => {
-
- var tasklist = [];
- dirs( (dir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + dir.name })()), instanceroot )
- return Promise.all(tasklist)
- }
-
- , 'isurlaccessible' : function(args){
-
- args = args || {}
- var u = new URL(args.url || selectedinstance.reposerver)
- console.log(u)
- var httpoptions = { hostname : u.host || 'git.bbh.org.in', protocol : u.protocol || 'https'
- , method : 'GET'
- , username : args.username || selectedinstance.username || 'chess'
- , password : selectedinstance.password || 'chess'
- }
- httpoptions.path = args.path || `/`
- return new Promise(function( resolve, reject ){
- RESTAPI.get(httpoptions, function(){
- console.log('URL is accessible')
- resolve(true)
- }, function(){
- console.error('URL is not accessible')
- resolve(false)
- })
- })
- }
- , 'reset': () => {
-
-
-
- const fs = require('fs')
- const wipeDependencies = (__package) => {
- const file = fs.readFileSync(__package + '/package.json')
- const content = JSON.parse(file)
- for (var devDep in content.devDependencies) {
- if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
- content.devDependencies[devDep] = '*';
- }
- }
- for (var dep in content.dependencies) {
- if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
- content.dependencies[dep] = '*';
- }
- }
- fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
- }
-
- var repos = ['client'];
-
- repos.forEach(wipeDependencies)
-
-
-
-
-
- }
- , 'upgrade': () => {
- console.log('upgrade.......')
- var tasks = [
- () => {
- var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
- inherit: true, shell: true
- , env: ENV
- }).catch((e) => { console.error(e) })
- p.position = 1;
- console.log('One')
- return p;
- }
- , () => {
- var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
- inherit: true, shell: true
- , env: ENV
- }).catch((e) => { console.error(e) })
-
- p.position = 2;
- console.log('Two')
- return p;
- }
- , () => {
- var p = nodeShellExec('npm', ['install', '-g', 'n'], {
- inherit: true, shell: true
- , env: ENV
- }).catch((e) => { console.error(e) })
- p.position = 3;
- console.log('Three')
- return p;
- }
- , () => {
- var p = nodeShellExec('n', ['latest'], {
- inherit: true, shell: true
- , env: ENV
- }).catch((e) => { console.error(e) })
- p.position = 4;
- console.log('Four')
- return p;
- }
- ]
- any(tasks)
- console.log('.......done')
- console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
- console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
- console.info('Uninstalling existing ember globally');
- var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
- stdio: ['pipe', process.stdout, process.stderr],
- inherit: true,
- shell: true,
- cwd: path.dirname(__dirname),
- env: ENV
- })
- step1.on('close', () => {
- console.info('Installing ember globally');
- var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
- stdio: ['pipe', process.stdout, process.stderr],
- inherit: true,
- shell: true,
- cwd: path.dirname(__dirname),
- env: ENV
- })
-
- step2.on('close', () => {
- nodeShellExec('cmd', ['/c', 'ember', '--version'], {
- stdio: ['pipe', process.stdout, process.stderr],
- inherit: true,
- shell: true,
- cwd: path.dirname(__dirname),
- env: ENV
- })
- })
- })
- }
- , 'push': () => {
- if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
-
-
-
-
-
-
-
-
-
-
-
-
-
- var repo = processedArgs._[1];
- var remote = 'origin'
-
- var sequentialTaskShellCommands = [];
- if (!existsSync(`Z:/${repo}.git`)) {
- sequentialTaskShellCommands = [
-
-
-
-
- ['pwd', { cwd: 'Z:', inherit: true }]
- , ['mkdir', [`${repo}.git`], {
- cwd: `Z:`
- , inherit: true, shell: true
- , env: ENV
- }]
- , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
- , ['git', ['init', '--bare'], {
- cwd: `Z:/${repo}.git`
- , inherit: true, shell: true
- , env: ENV
- }]
-
- , ['git', ['remote', 'rename', remote, 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
- console.log(`Ignoring ${remote} rename error : ` + err); return true;
- }]
- , ['git', ['remote', 'add', remote, `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
-
-
- ]
- if (!existsSync(`Z:`)) {
- sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
- inherit: true, shell: true
- , env: ENV
- }])
- console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
-
- }
- }
-
- sequentialTaskShellCommands.push(['git', ['push', remote, 'master'], { cwd: `${instanceroot + '/' + repo}` }])
-
-
- var tasks = [];
- sequentialTaskShellCommands.forEach(shellcmd => {
-
- tasks.push(() => {
-
- var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
- return p;
- })
- })
- any(tasks);
-
- }
- , 'is-git-repo': (dir) => {
- return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
- }
-
-
-
- , 'remote': (args) => {
-
-
-
- if(!processedArgs.v) return false;
-
- var serial_perform = (repo) => {
- var options = { cwd: instanceroot + '/' + repo }
-
- return [
- ['git', ['remote', '-v'], options]
- ]
- }
-
- var x = (args) => {
- var tasq = () => {
-
- return nodeShellExec.apply(null, args).catch(e => {
-
- console.error(tasq.toString())
- })
- }
- tasq.toString = function(){
- return JSON.stringify(args)
- }
- return tasq;
- }
-
- var perform = (dir) => {
- return any(serial_perform(dir.name).map(x))
- }
-
- dirs(perform)
- }
-
- , 'remote set-url': (args) => {
-
- var __args = {
- remotename : args.remotename || processedArgs._[2]
- , url : args.url || processedArgs._[3]
- , branch : args.branch || processedArgs._[4] || 'master'
- }
- __args.upstream = args['upstream'] || processedArgs._[5] || `${__args.remotename}/${__args.branch}`
-
-
-
-
-
- var pushable = processedArgs.pushable || (args.remote ? args.remote.pushable : false) || args.pushable;
- var remotename = __args.remotename
- var url = __args.url
- var branch = __args.branch
- var upstream = __args.upstream
- console.log('remotename : ' + args.remotename)
-
- var serial_perform_git_seturl = (reponame) => {
- var options = { cwd: instanceroot + '/' + reponame }
-
- var serialcmds = [
- ['git', ['remote', 'set-url', remotename, url + '/' + reponame], { cwd: instanceroot + '/' + reponame }]
- ]
- if (!pushable) {
- serialcmds.push(['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + reponame }])
- }
-
- var requiresElevation = selectedinstance.elevated.find( r => r.repo === reponame)
- serialcmds.push(['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + reponame, requiresElevation }])
- serialcmds.push(['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }])
-
- return serialcmds
- }
-
- var x = (xargs) => {
- var tasq = () => {
-
- var task = (onsuccess, onerror)=>{
- return ()=>{
- return nodeShellExec.apply(null, xargs).then( onsuccess ).catch(e => {
-
-
- if(e.messages[0].search('No such remote') > -1 ){
- console.log(remotename + ' Remote doesnt exist will add.')
- return oplist['remote add']( args )
- }
- console.error(util.inspect(e) + ' ' + tasq.toString())
- })
- }
- }
-
- if(xargs[2].requiresElevation){
- if(!isElevated) {
- var etask = task( ()=>{ return remotename } )
- etask.statuslog = statuslog
- etask.selectedinstance = selectedinstance
- etask.processedArgs = processedArgs
- etask.runtimestamp = runtimestamp
- etask.ENV = ENV
- return shell_verse.runElevated(etask)
- }
- }
- return task(
- () => { fs.writeFileSync('run.done', 'success')}
- , () => { fs.writeFileSync('run.done', 'error') }
- )()
- }
- tasq.toString = function(){ return JSON.stringify(args) }
- return tasq;
- }
- var perform_git_seturl = (dir) => {
- return oplist['is-git-repo'](dir).then((logEntry) => {
- return any(serial_perform_git_seturl(dir.name).map(x))
- }).catch((e) => {
- console.log(e + ' Failed not recognized as a git repo : ' + dir.name)
- })
- }
-
- if(args.dir) return perform_git_seturl(args.dir)
- else return dirs(perform_git_seturl)
- }
-
-
-
-
-
-
- , 'remote exists': (args) => {
- var __args = {
- remotename : args.remotename|| processedArgs._[2]
- , url : args.url || processedArgs._[3]
- , branch : args.branch || processedArgs._[4]
- }
-
- var options = args.repo ? { cwd: instanceroot + '/' + args.repo } : {}
-
-
- var commands = [
-
-
- [
-
- 'git', ['config', `remote.${__args.remotename}.url`]
- , utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
- , {
- benign : args.benign, ignorefailures : args.ignorefailures,
- evaluateResult : function(err, result){
- return [
- +result.code === 0
- , result
- ]
- }
- } , options) ]
- ]
- var mapped = commands.map(getshelltask)
- mapped.push( function(prevserialtaskresult) {
- var pt = [false , null]
- if(prevserialtaskresult.error) {
-
- pt[1] = prevserialtaskresult.error[1]
- }
- else pt = prevserialtaskresult;
-
- console.dir(prevserialtaskresult)
- return getshelltask(['git', ['ls-remote', `${__args.url}`], utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
- , {
- benign : args.benign, ignorefailures : args.ignorefailures,
- evaluateResult : function(err, result){
- if(+result.code !== 0) return [pt, [ false, result]]
-
- return [pt, [true, result] ]
- }
- } , options) ])().catch( e => {
- console.error(e)
- return [pt, [ false, null]]
- })
- })
- return any(mapped, true, false, { accumulatedresults : [] }).then( allresolved => {
-
- console.dir(allresolved)
- !allresolved[0][0] && !allresolved[1][0] ? console.log('was not added as a remote and url is currently inaccessible.')
- : allresolved[0][0] && allresolved[1][0] ? console.log('was added as a remote and url is accessible.')
- : allresolved[0][0] && !allresolved[1][0] ? console.log('was added as a remote but url is currently inaccessible.')
- : console.log('was not added as a remote but url is currently accessible.')
-
- return !allresolved[0][0] && !allresolved[1][0] ? [0, 0]
- : allresolved[0][0] && allresolved[1][0] ? [1, 1]
- : allresolved[0][0] && !allresolved[1][0] ? [1, 0]
- : [0, 1]
- }).catch(e => {
- console.log(e)
- return [0, 0]
- })
- }
-
- , 'remote refresh' : (args) => {
-
- var url = args._[2] || selectedinstance.reposerver
- return oplist['isurlaccessible']({ url }).then(( baccess )=>{
- if(!baccess) {
- var reposerver = selectedinstance.reposerverinstances[url]
- if(!reposerver.external) {
-
- console.log('Internal server not accsssible. Will switch to external')
-
- url = reposerver.externalreposervers[0]
- }
- else {
- console.log('External server not accsssible. Will switch to interal')
-
- url = reposerver.internalreposervers[0]
- }
- return oplist['isurlaccessible']({ url }).then(( baccess )=>{
- if(!baccess) {
- console.log('Neither internal nor external servers are accessible.... Presenting choices...')
- console.log('PB : TODO -- Present appropriate choices...')
-
- }
- return dorefresh()
- })
- }
- dorefresh()
- console.log(baccess)
- }).catch((err)=>{ console.error(err) })
-
- function dorefresh(){
-
-
-
-
-
-
-
- args = args || {}
- var __args = {
- url : args.url || processedArgs._[2] || selectedinstance.reposerver
-
- }
-
- var serial_perform = (repo) => {
-
-
- var options = { cwd: instanceroot + '/' + repo }
- console.log('serial_perform : ' + repo)
-
- return [
- ['git', ['remote', '-v'], options]
- ]
-
-
- }
-
- var x = (args) => {
-
-
- var tasq = () => {
- console.log('--------------------------')
- console.log(args)
- return nodeShellExec.apply(null, args).catch(e => {
- console.log('caught error ------------------------' + JSON.stringify(e))
-
- console.error(tasq.toString() + args[2].cwd)
- })
- }
- tasq.toString = function(){
-
- return JSON.stringify(args)
- }
- return tasq;
- }
-
- var remotenames = (selectedinstance.selectedremotes || []).concat( selectedinstance.permanentremotes )
- var remotes = selectedinstance.reposerverinstances[__args.url].remotes
-
-
- function perform_remote_refresh(dir){
- var repo = dir.name
- var ___args = {url : __args.url, repo}
- if(repo === '.elxr') return Promise.resolve(true)
- if(repo === '.git') return Promise.resolve(true)
- if(repo === 'Downloads') return Promise.resolve(true)
-
-
- var reposmanfiest = utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
- , {}, selectedinstance, loadmanifest( selectedinstance.root + '/' + repo
- , { username : selectedinstance.username, instanceName : selectedinstance.instanceName
- , node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver }
- ))
-
- if( !reposmanfiest.error ) {
- var reporemotenames = remotenames.concat(reposmanfiest.selectedremotes || []).concat( reposmanfiest.permanentremotes || [] )
- var reporemotes = utils.assign([], remotes, reposmanfiest.reposerverinstances[___args.url].remotes)
- }
- else {
- var reporemotenames = remotenames
- var reporemotes = remotes
- }
-
- return (()=>{
- var promises = []
-
- return any(serial_perform(repo).map(x)).then(()=>{
- var branch = args.branch || 'master'
- reporemotenames.forEach(rm =>{
- console.log('Processing : ' + rm + ' ' + dir.name)
-
-
-
-
- promises.push( ((rm) => {
- var remotename = rm
- var repodef = selectedinstance.reposindexed[repo];
- if(!repodef) return
-
-
-
-
-
- var remote = reporemotes[remotename]
-
-
- var owner = getowner(repodef, remote)
-
- var reposerver = repodef.server || remote.server || selectedinstance.reposerver
-
- var auth = repodef.username ? repodef : remote.username ? remote : selectedinstance.reposerverinstances[reposerver].username ? reposerver : selectedinstance;
-
- var httpoptions = new URL(reposerver);
- httpoptions = {
- hostname: httpoptions.hostname
- , method: 'GET'
- , protocol : httpoptions.protocol
- }
- httpoptions.username = auth.username
- httpoptions.password = (auth.password || selectedinstance.password || '')
-
- var repourl = reporemotes[remotename].url + '/' + repo
-
-
-
- return GITEA.repository.exists( httpoptions, repo, owner ).then((bexists)=>{
- console.log(remotename + ' ' + repourl)
- if(bexists) {
- console.log(remotename + ' ' + repourl + ' is accessible')
- return ((remotename)=>{
- return oplist['remote set-url']( { dir, remotename, url : reporemotes[remotename].url, remote
- , repodef : selectedinstance.reposindexed[repo] } )
- })(remotename)
-
-
- }
- }).catch(e => {
- console.warn(remotename + ' ' + repourl + ' ' + e)
- })
- })(rm)
- )
- })
- return Promise.all(promises).then( accessibleremotes => {
- while(!accessibleremotes[accessibleremotes.length -1] && accessibleremotes.length) accessibleremotes.splice(accessibleremotes.length -1, 1)
-
- if(accessibleremotes.length) {
- ((remotename)=>{
- var upstream = `${remotename}/${branch}`
- var remote = reporemotes[remotename]
- return oplist['remote set-url']( { dir, remotename, url : reporemotes[remotename].url, remote
- , upstream
- , repodef : selectedinstance.reposindexed[repo] } )
- })( accessibleremotes[accessibleremotes.length -1] )
- }
- }).catch((e) => { console.log('Processing Error : ' + dir.name); console.error(e); return { error: true, message: repo } })
- })
-
- })()
- }
-
- if(isElevated) {
- var elevatedpromises = []
- selectedinstance.elevated.forEach( r => { elevatedpromises.push(perform_remote_refresh({ name : r.repo })) } )
- return Promise.all(elevatedpromises)
- }
- else return dirs(perform_remote_refresh)
- }
- }
-
- , 'remote add': (args) => {
-
-
-
-
-
-
-
-
-
-
-
-
-
- var __args = {
- remotename : args.remotename|| processedArgs._[2]
- , reponame : args.reponame || (args.repodef ? args.repodef.repo : undefined)
- , url : args.url || processedArgs._[3]
- , branch : args.branch || processedArgs._[4] || 'master'
- }
- __args.upstream = args['upstream'] || processedArgs._[5] || `${remotename}/${branch}`
-
- var remotename = __args.remotename
- var url = __args.url
- var branch = __args.branch
- var upstream = __args.upstream
-
- var pushable = processedArgs.pushable || (args.remote ? args.remote.pushable : false) || args.pushable;
-
- var serial_perform_git_add = (reponame) => {
- var options = { cwd: instanceroot + '/' + reponame }
-
- if (pushable) {
- var gacmds = [
- ['git', ['remote', 'add', remotename, url + '/' + reponame], { cwd: instanceroot + '/' + reponame }]
- , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + reponame }]
-
- ]
- }
- else {
-
- var gacmds = [
- ['git', ['remote', 'add', remotename, url + '/' + reponame], { cwd: instanceroot + '/' + reponame }]
- , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + reponame }]
- , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + reponame }]
-
-
- ]
- }
- if(__args['upstream']) gacmds.push(['git', ['branch', `--set-upstream-to=${upstream}`, branch], { cwd: instanceroot + '/' + reponame }])
- return gacmds
- }
-
-
- var perform_git_add = (dir) => {
- return oplist['is-git-repo'](dir).then((logEntry) => {
-
- if (logEntry.success) {
- return nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
- console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
- return remotename;
- })
- .catch((e) => {
- return perform( serial_perform_git_add, dir.name ).then(()=>{
- return remotename
- })
- })
- }
-
- }).catch((e) => {
- console.log('Failed : ' + dir.name)
- })
- }
-
- if(__args.reponame) { return perform_git_add( { name : __args.reponame} ) }
- else return dirs(perform_git_add)
- }
- , 'remote remove': (args) => {
-
- var __args = {
- remotename : args.remotename|| processedArgs._[2]
- }
- var remotename = __args.remotename
- var serial_perform_git_remove = (repo) => {
- var options = { cwd: instanceroot + '/' + repo }
-
- return [
- ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
- ]
- }
-
- var perform_git_remove = (dir) => {
- oplist['is-git-repo'](dir).then((logEntry) => {
-
- if (logEntry.success) {
- nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
- any(serial_perform_git_remove(dir.name).map(getnodeshellexectask))
- })
- .catch((e) => {
- console.log('skipped : ' + dir.name + `, reason : No remote named ${remotename}`)
- })
- }
-
- }).catch((e) => {
-
- })
- }
-
- dirs(perform_git_remove)
- }
- , 'get-remotes' : (args) => {
-
-
-
-
- var repo = args.repo
-
- var serial_perform = (repo) => {
- return [
- ['git', ['remote', '-vvvv'], { cwd: instanceroot + '/' + repo,
- evaluateResult : function( issuccess, result){
- if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
-
- var lines = result.messages.join('').split('\n')
- var remotes = {}
- lines.forEach(line => {
-
- var match = new RegExp(`(\\S+)\\s(\\S+)/${repo}.git\\s\\((\\S+)\\)`).exec(line)
- if(match) {
- var r = remotes[match[1]] || (remotes[match[1]] = { title : match[1] })
- if(match[3] === 'push') { r.push = match[2] }
- else r.url = match[2]
- }
- })
- return remotes
- }}]
- ]
- }
-
- return perform( serial_perform, repo )
- }
- , 'get-remote' : (upstream) => {
-
-
-
-
- var repo = upstream.repo
-
- var serial_perform = (repo) => {
- return [
- ['git', ['remote', '-vvvv'], { cwd: instanceroot + '/' + repo,
- evaluateResult : function( issuccess, result){
- if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
-
-
- var match = new RegExp(`${upstream.remotename}\\\s(\\S+)/${repo}.git\\s\\(fetch\\)`).exec(result.messages.join(' '))
- if(match) { upstream.url = match[1] }
- else throw Object.assign( new Error('No upstream found for active branch'), result)
- return upstream
- }}]
- ]
- }
-
- return perform( serial_perform, repo )
- }
- , 'get-upstream' : (args) => {
-
- var __args = {
- repo : args?.repo || processedArgs._[1]
- }
-
- var repo = __args.repo
-
- var serial_perform = (repo) => {
- return [
- ['git', ['branch', '-vvvv'], { cwd: instanceroot + '/' + repo,
- evaluateResult : function( issuccess, result){
- if(!issuccess || +result.code !== 0) throw Object.assign( new Error('git branch -vvvv crashed'), result);
-
- var match = /\*\s(\S+)\s\S+\s\[(\S+)\/(\S+).*?\].*?/.exec(result.messages.join(' '))
- if(match) { var upstream = { remotename : match[2], branch : match[1], remotebranch : match[3] } }
- else throw Object.assign( new Error('No upstream found for active branch'), result)
-
- if(args?.remotes) {
- var r = args.remotes[upstream.remotename];
- if(!r) return oplist['get-remote'](upstream)
-
- r.branch = upstream.branch
- r.remotebranch = upstream.remotebranch
- return r
- }
- return oplist['get-remote'](upstream)
- }}]
- ]
- }
-
- return perform( serial_perform, repo )
- }
- , 'init-gitea': (username) => {
-
- username = username || processedArgs._[1]
- if (!username) throw 'User name required'
- var serial_perform_init_gitea = (repo) => {
- var options = { cwd: instanceroot + '/' + repo }
-
- return [
- ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${username}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
- , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
- , ['git', ['remote', 'set-url', 'userfork', `${selectedinstance.reposerver}/${username}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
- ]
- }
-
- var perform_init_gitea = (dir) => {
- oplist['is-git-repo'](dir).then((logEntry) => {
-
- if (logEntry.success) {
- nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
- console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
- })
- .catch((e) => {
- perform( serial_perform_init_gitea, dir.name )
- })
- }
-
- }).catch((e) => {
-
- })
- }
-
- dirs(perform_init_gitea)
- }
- , 'syncmaster': (label) => {
-
-
-
- console.log('Running exlr pull : ' + path.dirname(__dirname))
-
- if (!processedArgs.runas) gitRepos.map((def) => {
- if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
- else performPullOrClone(def, def.branch || 'master')
- })
- var etask = ()=>{
- return any(elevatedRunasRepos.map((def) =>
- {
- if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
- else performPullOrClone(def, def.branch || 'master')
-
- })).then(() => {
- fs.writeFileSync('run.done', 'success')
- }).catch(() => {
- fs.writeFileSync('run.done', 'error')
- })
- }
- etask.statuslog = statuslog
- etask.selectedinstance = selectedinstance
- etask.processedArgs = processedArgs
- etask.runtimestamp = runtimestamp
- etask.ENV = ENV
- return shell_verse.runElevated(etask)
- }
-
- , 'repo-relocate' : function(args){
-
-
- args = ARGUMENTVALIDATOR.validate( args, { sourcerepo : true, targetrepo : true, remotebase : true }, {}, {
- remotebase : processedArgs._[5] || 'http://git.bbh'
- , folder : processedArgs._[3] || ''
- , targetfolder : processedArgs._[4] || ''
- , sourcerepo : processedArgs._[2]
- , targetrepo : processedArgs._[1]
- , repodir : `${processedArgs._[6] || instanceroot}` || `${instanceroot}/relocate`
- , branch : 'master'
- } )
-
- var sourcerepooptions = { cwd: args.repodir
-
- , inherit: true,
- shell: true,
- env: ENV
- , runas: processedArgs.runas
- }
-
- return oplist['repo-split'](args).then(()=>{
- return oplist['repo-merge'](args).then(()=>{
-
-
- var cmdseq = [
-
-
-
-
- ]
-
- return any(cmdseq.map(getshelltask))
- })
- }).catch(e=>{console.error(e)})
- }
-
- , 'repo-split' : function(args) {
-
-
-
-
-
-
-
- var currentargs = ARGUMENTVALIDATOR.validate( args, { repodir : true, remotebase : true }, {}, {
-
- folder : ''
- , targetfolder : ''
- , sourcerepo : undefined
- , targetrepo : undefined
-
- } )
-
-
-
-
-
-
-
-
-
-
- currentargs.sourceloc = args.folder ? `relocatesource-${args.sourcerepo}-${args.folder}` : `relocatesource-${args.sourcerepo}`
- currentargs.targetloc = args.targetfolder ? `relocatetarget-${args.targetrepo}-${args.targetfolder}` : `relocatetarget-${args.targetrepo}`
- currentargs.repodir = args.repodir + '/relocate/' + currentargs.sourceloc + `/${args.owner || defaultowner}`
- currentargs.repo = args.sourcerepo
- currentargs = utils.assign({}, args, currentargs)
- currentargs.remotebase = (args.remotebase || 'http://git.bbh') + `/${getowner(args)}`
-
-
-
- var cmdseq = [
-
- getshelltask([`"${gitbash}"`, ['-c', getCmdString(['mkdir', [' -p', 'relocate/' + currentargs.sourceloc + `/${getowner(args)}`] ]) ]
- , { cwd: args.repodir
-
- , inherit: true, shell: true, benign : true, env: ENV, runas: processedArgs.runas
- }])
-
-
- , GITSHELL.pullORcloneSHELLCMD( currentargs )
-
- , getshelltask([`"${gitbash}"`, ['-c', getCmdString(['mkdir', [' -p', currentargs.sourceloc + '-split' + `/${getowner(args)}` ] ]) ]
- , { cwd: args.repodir + '/relocate'
-
- , inherit: true, shell: true, benign : true, env: ENV, runas: processedArgs.runas
- }])
-
- , GITSHELL.pullORcloneSHELLCMD( utils.assign({}, currentargs, { remotebase : '../../' + currentargs.sourceloc + `/${getowner(args)}`
- , targetloc : '.'
- , repodir : args.repodir + '/relocate/' + currentargs.sourceloc + '-split' + `/${getowner(args)}`
- , localrepo :true
- }))
-
-
- , getshelltask([`"${gitbash}"`, ['-c', getCmdString(['mkdir', [' -p', currentargs.targetloc + `/${getowner(args)}`] ]) ]
- , { cwd: args.repodir + '/relocate'
-
- , inherit: true, shell: true, benign : true, env: ENV, runas: processedArgs.runas
- }])
- , GITSHELL.pullORcloneSHELLCMD( utils.assign({ requiresElevation : true }, currentargs, { repo : args.targetrepo
- , repodir : path.normalize(args.repodir + '/relocate/' + currentargs.targetloc) + `/${getowner(args)}` }) )
- ]
-
-
-
- return any(cmdseq).then(() => {
-
-
-
-
-
-
-
-
-
- currentargs.repodir = args.repodir + '/relocate/' + currentargs.sourceloc + '-split' + `/${getowner(args)}/${currentargs.repo}`
- return oplist['filter-repo'](currentargs)
- }).catch(e=>{
- console.error(e);
- throw 'failed'
- })
- }
-
- , 'repo-merge' : function(args) {
-
-
- var currentargs = ARGUMENTVALIDATOR.validate( args, { repodir : true, remotebase : true }, {}, {
- remotebase : 'http://git.bbh'
- , folder : ''
- , targetfolder : ''
- , sourcerepo : undefined
- , targetrepo : undefined
-
- } )
-
-
-
-
-
-
-
-
-
-
- currentargs.sourceloc = args.folder ? `relocatesource-${args.sourcerepo}-${args.folder}` : `relocatesource-${args.sourcerepo}`
- currentargs.targetloc = args.targetfolder ? `relocatetarget-${args.targetrepo}-${args.targetfolder}` : `relocatetarget-${args.targetrepo}`
- currentargs.repodir = args.repodir + '/' + currentargs.sourceloc
- currentargs.repo = args.sourcerepo
- currentargs = utils.assign({}, args, currentargs)
-
-
- var targetrepooptions = { cwd: args.repodir + '/relocate/' + currentargs.targetloc + `/${args.owner || defaultowner}` + `/${args.targetrepo}`
-
- , inherit: true,
- shell: true,
- env: ENV
- , runas: processedArgs.runas
- }
-
-
- var cmdseq = [
- ['git', ['pull', `../../../` + currentargs.sourceloc + '-split' + `/${args.owner || defaultowner}` + `/${args.sourcerepo}`, `master`, '--allow-unrelated-histories']
- , targetrepooptions ]
-
- ]
- return any(cmdseq.map(getshelltask)).catch(e=>{console.error( JSON.stringify(e) ) })
- }
-
- , 'filter-repo' : function(args){
-
- var args = args || {
- folder : ''
- , targetfolder : ''
- , remotebase : 'http://git.bbh'
- , targetrepo : undefined
- }
-
- args = ARGUMENTVALIDATOR.validate( args, { sourcerepo : true, repodir : true, sourceloc : true }, {}, {
- remotebase : 'http://git.bbh'
- , folder : ''
- , targetfolder : ''
- , sourcerepo : undefined
- , targetrepo : undefined
-
- } )
-
- var sourcerepooptions = { cwd: args.repodir
-
- , inherit: true, shell: true, env: ENV
- , runas: processedArgs.runas
- }
-
- var cmdargs = (args.targetfolder && args.folder) ? ['filter-repo', '--force', '--path', `${args.folder}` , `--path-rename :${args.targetfolder}/` ]
- : args.targetfolder ? ['filter-repo', '--force',`--path-rename :${args.targetfolder}/` ]
- : args.folder ? ['filter-repo', '--force','--path', `${args.folder}` ] : ['filter-repo', '--force']
-
- var cmdseq = [
-
-
- ['git', cmdargs, sourcerepooptions ]
- ]
- console.dir(args.targetfolder)
- return any(cmdseq.map(getshelltask)).catch(e=>{console.error(e); throw 'failed' })
- }
-
- , 'filter-branch' : function(preservefolder, repo){
-
-
-
-
-
-
-
- throw 'filter-repo-history not yet implmented pls refer to manual commands in code.'
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- , 'clone' : (label) =>{
- return elxr.getPullOrCloneTask(selectedinstance)
- }
- , 'pull' : (label) => {
-
-
-
- return elxr.getPullOrCloneTask(selectedinstance)
- }
- , 'isInstalled': () => {
- return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
- console.log(processedArgs._[1] + ' exists.')
- return true;
- });
- }
- , 'c' : ()=>{
-
- }
- , 'i' : () => {
- var tasks = []
-
- tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
- tasks.push(oplist['use'])
- oplist['npmi'].statuslog = statuslog
- tasks.push(shell_verse.getNonElevatedTask(oplist['npmi']))
-
-
-
-
-
-
-
-
-
-
-
-
-
- return any(tasks);
-
- }
- , 'npmi': () => {
- var tasks = [];
-
-
- tasks.push(getShellTask(
- 'npm',[ 'i', '-g', 'babel-cli' ]
- ) )
-
- var npmbuildrepos = ['loopback-jsonapi-model-serializer']
-
- npmbuildrepos.forEach(repo => {
- tasks.push(() => {
- return nodeShellExec('npm', ['i --force'], {
- inherit: true, shell: true
- , cwd: instanceroot + '/' + repo
- , env: ENV
- , title: `npm i for ${repo}`
- }).catch((e) => {
- console.error('Ignoring Benign Error'); console.error(e);
- }).then(() => {
- console.log(`--npm run build for ${repo}--------------------`)
- return nodeShellExec('npm', ['run build'], {
- inherit: true, shell: true
- , cwd: instanceroot + '/' + repo
- , env: ENV
- , title: `npm run build for ${repo}`
- }).then(Tasq.then).catch(Tasq.catch)
- })
- })
- })
-
- return any(tasks).then(() => {
-
- gitRepos.push({ repo : 'chess-server-lib/server'});
- gitRepos = gitRepos.concat(elevatedRunasRepos);
-
-
-
-
-
-
-
-
- var rmtasks = []
- var repotasks = []
- var env = Object.assign({}, ENV)
- delete env.NODE_ENV
- gitRepos.forEach(repodef => {
- rmtasks.push(
-
-
-
- callshelltask(['rm', ['package-lock.json'], {
- inherit: true, shell: true
- , cwd: instanceroot + '/' + repodef.repo
- , env: ENV
- , title: `rm 'package-lock.json' for ${repodef.repo}`
- }])
- .then(()=>{
- console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
- }).catch((e) => { console.error(e) })
-
- )
-
- if (npmbuildrepos.indexOf(repodef.repo) < 0) {
- repotasks.push(
- () => {
- console.log(`--npm i for ${repodef.repo}--------------------`)
- var p = nodeShellExec('npm', ['i', '--force'], {
- inherit: true, shell: true
- , cwd: instanceroot + '/' + repodef.repo
- , env
- , title: `npm i for ${repodef.repo}`
- }).then(Tasq.then).catch(Tasq.catch)
- return p;
- })
- }
- })
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- var bowerRepos = [{ repo : 'elixir-client'}];
- var bowertasks = []
- bowerRepos.forEach(repodef => {
- bowertasks.push(() => {
- console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
-
- var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
-
- inherit: true, shell: true
- , cwd: instanceroot + '/' + repodef.repo
- , env: ENV
- , title: `bower i for ${repodef.repo}`
- }).then(Tasq.then).catch(Tasq.catch)
- return p;
- })
- })
-
- return Promise.all(rmtasks).then(() => any(repotasks)).then(()=>any(bowertasks));
- }).catch(e => {
- console.error(e)
- }).finally(statuslog.finally)
-
- }
- , 'start': (args) => {
-
-
- var label = clioverrides.cmd
- var env = Object.assign({}, ENV);
- var nodecmd = clioverrides.node_env === 'development' ? 'nodemon' : 'node';
-
- function startFn( o ){
- var cmd = [nodecmd, [`--inspect=${o.debugport}`, '--preserve-symlinks', o.script]]
- console.log(`Starting ${o.name}.`);
-
- if(shell_verse.iswin()){
- var __cmd = 'cmd'
- var a1 = '/k'
- }
- else if(shell_verse.islin()) {
- var __cmd = 'sh'
- var a1 = '-c'
- }
-
- if(o.cmd) {
- cmd = o.cmd
- var childPromise = nodeShellExec(...o.cmd, {
-
- shell: true,
- detached: true,
- stdio: 'ignore',
- cwd: instanceroot + o.path
- , env
- })
- }
- else {
- var childPromise = nodeShellExec(__cmd, [a1, getCmdString(cmd) ], {
-
- shell: true,
- detached: true,
- stdio: 'ignore',
- cwd: instanceroot + o.path
- , env
- })
- }
-
- var child = childPromise.process;
- var cpid = child.pid
- childPromise.then(()=>{
- console.log(` *** started ${o.name} PID(${cpid}) ${cmd}`);
- fs.writeFileSync(o.pidstore, '' + cpid)
- })
- .catch(e => console.error(e) )
- }
-
- if(clioverrides.node_env === 'development') {
- env.DEBUG = 'loopback:connector:' + dbForLabel(label)
-
- if(!processedArgs._[2]) processedArgs._[2] = 'all'
- if(processedArgs._[2] === 'server' || processedArgs._[2] === 'all'
- || processedArgs._[2] === 'elixir'
- ) {
- startFn( { debugport : 9228, script : 'elixir/server.js', name : 'Elixir Loopback Server', path : '/' + 'elixir-server'
- , pidstore : '.elixir-server.elixir.server.pid'
- } )
- }
- if(processedArgs._[2] === 'server' || processedArgs._[2] === 'all'
- || processedArgs._[2] === 'express'
- ) {
- startFn( { debugport : 9227, script : 'bin/www', name : 'Express Server', path : '/' + 'chess-server-lib/server'
- , pidstore : '.express.server.pid'
- } )
- }
-
- if(processedArgs._[2] === 'client' || processedArgs._[2] === 'all') {
- startFn( {
- name : 'Elixir Ember Client', path : '/' + 'client'
- , cmd : ['node_modules/ember-cli/bin/ember', ['s']]
- , pidstore : '.client.server.pid'
- } )
- }
- }
-
- }
- , 'stop': (label) => {
- const kill = require('tree-kill');
-
- try{
- var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', { encoding: 'utf8'})
- fs.unlinkSync('.elixir-server.elixir.server.pid')
- console.log(serverPid)
- kill(serverPid)
- }
- catch(e){ console.error(e) }
-
- try{
- serverPid = fs.readFileSync('.express.server.pid', { encoding: 'utf8' })
- fs.unlinkSync('.express.server.pid')
- console.log(serverPid)
- kill(serverPid)
- }
- catch(e){ console.error(e) }
-
- try{
- serverPid = fs.readFileSync('.client.server.pid', { encoding: 'utf8' })
- fs.unlinkSync('.client.server.pid')
- console.log(serverPid)
- kill(serverPid)
- }
- catch(e){ console.error(e) }
- }
- , 'model' : () => {
- var etask = ()=>{
- var tasks = [
- () => {
- var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
- , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
- inherit: true, shell: true
- , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
- , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
- , env: ENV
- }).catch((e) => { console.error(e) })
- return p;
- }
- ];
- return any(tasks).then(() => {
- fs.writeFileSync('run.done', 'success')
- }).catch(() => {
- fs.writeFileSync('run.done', 'error')
- })
- }
- etask.statuslog = statuslog
- etask.selectedinstance = selectedinstance
- etask.processedArgs = processedArgs
- etask.runtimestamp = runtimestamp
- etask.ENV = ENV
- return shell_verse.runElevated(etask)
- }
-
-
- , 'use' : () => {
-
-
-
-
-
-
-
-
-
-
- if (( !processedArgs.force) &&
- runconfig.NODE_ENV && runconfig.NODE_ENV === (selectedinstance.node_env || runconfig.NODE_ENV) &&
- selectedinstance.instanceName && runconfig.use === selectedinstance.instanceName) {
-
- console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
- if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
- if (existsSync('config') && existsSync('data')){
- return
- }
- }
-
- var tasks = [
- () => {
- var promise = new Promise((resolve, reject)=>{
- existslink('config', function(err, data){
- if(data) {
- var p = shell_verse.removeJuncionOrLink('config')
- .then(()=>{resolve(true)})
- .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
- }
- else resolve(false)
- })
- })
- return promise;
- },
- () => {
- var promise = new Promise((resolve, reject)=>{
- existslink('data', function(err, data){
- if(data) {
- var p = shell_verse.removeJuncionOrLink('data')
- .then(()=>{resolve(true)})
- .catch((err) => { console.log('Ignoring benign error : ' + err); return resolve(true); })
- }
- else resolve(false)
- })
- })
- return promise;
- },
- ];
- runconfig.NODE_ENV = ENV.NODE_ENV = ENV.NODE_ENV || runconfig.NODE_ENV || 'development';
- if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
- if (!runconfig.use && selectedinstance.instanceName) runconfig.use = selectedinstance.instanceName;
- if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
- fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
-
- var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
-
- var performPullOrCloneOrCloneForBranch = (def)=>{
- var promise = Promise.resolve(true)
- if (!branch) {
- var dscoverbranchcmd = gitops.getdiscoverbranchcmd({ repo, repodir : instanceroot})
-
- promise = nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{ branch = __branch})
- .catch((e) => { console.error(e); return { error: true, message: repo } })
-
- }
-
- return promise.then(()=>{ return elxr.getPullOrCloneTask(def)() }).catch(e => { console.error( 'performPullOrCloneOrCloneForBranch : Failed ' + e )})
- }
-
- var performCloneAndCheckout = null;
-
- var performCheckout = performCloneAndCheckout = (def) => {if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
-
- return performPullOrCloneOrCloneForBranch(def).then(()=>{
- nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
-
-
- cwd: instanceroot + '/' + def.repo
-
- , runas: processedArgs.runas
- , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
- }).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 } })
- })
- }
-
-
-
-
- var elevatedqueue = [];
- var enqueueOnce = (queue, task, def) => {
- var found = queue.find(element => {
- var keys = Object.keys( element )
- for(var k=0; k < keys.length; k++) {
- if(element[keys[k]] !== def[k]) return false;
- }
- })
- queue.push(function(){ return task(this)}.bind(def));
- }
- var enqueue = (queue, task, def) => {
- queue.push(function(){ return task(def)}.bind(def));
- }
-
- var mergeSources = {
- 'development': null,
- 'test': 'master',
- 'production': 'master'
- }
- var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
-
-
- if(branch === mergesource) performCheckout = (def) => {
- var dscoverbranchcmd = gitops.getdiscoverbranchcmd({ repo, repodir : instanceroot})
- return nodeShellExec.apply(null, dscoverbranchcmd).then(__branch=>{
-
- if(branch === __branch) return performCloneAndCheckout(def)
- return performPullOrCloneOrCloneForBranch(def)
- })
- .catch((e) => { console.error(e); return { error: true, message: repo } })
- }
-
-
- var performPullOrCloneAll = (def) => {
- if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
- return nodeShellExec('git', ['pull', '--all'], {
-
- cwd: instanceroot + '/' + def.repo
- , runas: processedArgs.runas
- , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
- }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
- }
-
- var excludeCheckouts = Object.assign(exludeMergeRepos)
- delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
-
-
- var performMerge = (def) => {
- if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
- return nodeShellExec('git', ['merge', mergesource], {
- inherit: true, shell: true,
- cwd: instanceroot + '/' + def.repo
- , runas: processedArgs.runas
- }).catch((e) => { console.error(e) })
- }
- if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
-
-
-
-
-
-
- return any(tasks).then(() => {
-
- var task = ()=>{
-
-
-
- return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
-
- .then(() => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(gitRepos.map((repo) => performPullOrCloneAll(repo)))
- })
-
- .then( () => {
- if(!mergesource || branch === mergesource ) return Promise.resolve(true)
- return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
- })
-
- .then( () => {
- if(!mergesource || branch === mergesource ) return Promise.resolve(true)
- return any(gitRepos.map((repo) => performPullOrCloneAll(repo)))
- })
-
- .then( () => {
- if(!mergesource || branch === mergesource ) return Promise.resolve(true)
- return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
- })
- .then(
- () => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
- })
- }
- task.statuslog = statuslog
- var netask = shell_verse.getNonElevatedTask(task)
-
- var eltask = ()=> {
- var opts = {
- inherit: true, shell: true
- , cwd : instanceroot
- , env: ENV
- }
- var tasks = [
- () => {
-
- var target = runconfig.use + '-' + 'config' + '-' + ENV.NODE_ENV
- var p = shell_verse.createJuntionOrLink('config', target, opts)
- return p;
- }
- ];
-
- tasks = tasks.concat( [
- () => {
- var dataToLink = runconfig.use + '-data' + '-' + ENV.NODE_ENV
- if(!existsSync(dataToLink)) dataToLink = runconfig.use + '-data';
- var p = shell_verse.createJuntionOrLink('data', dataToLink, opts)
- return p;
- }
- ]
- )
-
-
- return any(tasks).then(()=>{
-
- return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
-
- .then(() => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repo) => performPullOrCloneAll(repo)))
- })
-
- .then( () => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
- })
-
- .then( () => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repodef) => performPullOrCloneAll({repo : repodef.repo, requiresElevation : true })))
- })
-
- .then( () => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
- })
- .then(
- () => {
- if(!mergesource || branch === mergesource) return Promise.resolve(true)
- return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
- })
- .then(() => {
- fs.writeFileSync('run.done', 'success')
- }).catch(() => {
- fs.writeFileSync('run.done', 'error')
- })
- })
- }
- eltask.statuslog = statuslog
- eltask.selectedinstance = selectedinstance
- eltask.processedArgs = processedArgs
- eltask.runtimestamp = runtimestamp
- var eltask = shell_verse.getElevatedTask(eltask)
-
- return eltask().then( ()=>{ return netask() })
-
- }).catch((e) => {
- fs.writeFileSync('run.done', 'error : ' + e)
- })
-
-
-
-
-
-
- }
- , 'g' : () => {
- if (processedArgs.h) {
-
- console.log('elxr g model [modelname] => generate a model named [modelname]');
- console.log('elxr g vmodel [modelname] => generate a model named [modelname]');
- console.log('elxr g vmodel [modelname] --server=true => generate only a server model named [modelname]');
- console.log('elxr g vmodel [modelname] --all=true => default generate server and client model named [modelname]');
- console.log('elxr g => regenerate all known models');
- return
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- if (0) {
-
- nodeShellExec('pwd', { inherit: true });
-
-
-
- nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
- "--profile-directory=Profile 1"
- , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' ]);
-
- }
-
-
-
-
- var g = {
- 'client': () => {
-
-
- console.info('Creating new ember client named : ' + processedArgs._[2]);
- var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
- stdio: ['pipe', process.stdout, process.stderr],
- inherit: true,
- shell: true,
- cwd: path.dirname(__dirname),
- env : ENV
- })
- },
-
- 'modelr': () => {
- var tasks = [
- () => {
- var p = nodeShellExec('"ember"', [
- 'g'
- , 'modelr'
- , processedArgs._[2]], {
- inherit: true, shell: true, env: ENV
- }).then(() => {
- console.log('Blueprint generation complete for : ' + processedArgs._[2])
- return true;
- }).catch((e) => { console.error(e) })
- return p;
- },
- () => {
- var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
- var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
- chromeprefs = JSON.parse(chromeprefs)
- var previous = chromeprefs.download.default_directory;
- var parentDir = path.dirname(__dirname);
- chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
- fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
-
-
- var p = nodeShellExec('"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/' + processedArgs._[2]], {
- inherit: true, shell: true
- , env: ENV
- }).then(() => {
- chromeprefs.download.default_directory = previous;
- fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
- return true;
- }).catch((e) => { console.error(e) })
- return p;
- }
- ,
- () => {
- console.log('Browser process should have closed here....')
- return true;
- }
- ]
- any(tasks)
-
- }
-
- , 'undefined' : ()=>{
- console.warn('Are you sure you want to refresh all the models.');
- throw 'NOT YET IMPLMENTED'
- }
-
- , 'vmodel' : (options)=>{
-
- options = options || {
- generate : processedArgs['all'] ? 'all' : processedArgs['server'] ? 'server' : processedArgs['client'] ? 'client' : null
- }
-
- if(!options.generate) return 'Nothing specified for generation'
-
- var name = processedArgs._[2];
- if(!name) return 'No name specified for generation'
- var templateverse = `${selectedinstance.root}/bbhverse/__universe__/vmodel`
-
-
- var workingtarget = `${selectedinstance.root}/.elxr/run-${runtimestamp}/temp/vmodelworkingdir`
- var destination = `${selectedinstance.root}`
-
-
- return copyrecursive(templateverse, workingtarget).then( r => {
-
- var base = 'chess'
- var patternsubstitutions = [
- { strOrregexp : /(__name__)/g, substitutes : [name]}
- , { strOrregexp : /(__instance__)/g, substitutes : [selectedinstance.instanceName]}
- , { strOrregexp : /(__base__)/g, substitutes : [base]}
- , { strOrregexp : /(__microservice__)/g, substitutes : [selectedinstance.microservice || selectedinstance.instanceName]}
- , { strOrregexp : /(__microclient__)/g, substitutes : [selectedinstance.microclient || `${selectedinstance.instanceName}-client` || 'client']}
- ]
- var options = { source : templateverse, target : workingtarget
- , base , destinationroot : destination, workingtarget
- , processingtype : 'inplace', sourcetype : 'filesystem', patternsubstitutions }
-
- var actions = [
- fswalk( workingtarget, options
- , [ function(t, o){
-
-
- return any([
-
- ()=>{ return fscontentreplace( t, o ) }
- , ()=>{ return fsrename( t, o ) }
- ])
- }] )
-
- , () => dirs((innernode, s, t, o ) => fswalk( path.join(workingtarget, innernode.name), utils.assign({}, o, { innernode }), [ templatelink ] )
- , workingtarget, null, options)
-
-
-
-
- ]
-
- return any(actions);
-
- })
-
- }
- }
-
- g[processedArgs._[1]]();
- }
- , 'launchui' : () => {
- console.log('-----------------------------')
- console.log('Launching Elxir Admin Console')
- console.log('-----------------------------')
-
-
- processedArgs.awaitrun = true;
- return shell_verse.launchui()
-
-
-
-
-
-
-
-
-
-
- }
- , 'create' : () => { return createInstance(selectedinstance) }
-
- , 'httpget' : () => {
-
-
-
-
-
-
-
- return createInstance(selectedinstance)
- }
-
- , 'getuser' : ()=>{ return prerequisites.git.getuser().then(u=>{ console.log(u)}) }
- , 'switch user' : (tousername)=>{ return GIT['switch user'](tousername) }
- }
-
- var gitops = {
-
- getdiscoverbranchcmd : function(repodef){
-
- var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
- var cmd = [gitbash
- , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
- , { cwd: repodef.repodir + '/' + repodef.repo, title: 'discoverbranch for ' + repodef.repo + ' ' + parameters.join(' ') }]
- return cmd
- }
- }
-
- var getPullCmd = (repodef) => {
-
-
- var repo = repodef.repo
- var pullCmd = []
- var branch = repodef.branch
- if(!branch) {
-
-
-
- pullCmd= gitops.getdiscoverbranchcmd(repodef)
-
-
- }
-
-
-
-
-
-
-
- if(branch) {
- var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
- var pullCmd = [ gitbash
- , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
- , { cwd: repodef.repdir + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
- }
- else pullCmd = ['git', ['pull'], {
- inherit: true, shell: true,
- cwd: repodef.repodir + '/' + repo
-
- , runas: processedArgs.runas
- , title: `git pull ${repo}`
- }]
- return pullCmd
- }
-
- var getPullOrCloneTask = (repodef, branch, owner, errHandler, elevatedBatch, regularBatch) => {
-
-
- var repo = repodef.repo;
- repodef.repodir = repodef.repodir || instanceroot
- repodef.branch = repodef.branch || branch
- elevatedBatch = elevatedBatch || [];
- regularBatch = regularBatch || [];
- try{
-
-
-
- var exists = existsSync(instanceroot + '/' + repo)
- }
- catch(e){
- exists = false
- console.log(e)
- }
-
- function initTask(etask){
- etask.info = { repo }
- etask.errHandler = errHandler
- etask.statuslog = statuslog
- etask.processedArgs = processedArgs
- etask.selectedinstance = selectedinstance
- etask.runtimestamp = runtimestamp
- etask.ENV = ENV
- }
-
- function initElevatedBatch(){
- elevatedBatch.info = { repo }
- elevatedBatch.errHandler = errHandler
- elevatedBatch.statuslog = statuslog
- elevatedBatch.processedArgs = processedArgs
- elevatedBatch.selectedinstance = selectedinstance
- elevatedBatch.runtimestamp = runtimestamp
- elevatedBatch.ENV = ENV
- }
-
- if (exists) {
-
- var tasks = [];
- return (()=>{
-
- if(selectedinstance.addremotes) {
- return oplist['get-remotes']({repo}).then(( remotes )=>{
- return oplist['get-upstream']({repo, remotes}).then(( upstream ) => {
- return __addremotesandpull({ upstream, remotes})
- })
- })
- }
- else return __pull();
- })()
-
- function __pull(){
- var branchprint = branch ? ' branch :' + branch : '';
- var task = ()=>{
- console.log('pulling ' + instanceroot + '/' + repo + branchprint )
- return any(tasks).then( ()=>{
- return nodeShellExec.apply(null, getPullCmd(repodef)).then(() => {
- return true;
- })
- })
- }
- initTask(task)
-
- if(repodef.requiresElevation) {
- elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
- if(elevatedBatch.length === 1) { initElevatedBatch(); initTask(elevatedBatch[0]) }
- else initTask(elevatedBatch[elevatedBatch.length-1])
- return elevatedBatch[elevatedBatch.length-1]
- }
- else {
- regularBatch.push(shell_verse.getNonElevatedTask( task ))
- return regularBatch[regularBatch.length-1]
- }
- }
-
- function __addremotesandpull(options){
-
- var tasks = []
-
-
-
- var selectedremotes = Array.from( new Set(selectedinstance.selectedremotes.concat(Object.keys(repodef.remotes || {}))));
- if(selectedremotes.length > 0) var selectedremoteFilter = function(rs) { return selectedremotes.find( rs.server ) }
- else var selectedremoteFilter = function(){ return true }
-
- var repoRemotes = Object.assign( {}, selectedinstance.remotes, options.remotes, options.upstream, repodef.remotes );
-
-
-
-
- Object.keys(repoRemotes).forEach((remotename)=>{
-
- var ai_RemoteAddNeeded = (r)=>{
- if(r.server === reposerver && selectedremoteFilter() && r.accessibility.find( selectedinstance[ 'remote-type' ] )){
- var exists = false;
- if(exists = (options.remotes[r.remotename] || Object.keys(options.remotes).find( lrn => {
- var exists = options.remotes[lrn].server === r.server && !options.remotes[r.remotename]
- if(exists) console.warn('Found duplicate remote with a different name for the same server...')
- return exists
- } )) ) {
- return false
- }
- return true
- }
- return false
- };
- tasks.push(
- ()=>{
- return oplist['remote exists']({
- remotename, repo, benign : true, ignorefailures : true
- , url : repoRemotes[remotename].url + repo
- , branch : checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
- }).then( (r) => {
- if(!r[1]) return false;
- else if(r[0]) return true;
- else if(ai_RemoteAddNeeded( repoRemotes[remotename] )) return oplist['remote add']( { remotename,
- 'set-upstream' : (selectedinstance['upstream'] || `${remotename}/${branch}`)
- , reponame : repo
- , url : repoRemotes[remotename].url , branch : checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
- })
-
- })
- }
- )
- })
-
- utils.any(tasks).then(()=>{
- __pull()
- })
- }
- }
- else {
-
- console.log('cloning ' + repo)
-
-
- var task = ()=>{
- return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${repodef.owner || owner || defaultowner}/` + repo + '.git'],
- {
- inherit: true, shell: true,
- env: ENV
- , cwd : instanceroot
- , runas: processedArgs.runas
- }).then(() => {
-
- var task = ()=>{
- return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
- {
- inherit: true, shell: true,
- env: ENV
- , cwd: instanceroot + '/' + repo
- , runas: processedArgs.runas
- , title: `'git', ${['config', '--replace-all', 'core.symlinks', selectedinstance.username].join(' ')}`
- })
- }
-
- initTask(task)
-
- if(repodef.requiresElevation) {
- elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
- return elevatedBatch[elevatedBatch.length-1]
- }
- else {
- regularBatch.push(shell_verse.getNonElevatedTask( task ))
- return regularBatch[regularBatch.length-1]
- }
- })
- }
-
- initTask(task)
- if(repodef.requiresElevation) {
- elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
- return elevatedBatch[elevatedBatch.length-1]
- }
- else {
- regularBatch.push(shell_verse.getNonElevatedTask( task ))
- return regularBatch[regularBatch.length-1]
- }
- }
- }
-
- var util = require('util');
- var cliname = 'elxr';
- var ver = '1.1';
- var readme = `
- Command syntax examples
-
- elxr
- Displays help. Same as elxr h
-
- elxr i
- Runs interactive propmts to help choose installation options.
-
- NODE_ENV={{yourenvironment}} elxr {{cmd}} {{instancename}} {{otheroptions}}
- General command syntax.
- Eg: NODE_ENV=development elxr pull elixir
-
- Note : Although {{instancename}} is generally a positional parameter supplied immediately after the cmd for most cmd's.
- The specific cmd defines what the value is interpreted as.
- There are several cmds that do not require an {{instancename}} parameter.
- Eg: elxr remote remove origin
- Git operations or passthrough external commands on all repository folders in you working directory.
-
- Main objectives.
- elxr cli is a wrapper around other shell commands and api based operations.
- One of the main objetives it achives is ease of use of repeating an individual cmd multiple times on all targets.
- Eg: A git operation like pull can be repeated consistently on a set of git repositories.
-
- `;
- var help = `
- ${readme}
-
-
- # list of commands... please refer dveloper documentation for ${cliname}
- \r\n\t${
- Object.keys(oplist).join('\r\n\t')
- }
- `;
-
- var elxr = {
- help() {
- return chalk.cyanBright(`
- -------------------------------------------------------------------------------
- *** BBH Elixir ***
- -------------------------------------------------------------------------------
- elxr ${ver}
- A cli tool for chess
- ${help}
- -------------------------------------------------------------------------------
- `)
- }
- , info() {
- return chalk.cyanBright(`
- -------------------------------------------------------------------------------
- *** BBH Elixir ***
- -------------------------------------------------------------------------------
- elxr ${ver}
- A cli tool for chess
- -------------------------------------------------------------------------------
- `)
- }
- , getPullOrCloneTask(args){
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- var __args = {
- remotename : args.remotename|| processedArgs._[2]
- , url : args.url || processedArgs._[3]
- , branch : args.branch || processedArgs._[4]
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- var def = args || {
- repos : selectedinstance.repos,
- elevated : selectedinstance.elevated
- }
-
- var elevatedpulltasks = null;
- if(def.repo) {
-
- if(def.repo.requiresElevation) {
- var t1 = function() {
- return performPullOrClone(def).then(() => {
- return true;
- }).catch((e) => {
- console.error(e)
- }).finally(Traq.finally)
- }
- t1.statuslog = statuslog
- t1.selectedinstance = selectedinstance
- t1.processedArgs = processedArgs
- elevatedpulltasks = shell_verse.getElevatedTask( t1 )
- }
- else {
- var t2 = function(){
- return performPullOrClone(def).then(() => {
- console.log('pulled ' + JSON.stringify(def.repo))
- return true;
- }).catch((e) => {
- console.error(e)
- })
-
- }
- t2.statuslog = statuslog
- var regularpulltasks = shell_verse.getNonElevatedTask( t2 )
- }
- if(elevatedpulltasks) return elevatedpulltasks
- else return regularpulltasks
- }
-
-
- console.dir(def)
- console.log('Running exlr pull : ' + path.dirname(__dirname))
-
- var useGitPull = processedArgs.useGitPull || false;
-
- if(def.elevated || def.repos) {
- if(def.elevated) def.requiresElevation = true;
- else delete def.requiresElevation;
- }
- else {
- if(def.requiresElevation) def.elevated = [def]
- else def.repos = [def]
- }
-
- var regularpulltasks = function(){ return Promise.resolve(true) }
-
- if(def.elevated){
- elevatedpulltasks = function() {
- var eBatch = []
- def.elevated.map((def) => getPullOrCloneTask(def, null, null, null, eBatch))
- if(eBatch.length<1) return Promise.resolve(true);
- eBatch[0].processedArgs = processedArgs
- return shell_verse.runElevatedBatch(eBatch).then(() => {
- return true;
- }).catch((e) => {
- console.error(e)
- })
- }
- elevatedpulltasks.statuslog = statuslog
- }
- if(def.repos) {
- var regularpulltasks = function(){
- var pendingpulls = [];
- def.repos.forEach((def) => {
- pendingpulls.push(
-
-
- function(){
-
-
-
- return performPullOrClone(def).then(()=>{ console.log('pulled ' + JSON.stringify(def.repo)) })
- .catch(e => {
- console.error(util.inspect(e)); throw e })
- }
- )
- })
- return any(pendingpulls).finally(Traq.finally)
- }
- regularpulltasks.statuslog = statuslog
- }
-
-
- return elevatedpulltasks().then(()=>{
- if(isWin() && isElevated) return Promise.resolve(true);
- return regularpulltasks()
- })
- }
- }
-
-
- var unbound_interactionpoints = function(selectedinstance){
- var self = this;
- var _interactionpoints = {
- get runchoice() {
- return {
- label :
- `Choose an option :
- d) Install the default chess instance.
- => elxr i chess node_env=development --default
- n) Create your custom new instance interactively
- => elxr i {{instanceName}} node_env={{environment}}
- i) Choose an instance and environment to install
- => elxr i {{instanceName}} node_env={{environment}}
- c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
- => elxr {{cmd}} {{instanceName}} node_env={{environment}}
- h) Help
- q) Quit
- : `
- , choices : []
- , defaultchoice : 'c'
- , selectedchoice : self.target.runchoice
- , interpret : function(choice){
- var interpret_map = {
- d : function(){
- processedArgs._[0] = 'i'
- self.target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
- self.target.node_env = processedArgs.node_env = (ENV.NODE_ENV && ENV.NODE_ENV.trim()) || processedArgs.node_env || 'development'
- self.target.reposerver = 'https://git.bbh.org.in'
- }
- , n : function() { processedArgs._[0] = 'i' }
- , i : function() {
- processedArgs._[0] = 'i'
-
- }
- , c : async function() {
-
- Object.defineProperty(self, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
- label : `Enter cmd :
- p) pull
- Default <= p
- : `
- , defaultchoice : 'pull'
- }
- ));
-
- var cmd = await self.target['cmd'];
- if (!cmd || cmd === 'p') { self.target['cmd'] = processedArgs._[0] = 'pull' }
- else self.target['cmd'] = processedArgs._[0] = cmd
- return cmd;
- }
- , h : function() { console.log(elxr.help()); process.exit() }
- , q : function() { process.exit() }
- }
-
- if(Promise.resolve(choice) === choice){
- return choice.then( resolvedchoice => {
- return (interpret_map[choice] || interpret_map['c']).call(self.target)
- })
- }
- else return Promise.resolve( (interpret_map[choice] || interpret_map['c']).call(self.target) )
-
-
-
-
-
-
- }
- }
- }
- , get instanceName() {
- return { label : `Enter Instance Name ( <= ${self.target.instanceName || 'chess'} ) : `
- , choices : self.choices['instanceName'], defaultchoice : 'chess'
- , selectedchoice : self.target.instanceName
- }
- }
- , get instanceType() {
- return { label : `Enter Instance Type ( <= ${self.target.instanceType || 'development'} ) : `
- , choices : self.choices['instanceType'], defaultchoice : 'development'
- , selectedchoice : self.target.instanceType || 'development'
- }
- }
- , get reposerver() {
- return { label : `Enter Repo Server Base Url ( <= ${self.target.reposerver || 'https://git.bbh.org.in'} ) : `
- , get choices() {
-
-
-
-
-
-
-
-
- return self.choices['reposerver']
- }
- , set choices(cs) {
- return self.choices['reposerver'].concat([selectedinstance.reposerver]).concat(cs)
- }
-
- , defaultchoice : selectedinstance.reposerver || 'https://git.bbh.org.in'
- , selectedchoice : self.target.reposerver
- }
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- , get username() { return { label : `Enter User Id for ${self.target.reposerver} ( <= ${self.target.username || 'chess'} ) : `
- , choices : self.choices['username'], defaultchoice : self.target.username || 'chess', selectedchoice : self.target.username } }
- , get password() { return { label : `Enter Password for ${self.target.username} @ ${self.target.reposerver} ( <= ${self.target.password || ''} ) : `
- , choices : self.choices['password'], defaultchoice : '***', selectedchoice : self.target.password } }
- , get email() { return { label : `Enter Email for ${self.target.username} @ ${self.target.reposerver} ( <= ${self.target.email || ''} ) : `
- , choices : self.choices['email'], defaultchoice : 'guest@bbh.org.in', selectedchoice : self.target.email } }
-
- }
- return _interactionpoints
- }
-
- var get_interactionpoints_template = function(){
- return {
- instanceName : { label : `Enter Instance Name ( <= ${this.target.instanceName || 'chess'} ) : `
- , choices : this.choices['instanceName'], defaultchoice : 'chess'
- , selectedchoice : this.target.instanceName
- }
- }
- }
-
- var subcommandlabels = {
- switch : (`switch ${processedArgs._[1] || ''}`).trim()
- }
-
-
- function elxrworker(oplist) {
-
- var __runcmd = function (label, oplist) {
- var distinquishedlabel = subcommandlabels[label] || label
- return oplist[distinquishedlabel] ? oplist[distinquishedlabel].cmdFn ? oplist[distinquishedlabel].cmdFn(processedArgs) : oplist[distinquishedlabel](processedArgs) : null;
- }
- return __runcmd(processedArgs.label || clioverrides.cmd || processedArgs._[0] || 'undefined', oplist);
- }
-
- var elxrcmd = (function(){
-
- var __cmdprototype = function(){}
- function subcommandlabelFor(cmd, sub){ return (`${cmd} ${sub || ''}`).trim() }
-
- var __cmd = {
- interpret() {
- var interpreted = {}
-
- processedArgs._[1] ? interpreted.instanceName = processedArgs._[1] : null;
- interpreted.runchoice = processedArgs._[0] || selectedinstance.runchoice;
-
-
-
-
-
-
-
-
-
- interpreted.cmd = this.cmd
- return interpreted
- }
- , getPossiblePrompts(){ return { username : true, password : true, instanceName : true, instanceType : true, reposerver : true } }
- , cmdFn : ()=>{ throw "Elxr Unknown command."}
- , finalized : true
- , toArgs : function( o ){
-
- return o }
- }
-
- function __createO(o){
- if(o.finalized) return o;
- var subs = Object.keys(cmds[o.cmd].subcommands || {})
-
-
- subs.forEach(sub=>elxrcmd.create( cmds[subcommandlabelFor(o.cmd, sub)] ))
-
- var created = utils.assign_core( { keycase: true, arraymergetype : utils.assign_core.DISTINCT_UNION }
- , {}, __cmd, cmds[o.cmd], o)
- cmds[o.cmd] = created;
- created.cmdFn = oplist[o.cmd] || o.cmdFn || created.cmdFn
- oplist[o.cmd] = created.cmdFn;
- noprerequisites[o.cmd] = created.noprerequisites
- return created.cmdFn;
- }
-
- function create(o){ return __createO(o) }
- __cmdprototype.create = create;
-
- return __cmdprototype;
- })()
-
- function resetgitconfig(){
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- var options = {
- inherit: true, shell: true, env: ENV
- , cwd: instanceroot
- , runas: processedArgs.runas
- }
-
- var task = ['git', ['config'], options]
-
- var tasklist = [
-
-
-
-
- ['--global', 'credential.helper', "'store --file ~/.git_repo_credentials'"]
- , ['--global', '--replace-all', 'user.name', 'pb']
- , ['--global', '--replace-all', 'user.email', 'pradeep@bbh.org.in']
-
-
-
- ]
- var onEachError = e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n')
- var shellT = (args) => { return getgitbashtask(args, onEachError)
-
- }
- execserial(tasklist, task, shellT, onEachError )
- }
-
- function reinit(){
- sysAddPathVar('%AppData%\\npm')
- resetgitconfig()
- }
-
- function init(){
- sysAddPathVar('%AppData%\\npm')
- resetgitconfig()
- }
-
-
- var getCmdString = function(args){ return `"${args[0]} ${args[1].join(' ')}"` }
- var getgitbashtask = (args, onEachError) => { return () => {
- return nodeShellExec( `"${gitbash}"`, ['-c', getCmdString(args)], args[2]).catch( onEachError || function(e){ console.error(e) }) }
- }
-
- var getshelltask = (args) => {
- return args[0] === 'rm' ? getgitbashtask(args) : () => {
- return nodeShellExec.apply(null, args).catch(function(e){
- e.benign = args[2].benign;
- if(!e.benign) { console.error( JSON.stringify(e) ); }
- throw e
- })
- }
- }
-
-
-
- const GITSHELL = (function(){
- const GITSHELL = function(){}
- GITSHELL.bash = shell_verse.getbash()
-
- GITSHELL.getdiscoverbranchcmd = function(repodef){
-
- var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
- var cmd = [GITSHELL.bash
- , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
- , { cwd: repodef.repodir + '/' + repodef.repo, title: 'discoverbranch for ' + repodef.repo + ' ' + parameters.join(' ') }]
- return cmd
- }
-
- GITSHELL.getPullCmd = (repodef) => {
-
-
- var repo = repodef.repo
- var pullCmd = []
- var branch = repodef.branch
- if(!branch) {
-
-
-
- pullCmd = GITSHELL.getdiscoverbranchcmd(repodef)
-
-
- }
-
-
-
-
-
-
-
- if(branch) {
- var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
- var pullCmd = [ gitbash
- , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
- , { cwd: repodef.repodir + '/' + repo, title : 'pull all remotes for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
- }
- else pullCmd = ['git', ['pull'], {
- inherit: true, shell: true,
- cwd: repodef.repodir + '/' + repo
-
- , runas: processedArgs.runas
- , title: `git pull ${repo}`
- }]
- return pullCmd
- }
-
- GITSHELL.pullORcloneSHELLCMD = ( repodef ) => {
-
-
- ARGUMENTVALIDATOR.validate( repodef, { repo : true, repodir : true, branch : true })
-
- var repo = repodef.repo;
- repodef.repodir = repodef.repodir || instanceroot
- var branch = repodef.branch
- var elevatedBatch = repodef.elevatedBatch || [];
- var regularBatch = repodef.regularBatch || [];
-
- var errorHandler = (e) => {
- console.error(e)
- throw e;
- }
-
- function initTask(etask){
- etask.info = { repo }
- etask.errHandler = elevatedBatch.errHandler || errorHandler
- etask.statuslog = statuslog
- etask.processedArgs = processedArgs
- etask.selectedinstance = selectedinstance
- etask.runtimestamp = runtimestamp
- etask.ENV = ENV
- }
-
- function initElevatedBatch(){
- elevatedBatch.info = { repo }
- elevatedBatch.errHandler = elevatedBatch.errHandler || errorHandler
- elevatedBatch.statuslog = statuslog
- elevatedBatch.processedArgs = processedArgs
- elevatedBatch.selectedinstance = selectedinstance
- elevatedBatch.runtimestamp = runtimestamp
- elevatedBatch.ENV = ENV
- }
-
- try{
-
-
-
- var exists = existsSync(repodef.repodir + '/' + repo)
- }
- catch(e){
- exists = false
- console.log(e)
- }
-
- if (exists) {
-
- var tasks = [];
- return __pull();
-
- function __pull(){
- var branchprint = branch ? ' branch :' + branch : '';
- var cmd = GITSHELL.getPullCmd(repodef)
-
-
-
-
-
-
-
- var task = ()=>{
- return any(tasks).then( ()=>{
- console.log('pulling ' + repodef.repodir + '/' + repo + branchprint )
- return nodeShellExec.apply(null, cmd).then(() => {
- return true;
- })
- })
- }
- initTask(task)
-
- if(repodef.requiresElevation) {
- task.selectedinstance = selectedinstance
- task.args = [cmd[0], [cmd[1].join(' ')], cmd[2]]
-
- elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
- if(elevatedBatch.length === 1) { initElevatedBatch(); initTask(elevatedBatch[0]) }
- else initTask(elevatedBatch[elevatedBatch.length-1])
- return elevatedBatch[elevatedBatch.length-1]
- }
- else {
- regularBatch.push(shell_verse.getNonElevatedTask( task ))
- return regularBatch[regularBatch.length-1]
- }
- }
- }
- else {
-
-
-
-
-
-
- var cmd = ['git', ['clone', '-c', 'core.symlinks=true', repodef.remotebase + `/` + repo + ( repodef.localrepo ? '' : '.git') ],
- {
- inherit: true, shell: true,
- env: ENV
- , cwd : repodef.repodir
- , runas: repodef.requiresElevation || processedArgs.runas
- }]
- var task = ()=>{
- console.log('cloning ' + repo)
-
- return nodeShellExec.apply( null, cmd).then(() => {
- var task = ()=>{
- return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
- {
- inherit: true, shell: true,
- env: ENV
- , cwd: repodef.repodir + '/' + repo
- , runas: repodef.requiresElevation || processedArgs.runas
- , title: `'git', ${['config', '--replace-all', 'core.symlinks', selectedinstance.username].join(' ')}`
- })
- }
-
- initTask(task)
-
- if(repodef.requiresElevation) {
- elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
- return elevatedBatch[elevatedBatch.length-1]
- }
- else {
- regularBatch.push(shell_verse.getNonElevatedTask( task ))
- return regularBatch[regularBatch.length-1]
- }
- })
- }
-
- initTask(task)
- if(repodef.requiresElevation) {
- console.dir(cmd)
- task.selectedinstance = selectedinstance
- task.args = [cmd[0], [cmd[1].join(' ')], cmd[2]]
- console.dir(task.args)
- elevatedBatch.push(shell_verse.getElevatedTaskInBatch( task ));
- return elevatedBatch[elevatedBatch.length-1]
- }
- else {
- regularBatch.push(shell_verse.getNonElevatedTask( task ))
- return regularBatch[regularBatch.length-1]
- }
- }
- }
- return GITSHELL
- })()
-
- var cmdFns = {
- resetgitconfig, reinit, init, g : oplist['g'], 'get-upstream' : oplist['get-upstream']
- }
-
- Object.entries(cmds).forEach( ca => {
- ca[1].cmd = ca[0]
- ca[1].cmdFn = ca[1].cmdFn || cmdFns[ca[0]]
- ca[1].noprerequisites = noprerequisites[ca[1].cmd]
- elxrcmd.create( ca[1] )
- })
-
- shell_verse.cmds = cmds;
- shell_verse.generateDependencies()
- console.dir(Object.keys(shell_verse.cmds))
-
- Tasq.addlistener(statuslog.statuslog)
- if(clioverrides.noprerequisites) return elxrworker(cmds)
-
- var pending = (function() {
-
-
- acquirelocalinstances( { root : ENV.wd } )
-
- function createLocalChessInstance( cfg ){
-
- reconfirm = getReconfirmAll()
- var inst = {};
- var __new = Object.assign({}, __default, cfg)
- inst[cfg.node_env] = __new; return inst;
- }
-
- if(chessinstances.error) {
- delete chessinstances.error
-
- try { var installchoices = require(path.normalize(ENV.wd + '/installchoices.js'))
- var instanceName = installchoices.instanceName;
- var reposerver = installchoices.reposerver
- var node_env = clioverrides.node_env || installchoices.node_env
- var __instance = (chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
- instanceName, node_env, root, reposerver } ))[node_env];
- chessinstances['current_run'] = { instanceName, node_env, reposerver, root }
-
-
-
-
-
-
- __instance.username = installchoices.username = installchoices.gitUser
- __instance.email = installchoices.email = installchoices.gitEmail
- }
- catch(e){
- console.warn(e)
- console.warn( 'Install choices not found. WIll prompt for choices' )
- throw 'PROMPT FOR INSTLL CHOICES TO BE IMPLEMENTED'
-
-
- }
- }
-
-
-
- var instanceName = clioverrides.instanceName || chessinstances.current_run.instanceName
- var instance = {}
- function oninstanceName(instanceName) {
-
- var instance_ = chessinstances[instanceName]
- if(instance_) {
- instance = instance_[clioverrides.node_env || chessinstances.current_run.node_env] || utils.assign(chessinstances['current_run'], clioverrides, { instanceName })
- }
- else instance = utils.assign(chessinstances['current_run'], clioverrides, { instanceName })
-
- return instance
- }
- if(!instanceName) {
- var interactionpoints = (function() { return { instanceName : get_interactionpoints_template.bind({target : {}, choices : {}})()['instanceName'] } })()
- var eachPrompt = getBoundEachPrompt(instance, utils.assign({}, interactionpoints), interactionpoints, {})
- var pendingtasks = any( Object.keys(interactionpoints).reduce(eachPrompt, []) ).then(()=>{
- return oninstanceName(instance.instanceName)
- })
- }
- else {
- var pendingtasks = Promise.resolve(oninstanceName(instanceName))
- }
-
- return pendingtasks.then((instance)=>{
-
-
-
-
-
-
- var __repo_manifest_elxr = loadmanifest( instance.root + '/elxr'
- , { username : instance.username , instanceName : instance.instanceName
- , node_env : clioverrides.node_env, reposerver : instance.reposerver }
- )
-
- if(__repo_manifest_elxr.error) console.log(__repo_manifest_elxr.e.message)
-
- var instance_specific_config_manifest = loadmanifest( instance.root + `/${instance.instanceName}-config-${clioverrides.node_env}`
- , { username : instance.username , instanceName : instance.instanceName
- , node_env : clioverrides.node_env, reposerver : instance.reposerver }
- )
- if(instance_specific_config_manifest.error) console.log(instance_specific_config_manifest.e.message)
- delete __repo_manifest_elxr.error
- delete __repo_manifest_elxr.e
-
- delete instance_specific_config_manifest.error
- delete instance_specific_config_manifest.e
-
-
-
-
-
-
-
-
-
-
-
- var __pvt = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
- , __default, __repo_manifest_elxr, instance
- , { root : ENV.wd, node_env : ENV.NODE_ENV
- , get instanceName() {
-
- return instance.instanceName
- }
- }
- , instance_specific_config_manifest
- , clioverrides
- )
-
-
- Object.keys(instance_specific_config_manifest).forEach( key => {
- __pvt[key] = instance_specific_config_manifest[key]
- })
-
- var __pub = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }, {}, __pvt
-
-
- , { get root(){ return __pvt.root }
- , get node_env(){ return __pvt.node_env }
- , get instanceName() { return __pvt.instanceName }
- , get reposindexed(){
-
- var indexed = {}
- this.repos.forEach(r => { indexed[r.repo] = r })
- this.elevated.forEach(r => { indexed[r.repo] = r })
- Object.defineProperty(this, 'reposindexed', { value: indexed, writable: false });
- return indexed;
- }
- , set root(val){
- throw 'root changes not yet supported'
-
- if(__pvt.root === val){
-
- return __pvt.root = val
- }
- else __pvt.root
- }
- }
- )
-
- chessinstances[__pub.instanceName] = chessinstances[__pub.instanceName] || {}
- chessinstances[__pub.instanceName][__pub.instanceType] = __pub
-
-
- if(__pub?.repos && !__pub?.repos[0]?.repo) {
- console.warn('repo manifest has obsolete format. Attempting upgrade.')
- __pub.repos = __pub.repos.map(function(repo){ return { repo } })
- }
- if(__pub?.elevated && !__pub?.elevated[0]?.repo) {
- console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
- __pub.elevated = __pub.elevated.map(function(repo){ return { repo } })
- }
-
-
-
-
-
-
-
-
-
- if(!__pub.reposerver) reconfirm['reposerver'] = true
- __pub.reposerver = __pub.reposerver || __pub.reposervers[0]
-
- cacheWriteInstanceConfig(chessinstances, __pub.root, __pub )
-
- Object.defineProperty(__g, 'selectedinstance', {
- get(){ return __pub}
- , set( inst ){
- utils.assign(__pub, inst); return __pub
- }
- })
- return __pub;
- })
-
- })()
-
- return pending.then(( selectedinstance)=>{
-
- shell_verse.init({ statuslog, selectedinstance, processedArgs, runtimestamp, ENV })
- Object.keys(oplist).forEach( oper => {
- if(cmds[oper]) return
-
- cmds[oper] = {}
-
-
-
-
- })
-
- var cmdFns = {
- resetgitconfig, reinit, init, g : oplist['g'], 'get-upstream' : oplist['get-upstream']
- }
-
- Object.entries(cmds).forEach( ca => {
- ca[1].cmd = ca[0]
- ca[1].cmdFn = ca[1].cmdFn || cmdFns[ca[0]]
- ca[1].noprerequisites = noprerequisites[ca[1].cmd]
- elxrcmd.create( ca[1] )
- })
-
- shell_verse.cmds = cmds;
-
-
- runlogjson = `${selectedinstance.root}/.elxr/run-${runtimestamp}/run.log`
- ensureDirectoryExistence(runlogjson)
- fs.writeFileSync(runlogjson, JSON.stringify( { message : `Started ${runtimestamp}`, success:true}))
- Tasq.addlistener((e)=>{ fs.writeFileSync(runlogjson, ', ' + JSON.stringify( e ), { 'flag': 'a+' }) })
-
-
- var chalk = require('chalk')
- const homedir = require('os').homedir();
-
- function sysAddPathVar(addpath){
-
-
-
-
-
- var etask = ()=>{
- return nodeShellExec('Powershell.exe', [
- `$path = [Environment]::GetEnvironmentVariable('PATH', 'Machine')
- $newpath = $path + ';${addpath}'
- [Environment]::SetEnvironmentVariable("PATH", $newpath, 'Machine')`
- ]).then(() => {
- fs.writeFileSync('run.done', 'success')
- }).catch(() => {
- fs.writeFileSync('run.done', 'error')
- })
- }
- etask.statuslog = statuslog
- etask.selectedinstance = selectedinstance
- etask.processedArgs = processedArgs
- etask.runtimestamp = runtimestamp
- etask.ENV = ENV
- return shell_verse.runElevated(etask)
-
-
-
-
-
-
-
-
-
- }
-
-
- var getCredentials = function(){
-
-
-
- var creds = fs.readFileSync(path.normalize(`${homedir}/.elxrcredentials`), { encoding: 'utf8' });
- var creds = creds.split('\n').map( c => c.trim() && new URL(c));
- console.log(creds);
- creds.forEach(cred => {console.log( cred.hostname ); console.log( cred.username )} );
-
-
-
-
-
-
- getCredentials = ()=>{ return creds }
- return getCredentials();
- }
-
-
-
-
-
-
-
-
-
- const { readdir } = require("fs").promises
-
-
- const dirs = async (perform, src, target, options) => {
- var rs = []
- for (const dir of await readdir(src || selectedinstance.root, { withFileTypes: true })) {
- if (dir.isDirectory()) rs.push( perform(dir, src, target, options) )
- }
- return any(rs)
- }
-
- var fsMove = async function(from, to, options) {
-
- if(!options?.innernode) {
- var exists = fs.existsSync(from);
- var stats = exists && fs.statSync(from);
- var isDirectory = exists && stats.isDirectory();
- }
- else {
- var isDirectory = options.innernode.isDirectory()
- }
-
- if(!isDirectory) return fs.renameSync(from, to)
-
- fs.mkdirSync(to, { recursive : true })
-
- var rs = [];
- for (const innernode of await readdir(from, { withFileTypes: true })) {
- rs.push( fsMove( path.join(from, innernode.name), path.join(to, innernode.name), { innernode } ) )
- }
-
- return any(rs)
- };
-
-
-
-
- var copyrecursive = async function(src, target, options) {
-
- if(!options?.innernode) {
- var exists = fs.existsSync(src);
- var stats = exists && fs.statSync(src);
- var isDirectory = exists && stats.isDirectory();
- }
- else {
- var isDirectory = options.innernode.isDirectory()
- }
-
- if(!isDirectory) return fs.copyFileSync(src, target)
-
- fs.mkdirSync(target, { recursive : true })
-
- var rs = [];
- for (const innernode of await readdir(src, { withFileTypes: true })) {
- rs.push( copyrecursive( path.join(src, innernode.name), path.join(target, innernode.name), { innernode } )
-
-
-
- )
- }
-
- return any(rs)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- };
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- const fswalk = async (pathToWalk, options, actions) => {
-
-
- if(!options.innernode) {
- var exists = fs.existsSync(pathToWalk);
- var stats = exists && fs.statSync(pathToWalk);
- var isDirectory = exists && stats.isDirectory();
- }
- else {
- var isDirectory = options.innernode.isDirectory()
- }
-
- if(!isDirectory) return any(actions.map( a => ()=>a( pathToWalk, utils.assign({}, options
- , { pathToWalk, innernode : options.innernode || { isDirectory : function(){ return true } } }) ) ))
-
- var rs = [];
- for (const innernode of await readdir(pathToWalk, { withFileTypes: true })) {
- rs.push( fswalk( path.join(pathToWalk, innernode.name), utils.assign({}, options, {pathToWalk, innernode }), actions )
-
-
-
- )
- }
-
- Array.prototype.push.apply(rs, actions.map( a => ()=>a( pathToWalk, utils.assign({}, options
- , { pathToWalk, innernode : options.innernode || { isDirectory : function(){ return true } } } ) ) ))
-
- return any(rs)
- }
-
- var fsrecurse = function(target, options, actions, root) {
- var exists = fs.existsSync(target);
- var stats = exists && fs.statSync(target);
- var isDirectory = exists && stats.isDirectory();
- if (isDirectory) {
- var tasks = []
- tasks.push( dirs( function(childItemName) {
- return fsrecurse(path.join(target, childItemName.name)
- , options, actions, root);
- }, target ))
- return any(tasks)
- } else {
- var prevActionResult = null;
- return any( actions.map( (action) => prevActionResult = action.apply(null, target, options) ))
- }
- };
-
-
- var fslink = function(to, options){ fs.symlinkSync( to, options.from ) }
-
- var fsrename = function(target, options){
-
-
- var targetname = options.innernode?.name || path.parse(target).base;
- var replaced = targetname;
-
- options.patternsubstitutions.forEach( ps => { replaced = regexreplaceall( replaced, ps ) })
- if(replaced && replaced !== targetname) {
- var tr = target.replace( targetname, replaced )
- fs.renameSync(target, tr)
- return tr;
- }
- else return replaced
- }
-
- var fscontentreplace = function( target, options ){
-
- if(options.processingtype === 'inplace' && options.sourcetype === 'filesystem' && !options.innernode.isDirectory() ) {
- var content = fs.readFileSync(target, { encoding: 'utf8' })
- options.patternsubstitutions.forEach( ps => { content = regexreplaceall( content, ps ) })
- fs.writeFileSync(target, content)
- }
- }
-
- var templatelink = function(target, options){
- var targetSubPath = target.replace(options.workingtarget + '/', '' );
- var targetSubPathsplit = targetSubPath.split("/")
- var targetPathBaseDir = `${targetSubPathsplit[0]}/${targetSubPathsplit[1]}`
-
- var linkToSubPathReplacement = `${options.base}-server-lib/common`
-
-
- var rgxp = new RegExp(`(__link__${options.base}-server-lib)`, "g")
- var linkToSubPath = targetSubPath
- var b = target.match(rgxp)
- var linkFromName = regexreplaceall( target, { strOrregexp : rgxp, substitutes : [ '' ] } )
- linkFromName = linkFromName.replace(options.workingtarget, options.destinationroot)
-
- if( b ) {
-
- linkToSubPath = regexreplaceall( linkToSubPath, { strOrregexp : rgxp, substitutes : [ '' ] } )
- }
-
- options.patternsubstitutions.forEach( ps => { linkToSubPath = regexreplaceall( linkToSubPath, ps ) })
- var linkToName = `${options.destinationroot}/${linkToSubPath}`
-
- if(b){
- linkToSubPath = linkToSubPath.replace( targetPathBaseDir, linkToSubPathReplacement)
-
-
- fs.unlinkSync( target );
- fslink( `${options.destinationroot}/${linkToSubPath}`, { from : linkFromName } )
- }
- else {
- fsMove( `${options.workingtarget}/${linkToSubPath}`, linkToName )
-
- }
- }
-
-
- var processpatterns = function(target, options){
-
-
-
-
-
- if(options.processingtype === 'inplace' && options.sourcetype === 'filesystem' ) {
-
- options.patternsubstitutions.forEach( ps => {
-
-
- return options.tasks.map( t => { return t( target, ps ) } )
-
-
-
-
-
-
- })
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- }
-
- function copyFileSync( source, target , options) {
-
- var targetFile = target;
-
-
- if ( fs.existsSync( target ) ) {
- if ( fs.lstatSync( target ).isDirectory() ) {
- targetFile = path.join( target, path.basename( source ) );
- }
- }
-
- fs.writeFileSync(targetFile, fs.readFileSync(source));
- }
-
- function copyFolderRecursiveSync( source, target, options ) {
- var files = [];
-
-
- var targetfolder = path.join( target, path.basename( source ) );
- if ( !fs.existsSync( targetfolder ) ) {
- fs.mkdirSync( targetfolder );
- }
-
-
- if ( fs.lstatSync( source ).isDirectory() ) {
- files = fs.readdirSync( source );
- files.forEach( function ( file ) {
- var curSource = path.join( source, file );
- if ( fs.lstatSync( curSource ).isDirectory() ) {
- copyFolderRecursiveSync( curSource, targetfolder );
- } else {
- copyFileSync( curSource, targetfolder );
- }
- } );
- }
- }
-
-
- var getShellTask = (command, args, options) => {
- options = options || {}
- var callshell = command === 'rm' ? getgitbashtask : getshelltask;
- return () => {
- var p = callshell( [command, args, Object.assign({
- inherit: true, shell: true, env: ENV, title: `${command} ${args}`
- }, options)
- ])()
- if (options.ignorefailures) {
- return p.catch(e => {
-
- })
- }
- else return p;
- }
- }
-
- var callshelltask = (args) => {
-
- if( Object.prototype.toString.call(args) === '[object Function]' ) {
- return args;
- }
- return getshelltask(args)()
- }
-
- var getnodeshellexectask = (args) => { return () => { return nodeShellExec.apply(null, args) }}
- var perform = function( serailtasks, taskvector ){ return any( serailtasks(taskvector).map(getnodeshellexectask)) }
-
- var getTaskCheckExists = shell_verse.getTaskCheckExists
-
-
-
-
-
-
-
-
-
- var currentGitAuthUser;
-
- var elevatedRunasRepos = null
- var gitRepos = null
-
-
-
-
- var dbForLabel = function (label) {
- var dbsForLabel = {
- devmysql: 'mysql'
- , development: 'mssql'
- , production: 'mssql'
- }
- return dbsForLabel[label] || 'mysql'
- }
-
-
- var checkoutMap = { 'development': 'master' }
-
-
-
-
-
- var exludeMergeRepos = [];
- var useGitPull = processedArgs.useGitPull || false;
- var configPromise = null
-
- var reconfirmcmds = { create : true }
-
- var independentcmd = function(){
- return false;
- }
-
- function preworkerconfig(){
-
- gitRepos = selectedinstance.repos
-
-
-
- elevatedRunasRepos = selectedinstance.elevated
-
- exludeMergeRepos = selectedinstance.exludeMergeRepos
-
-
-
-
- var mysql = '../xampp/mysql/bin/mysql'
- var mysqldump = '../xampp/mysql/bin/mysqldump'
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- var os = require("os");
- var hostname = os.hostname();
- var clustername = null;
- var configs = (function(){
-
-
-
-
- return {
- ownerClusterNodeConfig(selected) {
-
-
- var clusternodename = hostname || `CHESS0001${selected.username}`;
- clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
- return __acquireConfig(selected, { remote : 'userfork' }
- , selected.instanceName + '-config-' + selected.node_env + `-${clusternodename}`
- , function(e){ console.info('Customized node level config not found. This is not an Error. Will attempt with owner level config.');
- e.benign = true
- return e; }
- )
- }
- , ownerInstnace(selected) { return __acquireConfig(selected, { remote : 'userfork' }
- , selected.instanceName + '-config-' + selected.node_env
- , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
- e.benign = true
- return e }
- )
- }
-
- , commonInstance(selected) { return __acquireConfig(selected, { owner : defaultowner }
- , undefined
- , function(e){
-
- statuslog.statuslog(e, e)
- var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
- utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
- , selectedinstance, require(manifestpath)( {utils}, null, { username : selectedinstance.username, instanceName : selectedinstance.instanceName
- , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' } ))
- console.dir(selectedinstance.repos)
-
-
- if(selectedinstance?.repos && !selectedinstance.repos[0].repo) {
- console.warn('repo manifest has obsolete format. Attempting upgrade.')
- selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
- }
- if(selectedinstance?.elevated && !selectedinstance.elevated[0]?.repo) {
- console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
- selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
- }
- chessinstances[selected.instanceName][selected.node_env] = selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
- , selected, selectedinstance)
- chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
- selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0]
- cacheWriteInstanceConfig(chessinstances, selectedinstance.root, selectedinstance)
-
- throw e
- }
- ) }
-
- }
- })()
-
- var eNotImplemented = function(){
- console.error('Not yet implemented')
- process.exit()
- }
-
-
- var acquireConfig = function(slections){
- var configPriority = [ 'ownerClusterNodeConfig', 'ownerInstnace', 'commonInstance' ]
- return any(configPriority.map(cfg => { return function() { return configs[cfg](slections) } } ), true, true).then(()=>{
- return acquireData(slections)
- })
- }
-
- var instanceData = (function(){
- return {
- ownerClusterNodeData(selected) {
- var clusternodename = hostname || `CHESS0001${selected.username}`;
- clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
- return __acquireData(selected, { remote : 'userfork' }
- , selected.instanceName + '-data-' + selected.node_env + `-${clusternodename}`
- , function(e){ console.info('Customized node level data not found. This is not an Error. Will attempt with owner level config.');
- e.benign = true
- return e; }
- )
- }
- , ownerInstnace(selected) { return __acquireData(selected, { remote : 'userfork' }
- , selected.instanceName + '-data-' + selected.node_env
- , function(e){ console.info('Customized user level data not found. This is not an Error. Will attempt global common instance config.');
- e.benign = true
- return e }
- )
- }
-
- , commonInstance(selected) { return __acquireData(selected, { owner : defaultowner }
-
-
- ) }
- , genericChessInstance(selected) { return __acquireData(selected, { owner : defaultowner }) }
- }
- })()
-
- var acquireData = function(slections){
- var configPriority = [ 'ownerClusterNodeData', 'ownerInstnace', 'commonInstance' ]
- return any(configPriority.map(cfg => { return function() { return instanceData[cfg](slections) } } ), true, true)
- }
-
- var createTasq = (args, shellT, onEachError) => {
- var tasq = shellT ? shellT(args) : (() => { return nodeShellExec.apply(null, args).catch( onEachError || function(e){ console.error(e) } ) })
- tasq.toString = function(){ return JSON.stringify(args)}
- return tasq;
- }
-
- var execserial = function(tasklist, task, shellT){
- var exec = (taskArgs)=>{
- var thistask = task.concat();
- thistask[1] = thistask[1].concat()
- thistask[1].push.apply(thistask[1], taskArgs)
- return createTasq(thistask, shellT)
- }
-
- return any(tasklist.map(exec))
- }
-
- var execonce = function(taskArgs, task){ return any([task[1].push.apply(task[1], taskArgs)].map(createTasq)) }
-
-
- var __acquireConfig = function (selected, options, configrepo, errHandler) {
-
- configrepo = configrepo || selected.instanceName + '-config-' + selected.node_env;
- var owner = options.owner || selected.username || options.defaultowner
-
- var errorHandler = (e) => {
- 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`))){
-
- 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 => {
-
- if(propValue === 'y') {
- reconfirm = getReconfirmAll()
- return startElxr()
- }
- else if(propValue === 'r'){
- return acquireConfig(selected)
- }
- else process.exit()
- })
- }
-
- if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${owner}/${configrepo}.git/' not found`))){
- var choices = {
- t : `install a new temporary local instance with this name ( will not persist ).
- Use your own username for additional options. You can request for a username at chess@bbh.org.in )`
- , e : 'exit' }
-
- if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
- choices = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
- , {
- i : 'create a new instance with this name => will fork the default config under your username'
- , f : 'fork a new instance with this name for yourself for this node from another instance'
- , o : 'fork a new instance with this name for your organization from another instance'
- , c : 'create a custom config for yourself for this node'
- , p : 'create a custom config for yourself '
- }, choices)
- }
-
- return cli.prompt( choices
- , 'Config for instance not found. Would you like to ', 'e' ).then(propValue => {
-
- if(propValue === 't') {
- selectedinstance.local = true; return createInstance(selectedinstance)
- }
- if(propValue === 'i') return eNotImplemented()
- if(propValue === 'f') return eNotImplemented()
- if(propValue === 'o') return eNotImplemented()
- if(propValue === 'c') return eNotImplemented()
- if(propValue === 'p') return eNotImplemented()
-
- else process.exit()
- })
- }
-
- console.warn(e)
- throw e;
- }
-
- var successHandler = () => {
-
- var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
- utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
- , selectedinstance, require(manifestpath)( {utils}, null, { username : selectedinstance.username, instanceName : selectedinstance.instanceName
- , node_env : selectedinstance.node_env, reposerver : selectedinstance.reposerver }))
- console.dir(selectedinstance.repos)
-
-
- if(!selectedinstance.repos[0].repo) {
- console.warn('repo manifest has obsolete format. Attempting upgrade.')
- selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
- }
- if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
- console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
- selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
- }
- chessinstances[selected.instanceName][selected.node_env] = selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
- , selected, selectedinstance)
- chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
- selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0]
- cacheWriteInstanceConfig(chessinstances, selectedinstance.root)
- ENV.NODE_ENV = selectedinstance.node_env;
- }
-
- return performPullOrClone( selected.reposindexed[configrepo] || { repo : configrepo }
- , null, owner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
- .catch( (e)=>{
-
- if(Promise.resolve(e) === e) return e;
-
- e.benign = true;
- throw e;
-
- })
- }
-
- var __acquireData = function (selected, options, datarepo, errHandler) {
-
- datarepo = datarepo || selected.instanceName + '-data';
- var owner = options.owner || selected.username || options.defaultowner
-
- var errorHandler = (e) => {
- 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`))){
-
- 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 => {
-
- if(propValue === 'y') {
- reconfirm = getReconfirmAll()
- return startElxr()
- }
- else if(propValue === 'r'){
- return acquireConfig(selected)
- }
- else process.exit()
- })
- }
-
- if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${owner}/${datarepo}.git/' not found`))){
- var choices = {
- t : `install a temporary local data folder.
- For more options. Request and use a personal username at chess@bbh.org.in )`
- , e : 'exit' }
-
- if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
- choices = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
- , {
- i : 'create a new instance with this name => will fork the default config under your username'
- , f : 'fork a new instance with this name for yourself for this node from another instance'
- , o : 'fork a new instance with this name for your organization from another instance'
- , c : 'create a custom config for yourself for this node'
- , p : 'create a custom config for yourself '
- }, choices)
- }
-
- return cli.prompt( choices
- , 'Data repo for instance not found. Would you like to ', 'e' ).then(propValue => {
-
- if(propValue === 't') {
- selectedinstance.local = true; return createInstanceData(selectedinstance)
- }
- if(propValue === 'i') return eNotImplemented()
- if(propValue === 'f') return eNotImplemented()
- if(propValue === 'o') return eNotImplemented()
- if(propValue === 'c') return eNotImplemented()
- if(propValue === 'p') return eNotImplemented()
-
- else process.exit()
- })
- }
-
- console.warn(e)
- throw e;
- }
-
- var successHandler = () => {
-
- }
-
- return performPullOrClone( selected.reposindexed[datarepo] || { repo : datarepo }
- , null, owner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
- .catch( (e)=>{
-
- if(Promise.resolve(e) === e) return e;
-
- e.benign = true;
- throw e;
-
- })
- }
-
-
-
-
-
- var launchpath = selectedinstance.root
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- var __interactive_prompts = function( target, choices, promptsfilter ){
-
- Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
-
- var interactionpoints = unbound_interactionpoints.bind({target, choices})(selectedinstance)
-
- function getPromptKeys() {
-
- if(! (processedArgs.label || processedArgs._[0]) ) return Object.assign({}, interactionpoints);
-
- return promptkeys
- }
- var eachPrompt = getBoundEachPrompt( target, getPromptKeys() , interactionpoints, choices, promptsfilter)
- return Object.keys(promptsfilter || interactionpoints).reduce(eachPrompt, [])
- }
-
-
- var downloadsdir = shell_verse.downloadsdir;
- var prerequisites = [
- {
- shellcmd: 'git',
- name : 'git',
- url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
- , installer: 'Git-2.31.0-64-bit.exe'
- , installcmd: ['cmd', ['/c', 'start',
- '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
- , '/VERYSILENT'
-
- ]]
- , preinstallsteps: function() {
- var steps = [
- () => {
- if (!existsSync(downloadsdir + '/' + this.installer)) {
- return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
- }
- else return Promise.resolve(true)
- }
- ]
- var prompts = this.getuser(null, ()=>{
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- return Promise.resolve(true)
- })
-
- return any([any(steps), prompts])
- }
- , installsteps: function () {
- return any([this.installcmd].map(getshelltask))
- }
- , postinstallsteps: function(err, users){
- return this.getuser(null, (err, data)=>{
-
- console.dir(data)
- if(data && data.length === 1 && !shouldPrompt('username', promptkeys, selectedinstance) ) {
- return username = data[0];
- }
-
- data = data || ['guest']
- choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
-
- console.log('prompting in postinstallsteps')
-
- var username = 'guest';
- var email = 'guest@bbh.org.in';
- var password = '***';
-
- return any( getInteractionPoints([selectedinstance], promptkeys, { username, password, email}) ).then(()=>{
- if(!data.find(e => e === selectedinstance.username)) {
- var steps = [
- ['git', ['config', '--global', '--add', 'user.name', `${username}`]]
- , ['git', ['config', '--global', '--add', 'user.email', `${email}`]]
- ]
- return any(steps.map(getshelltask)).then(() => {
-
- })
- }
- else {
- return Promise.resolve(true)
- }
- });
- })
- }
- , install: function () {
- return any([ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
- }
- , verifyAndInstall : function(){
- return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
- if(exists) {
-
- return this.postinstallsteps.bind(this)()
- }
- return this.install();
- });
- }
- , getuser : function(repo, onResult){
-
- var __onResult = onResult || function(e, data){
- data = data || []
- choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
-
- return data[0]
- }
-
- var globalOrLocal = '--global';
- if(repo) globalOrLocal = '--local'
-
- return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(getshelltask)).then((result)=>{
-
- if(!result.success) return __onResult(result)
- else {
- var users = result.messages[0].trim().split('\n');
- if(users.length === 0 ||
- users.length === 1 && users[0] === 'guest') {
-
- return __onResult(result)
- }
- else {
- return __onResult(null, Array.from( new Set( users ) ) ); }
- }
- })
- .catch((e)=>{
- console.error(e)
- return __onResult(e)
- })
- }
- }
- ,
- {
- shellcmd: 'node',
- name : 'node',
- url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
- , installer: 'node-v14.16.0-x64.msi'
- , installcmd: ['MSIEXEC.exe', ['/i'
- , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
- , 'ACCEPT=YES', '/passive']]
- , install : function() { return any([this.installcmd].map(getshelltask)).then(() => { }) }
- }
- ]
- for(var i=0; i<prerequisites.length; i++) {
- prerequisites[prerequisites[i].name] = prerequisites[i];
- }
-
- prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
-
- var mainTasks = [];
- function verifyAndInstallPrerequisites() {
- var downloadtasks = [];
- var installtasks = [];
- prerequisites.forEach(preq => {
- downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
- if (exists) console.log(`${preq.shellcmd} exists`)
- else {
- console.log(`${preq.shellcmd} is not installed`)
- return preq.preinstallsteps.call(preq).then(() => {
- installtasks.push(preq.install.bind(preq))
- })
- }
- }))
- })
- return Promise.all(downloadtasks).then(() => { return any(installtasks) })
- }
-
-
- var runconfig = null;
-
- var promptkeys = {
- cmd : processedArgs._[0] || 'pull'
-
-
-
-
-
- }
-
-
- var choices = {
- 'instanceName' : []
- , 'reposerver' : []
- , 'upstream-remote' : []
- , 'instanceType' : []
- , username : ['guest', 'chessdemo', 'demo']
- }
-
- var getInteractionPoints = function(detectedinstanceoptions, possiblePrompts, promptsfilter){
-
- var instances = []
- var reposervers = [];
- var remotes = [];
- var instanceNames = []
- var instanceTypes = ['development', 'production'];
-
-
- Object.keys( chessinstances).forEach(instanceName => {
- if(instanceName === 'current_run') return ;
- Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
- var instance = chessinstances[instanceName][node_env];
- reposervers = reposervers.concat(instance.reposervers)
- if(instance.reposerver) reposervers.push(instance.reposerver)
- instances.push(instance)
- instanceTypes.push(instance.node_env)
- instanceNames.push(instance.instanceName)
- var otherremotes = instance?.reposerverinstances
- if(otherremotes) otherremotes = otherremotes[instance?.reposerver]?.remotes
- otherremotes = otherremotes || {}
- Array.prototype.push.apply(remotes, Object.keys(otherremotes))
- })
- })
- instances = instances.concat(detectedinstanceoptions)
-
- if(selectedinstance['instanceName']) instanceNames.push(selectedinstance['instanceName'])
- if(possiblePrompts['instanceName']) instanceNames.push(possiblePrompts['instanceName'])
- if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers'])
-
- choices['instanceName'] = Array.from( new Set(instanceNames.concat(choices['instanceName'])) )
- choices['reposerver'] = Array.from( new Set(reposervers.concat(choices['reposerver'])) )
-
- choices['instanceType'] = Array.from( new Set(instanceTypes.concat(choices['instanceType'])) )
-
- return __interactive_prompts(selectedinstance, choices, promptsfilter)
- }
-
- var detection_state = {
- localInstanceDetected : false
- }
-
- function createInstanceData(target, source) {
-
- var sourceinstance = source || target;
- console.dir(sourceinstance)
- var args = {
- remotebase : sourceinstance.reposerver
- , sourcerepo : sourceinstance.repo || 'chess-data'
- , targetrepo : `${target.instanceName}-data-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
- }
-
- if(sourceinstance.local) {
-
- var options = {
- inherit: true, shell: true,
- env: ENV
- , cwd : instanceroot
- , runas: processedArgs.runas
- }
- var cmdseq = [
- ['git', ['clone', `${args.remotebase}/${owner}/${args.sourcerepo}`, `${args.targetrepo}`], options]
- ]
- return any(cmdseq.map(getshelltask)).then(() => { return true })
- }
- else {
-
-
- if(source.reposerver !== target.reposerver && source.username !== target.username) {
- throw 'createInstanceData is possible only within the same repository server.'
- }
-
- var server = new URL(target.reposerver);
- return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
- , username : target.username, password : target.password
- }
-
- , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
- return GITEA.repository.updateattributes( {
- hostname : server.host, protocol : server.protocol
- , username : target.username, password : target.password
- }
- , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
- , { name : `${args.targetrepo}`}
- )
- }
- )
- }
-
-
-
-
-
-
-
-
-
-
- }
-
-
- function createInstance(target, source) {
-
- var sourceinstance = source || target;
- console.dir(sourceinstance)
- var args = {
- remotebase : sourceinstance.reposerver + '/chess/'
- , sourcerepo : sourceinstance.repo || 'chess-config'
- , targetrepo : `${target.instanceName}-config-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
- }
-
- if(sourceinstance.local) {
-
- var options = {
- inherit: true, shell: true,
- env: ENV
- , cwd : instanceroot
- , runas: processedArgs.runas
- }
- var cmdseq = [
- ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
- ]
- return any(cmdseq.map(getshelltask)).then(() => { return true })
- }
- else {
-
-
- if(source.reposerver !== target.reposerver && source.username !== target.username) {
- throw 'createInstance is possible only within the same repository server.'
- }
-
- var server = new URL(target.reposerver);
- return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
- , username : target.username, password : target.password
- }
-
- , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
- return GITEA.repository.updateattributes( {
- hostname : server.host, protocol : server.protocol
- , username : target.username, password : target.password
- }
- , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
- , { name : `${args.targetrepo}`}
- )
- }
- )
- }
-
-
-
-
-
-
-
-
-
-
- }
-
- var skipprerequisites = false;
- function initinstances() {
-
-
- var instanceName = selectedinstance.instanceName
- var node_env = selectedinstance.node_env
- var reposerver = selectedinstance.reposerver
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- if(selectedinstance.node_env === undefined) delete selectedinstance.node_env
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- if(selectedinstance?.repos && !selectedinstance?.repos[0]?.repo) {
- console.warn('repo manifest has obsolete format. Attempting upgrade.')
- selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
- }
- if(selectedinstance?.elevated && !selectedinstance?.elevated[0]?.repo) {
- console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
- selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
- }
-
-
-
-
-
- cacheWriteInstanceConfig(chessinstances, selectedinstance.root)
-
-
- selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0]
-
- return chessinstances
- }
-
- var skipprereqs = {}
- var maintask = () => {
-
-
- processedArgs._[0] === processedArgs._[0] || 'pull';
-
-
- if(!noprerequisites[processedArgs._[0]]
- && !skipprereqs[processedArgs._[0]]
- ) {
- return prerequisites.git.verifyAndInstall().then(()=>{
- var e = { message : 'verifyAndInstall', success : true}
- var inittasks = []
- var commontask = () => { preworkerconfig(); return elxrworker(oplist) }
- if(!detection_state.localInstanceDetected) {
- var t1 = ()=>{ return createInstance(selectedinstance) };
- t1.statuslog = statuslog
- var specifictask = shell_verse.getNonElevatedTask(t1)
- }
- else {
- var t2 = ()=>{ return acquireConfig(selectedinstance) };
- t2.statuslog = statuslog
- var specifictask = shell_verse.getNonElevatedTask(t2)
- }
- inittasks.push( specifictask().catch((err) => {
- e = err;
- console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
- console.error(err)
- }).then( commontask )
-
-
-
-
-
- )
-
- return any(inittasks)
- })
- }
- else {
- console.log('cmd has no preqs or has been configured to skip preqs')
- preworkerconfig()
- return elxrworker(oplist)
- }
-
- }
-
- function generateDependencies(){ return shell_verse.generateDependencies() }
-
- var startElxr = function() {
- const retaincount = 2
- var min = runtimestamp;
- var collect = []
-
- if(reconfirmcmds[processedArgs.label || processedArgs._[0]]) {
- reconfirm = getReconfirmAll()
- }
-
-
- var detectedinstanceoptions = [selectedinstance]
-
- var cmdinstance = cmds[clioverrides.cmd]
- var cmdprompts = cmdinstance.getPossiblePrompts()
-
-
- utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }, selectedinstance, promptkeys )
-
-
-
-
-
-
-
- try {
-
-
-
- initinstances(selectedinstance)
- var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
- var inst = initinstances(selectedinstance)
- detection_state.localInstanceDetected = true;
- return inst;
- })
- }
- catch (e) {
-
- var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
- return initinstances(selectedinstance)
- })
-
-
-
-
-
-
- todo = todo.then(() => {
- try {
-
-
-
- initinstances(selectedinstance)
- detection_state.localInstanceDetected = true;
- }
- catch (e) {
-
- console.log('No local instances config found in current root = ' + selectedinstance.root);
- console.log('A config will be createed with the instance and environment chosen...')
-
-
-
-
- detection_state.localInstanceDetected = false;
- return selectedinstance
- }
- })
- }
- return todo.then( ()=>{
-
-
-
- initinstances(selectedinstance)
-
- runconfig = { NODE_ENV: selectedinstance.node_env }
- try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
- generateDependencies();
- if(noprerequisites[processedArgs._[0]]
- || skipprereqs[processedArgs._[0]]
- ) {
- return elxrworker(oplist)
- }
-
- var neTask = ()=>{
- ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`)
-
- return dirs( (dir)=>{
- var matches = /run-(.*)/gm.exec(dir.name)
- if(matches) {
- if(+(matches[1]) < min) {
- min = matches[1]
- collect.splice( 0, 0, matches[1] )
- }
- else collect.push(matches[1])
- }
- return Promise.resolve(collect);
- }, `${selectedinstance.root}/.elxr` )
- .then(()=>{
-
- if(collect.length > retaincount) {
-
- var asyncs = [];
- while((collect.length - asyncs.length) > retaincount) {
- asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
- }
- return Promise.all(asyncs)
- }
- else return true
- })
- .catch(e => {
- console.error
- })
- }
- neTask.statuslog = statuslog
-
- shell_verse.getNonElevatedTask( neTask )()
-
- var commonTask = ()=>{
- verifyAndInstallPrerequisites.statuslog = statuslog
- if((!skipprerequisites || processedArgs.forceprereqs)) mainTasks.push(verifyAndInstallPrerequisites);
- mainTasks.push(maintask)
- return any(mainTasks);
- }
- return commonTask()
-
- })
-
-
- }
-
-
-
- var cmdobj = cmds[selectedinstance.cmd]
- return Promise.all((cmdobj.requires || []).map( (r) => utils.promisify(null, r) ) ).then(()=>{
- if(cmdobj.independentcmd) {
- if(cmdobj.requiresElevation) {
- return cmdobj.cmdFn(cmdobj.toArgs(processedArgs))
- }
- else return cmdobj.cmdFn(cmdobj.toArgs(processedArgs))
- }
- else return startElxr()
- })
- .catch(e => {
- if(typeof e === 'symbol') console.log('error : ' + 'symbol')
- else console.log('error : ' + e)
- })
-
-
-
-
- })
- })
-
-
-
-
-
-
-
-
-
- function checkandinstall(items) {
- var tasks = []
- items.forEach(item => {
- tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
- })
-
- return Promise.all(tasks).then(existances => {
- existances.forEach((exists, i) => {
- if (!exists) {
- return downloadandinstall([items[i]])
- }
- })
- })
- }
-
- function downloadandinstall(items) {
- var tasks = []
- items.forEach(item => {
- tasks.push(getTaskDownload(item))
- })
- return Promise.all(tasks)
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
|