選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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