Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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