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

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