555
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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