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

index.js 242KB

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