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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929
  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( { message : `Started ${runtimestamp}`, success:true})) // 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. e.benign = true
  2690. return e; }
  2691. )
  2692. }
  2693. , ownerInstnace(selected) { return __acquireConfig(selected, { remote : 'userfork' }
  2694. , selected.instanceName + '-config-' + selected.node_env
  2695. , function(e){ console.info('Customized user level config not found. This is not an Error. Will attempt global common instance config.');
  2696. e.benign = true
  2697. return e }
  2698. )
  2699. }
  2700. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  2701. , commonInstance(selected) { return __acquireConfig(selected, { repoOwner : defaultRepoOwner }
  2702. , undefined
  2703. , function(e){
  2704. // PB : TODO -- console.info('This is probably an error unless the user is asking to create a new instance with this name.')
  2705. statuslog.statuslog(e, e)
  2706. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  2707. utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  2708. , selectedinstance, require(manifestpath)( null, { utils, username : selectedinstance.username, instanceName : selectedinstance.instanceName
  2709. , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' } ))
  2710. console.dir(selectedinstance.repos)
  2711. // Config from server always override merges into selection except for the current selection.
  2712. // PB : TODO -- utils.assign Array merges are non-distinct...
  2713. if(selectedinstance?.repos && !selectedinstance.repos[0].repo) {
  2714. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  2715. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  2716. }
  2717. if(selectedinstance?.elevated && !selectedinstance.elevated[0]?.repo) {
  2718. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  2719. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  2720. }
  2721. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  2722. , selected, selectedinstance)
  2723. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  2724. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  2725. cacheWriteInstanceConfig(chessinstances)
  2726. // ENV.NODE_ENV = selectedinstance.node_env;
  2727. throw e
  2728. }
  2729. ) }
  2730. // , genericChessInstance(selected) { return __acquireConfig(selected, { repoOwner : defaultRepoOwner }) }
  2731. }
  2732. })()
  2733. var eNotImplemented = function(){
  2734. console.error('Not yet implemented')
  2735. process.exit()
  2736. }
  2737. // PB : TODO -- accept additional arg - an array specifying custom configPriority.
  2738. var acquireConfig = function(slections){
  2739. var configPriority = [ 'ownerClusterNodeConfig', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  2740. return any(configPriority.map(cfg => { return function() { return configs[cfg](slections) } } ), true, true).then(()=>{
  2741. return acquireData(slections)
  2742. })
  2743. }
  2744. var instanceData = (function(){
  2745. return {
  2746. ownerClusterNodeData(selected) {
  2747. var clusternodename = hostname || `CHESS0001${selected.username}`; // Cluster node names need to be unique accross all clusters to avoid collitions.
  2748. clustername = clustername || `${selected.username}-CHESS-${selected.node_env}`;
  2749. return __acquireData(selected, { remote : 'userfork' }
  2750. , selected.instanceName + '-data-' + selected.node_env + `-${clusternodename}`
  2751. , function(e){ console.info('Customized node level data not found. This is not an Error. Will attempt with owner level config.');
  2752. e.benign = true
  2753. return e; }
  2754. )
  2755. }
  2756. , ownerInstnace(selected) { return __acquireData(selected, { remote : 'userfork' }
  2757. , selected.instanceName + '-data-' + selected.node_env
  2758. , function(e){ console.info('Customized user level data not found. This is not an Error. Will attempt global common instance config.');
  2759. e.benign = true
  2760. return e }
  2761. )
  2762. }
  2763. // PB : TODO -- Use the ORG level instance before falling back to common Instance coz common instance may not exist for certain orgs.
  2764. , commonInstance(selected) { return __acquireData(selected, { repoOwner : defaultRepoOwner }
  2765. // , function(e){ console.info('This is probably an error unless the user is asking to create a new instance with this name.') }
  2766. ) }
  2767. , genericChessInstance(selected) { return __acquireData(selected, { repoOwner : defaultRepoOwner }) }
  2768. }
  2769. })()
  2770. var acquireData = function(slections){
  2771. var configPriority = [ 'ownerClusterNodeData', 'ownerInstnace', 'commonInstance' /*, 'genericChessInstance'*/ ]
  2772. return any(configPriority.map(cfg => { return function() { return instanceData[cfg](slections) } } ), true, true)
  2773. }
  2774. function reinit(){
  2775. sysAddPathVar('%AppData%\\npm')
  2776. resetgitconfig()
  2777. }
  2778. function init(){
  2779. sysAddPathVar('%AppData%\\npm')
  2780. resetgitconfig()
  2781. }
  2782. function resetgitconfig(){
  2783. // https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage
  2784. // Git Credential storage...
  2785. // git config --global credential.helper 'store --file ~/.gitcredentials'
  2786. // git credential fill
  2787. // protocol=https
  2788. // host=git.bbh.org.in
  2789. // username=bob
  2790. // password=pppp
  2791. // git credential-store --file ~/.gitcredentials store
  2792. // // notepad C:/Program Files/Git/etc/gitconfig
  2793. // git config --edit --system
  2794. // git credential-store --file ~/git.store store
  2795. // Find system git config
  2796. // git config --global --edit
  2797. // git config --list --show-origin
  2798. // git config --list --show-origin --show-scope
  2799. // https://stackoverflow.com/questions/35942754/how-can-i-save-username-and-password-in-git
  2800. // Recipie
  2801. // git config --global --unset credentials.helper
  2802. // cd /path/to/my/repo
  2803. // git config --unset credential.helper
  2804. // git config credential.helper 'store --file ~/.git_repo_credentials'
  2805. // git config credential.*.username my_user_name
  2806. // git config credential.https://gitlab.com.username my_user_name
  2807. // git credential fill
  2808. // git config --global credential.modalprompt false // doesnst work.
  2809. // core askpass = ;;; https://stackoverflow.com/questions/37182847/how-do-i-disable-git-credential-manager-for-windows
  2810. var options = {
  2811. inherit: true, shell: true //, env: process.env
  2812. , cwd: instanceroot
  2813. , runas: processedArgs.runas
  2814. }
  2815. var task = ['git', ['config'], options]
  2816. var tasklist = [
  2817. // ['--global', '--unset credentials.helper']
  2818. // ['--unset', 'credentials.helper']
  2819. // ,
  2820. // ['credential.helper', `'store --file git_repo_credentials'`]
  2821. ['--global', 'credential.helper', "'store --file ~/.git_repo_credentials'"]
  2822. , ['--global', '--replace-all', 'user.name', 'pb']
  2823. , ['--global', '--replace-all', 'user.email', 'pradeep@bbh.org.in']
  2824. // , ['--list']
  2825. // , ['credential', 'fill']
  2826. ]
  2827. var onEachError = e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n')
  2828. var shellT = (args) => { return getgitbashtask(args, onEachError)
  2829. // .catch(e => console.error( e.messages.join('\n') + e.result + '\n' + util.inspect(e) + '\n' + tasq.toString()) )
  2830. }
  2831. execserial(tasklist, task, shellT, onEachError )
  2832. }
  2833. var createTasq = (args, shellT, onEachError) => {
  2834. var tasq = shellT ? shellT(args) : (() => { return nodeShellExec.apply(null, args).catch( onEachError || function(e){ console.error(e) } ) })
  2835. tasq.toString = function(){ return JSON.stringify(args)}
  2836. return tasq;
  2837. }
  2838. var execserial = function(tasklist, task, shellT){
  2839. var exec = (taskArgs)=>{
  2840. var thistask = task.concat();
  2841. thistask[1] = thistask[1].concat()
  2842. thistask[1].push.apply(thistask[1], taskArgs)
  2843. return createTasq(thistask, shellT)
  2844. }
  2845. return any(tasklist.map(exec))
  2846. }
  2847. var execonce = function(taskArgs, task){ return any([task[1].push.apply(task[1], taskArgs)].map(createTasq)) }
  2848. var __acquireConfig = function (selected, options, configrepo, errHandler) {
  2849. configrepo = configrepo || selected.instanceName + '-config-' + selected.node_env;
  2850. var repoOwner = options.repoOwner || selected.username || options.defaultRepoOwner
  2851. var errorHandler = (e) => {
  2852. 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`))){
  2853. // console.error('Could not connect to repo server. Timed Out')
  2854. 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 => {
  2855. if(propValue === 'y') {
  2856. reconfirm = getReconfirmAll()
  2857. return startElxr()
  2858. }
  2859. else if(propValue === 'r'){
  2860. return acquireConfig(selected)
  2861. }
  2862. else process.exit()
  2863. })
  2864. }
  2865. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${repoOwner}/${configrepo}.git/' not found`))){
  2866. var choices = {
  2867. t : `install a new temporary local instance with this name ( will not persist ).
  2868. Use your own username for additional options. You can request for a username at chess@bbh.org.in )`
  2869. , e : 'exit' }
  2870. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  2871. choices = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  2872. , {
  2873. i : 'create a new instance with this name => will fork the default config under your username'
  2874. , f : 'fork a new instance with this name for yourself for this node from another instance'
  2875. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  2876. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  2877. , p : 'create a custom config for yourself '
  2878. }, choices)
  2879. }
  2880. return cli.prompt( choices
  2881. , 'Config for instance not found. Would you like to ', 'e' ).then(propValue => {
  2882. if(propValue === 't') {
  2883. selectedinstance.local = true; return createInstance(selectedinstance)
  2884. }
  2885. if(propValue === 'i') return eNotImplemented()
  2886. if(propValue === 'f') return eNotImplemented()
  2887. if(propValue === 'o') return eNotImplemented()
  2888. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  2889. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  2890. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  2891. else process.exit()
  2892. })
  2893. }
  2894. console.warn(e)
  2895. throw e; //('Config acquisition failed.')
  2896. }
  2897. var successHandler = () => {
  2898. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  2899. utils.assign_core( { keycase : true, arraymergetype : utils.assign_core.DISTINCT_UNION }
  2900. , selectedinstance, require(manifestpath)( null, { utils, username : selectedinstance.username, instanceName : selectedinstance.instanceName
  2901. , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' }))
  2902. console.dir(selectedinstance.repos)
  2903. // Config from server always override merges into selection except for the current selection.
  2904. // PB : TODO -- utils.assign Array merges are non-distinct...
  2905. if(!selectedinstance.repos[0].repo) {
  2906. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  2907. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  2908. }
  2909. if(selectedinstance.elevated[0] && !selectedinstance.elevated[0].repo) {
  2910. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  2911. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  2912. }
  2913. chessinstances[selected.instanceName][selected.node_env] = selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  2914. , selected, selectedinstance)
  2915. chessinstances[selected.instanceName][selected.node_env].reposervers = Array.from(new Set(chessinstances[selected.instanceName][selected.node_env].reposervers))
  2916. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  2917. cacheWriteInstanceConfig(chessinstances)
  2918. ENV.NODE_ENV = selectedinstance.node_env;
  2919. }
  2920. return performPull( selected.reposindexed[configrepo] || { repo : configrepo }
  2921. , null, repoOwner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  2922. .catch( (e)=>{
  2923. // if(e){
  2924. if(Promise.resolve(e) === e) return e;
  2925. // console.error(e)
  2926. e.benign = true;
  2927. throw e; // Not a hard error but we need this for bcontinueonfailure as we still want to stop on firstsuccess.
  2928. // }
  2929. })
  2930. }
  2931. var __acquireData = function (selected, options, datarepo, errHandler) {
  2932. datarepo = datarepo || selected.instanceName + '-data';
  2933. var repoOwner = options.repoOwner || selected.username || options.defaultRepoOwner
  2934. var errorHandler = (e) => {
  2935. 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`))){
  2936. // console.error('Could not connect to repo server. Timed Out')
  2937. 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 => {
  2938. if(propValue === 'y') {
  2939. reconfirm = getReconfirmAll()
  2940. return startElxr()
  2941. }
  2942. else if(propValue === 'r'){
  2943. return acquireConfig(selected)
  2944. }
  2945. else process.exit()
  2946. })
  2947. }
  2948. if(e.messages.join(' ').match(new RegExp (`fatal: repository '${selectedinstance.reposerver}/${repoOwner}/${datarepo}.git/' not found`))){
  2949. var choices = {
  2950. t : `install a temporary local data folder.
  2951. For more options. Request and use a personal username at chess@bbh.org.in )`
  2952. , e : 'exit' }
  2953. if(selectedinstance.username !== 'guest' && selectedinstance.username !== 'demo') {
  2954. choices = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  2955. , {
  2956. i : 'create a new instance with this name => will fork the default config under your username'
  2957. , f : 'fork a new instance with this name for yourself for this node from another instance'
  2958. , o : 'fork a new instance with this name for your organization from another instance' // prompt organization name...
  2959. , c : 'create a custom config for yourself for this node' // prompt hostname as nodename
  2960. , p : 'create a custom config for yourself '
  2961. }, choices)
  2962. }
  2963. return cli.prompt( choices
  2964. , 'Data repo for instance not found. Would you like to ', 'e' ).then(propValue => {
  2965. if(propValue === 't') {
  2966. selectedinstance.local = true; return createInstanceData(selectedinstance)
  2967. }
  2968. if(propValue === 'i') return eNotImplemented()
  2969. if(propValue === 'f') return eNotImplemented()
  2970. if(propValue === 'o') return eNotImplemented()
  2971. if(propValue === 'c') return eNotImplemented() // return createLocalChessInsance(selectedinstance)
  2972. if(propValue === 'p') return eNotImplemented() // return createChessInstance(selectedinstance)
  2973. // if(propValue === 'o') createChessInstance(selectedinstance, orgname)
  2974. else process.exit()
  2975. })
  2976. }
  2977. console.warn(e)
  2978. throw e; //('Config acquisition failed.')
  2979. }
  2980. var successHandler = () => {
  2981. }
  2982. return performPull( selected.reposindexed[datarepo] || { repo : datarepo }
  2983. , null, repoOwner, errHandler || errorHandler || ((e)=>{ throw e })).then( successHandler )
  2984. .catch( (e)=>{
  2985. // if(e){
  2986. if(Promise.resolve(e) === e) return e;
  2987. // console.error(e)
  2988. e.benign = true;
  2989. throw e; // Not a hard error but we need this for bcontinueonfailure
  2990. // }
  2991. })
  2992. }
  2993. var launchpath = path.resolve(path.normalize(process.env.wd))
  2994. 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.
  2995. // The easisest would be to ask for a target directory and default to current dir....
  2996. // path.dirname(launchpath).split(path.sep).pop()
  2997. var parent = path.dirname(launchpath);
  2998. var pp = launchpath;
  2999. var instancediscoverytasks = [];
  3000. while(parent !== pp){
  3001. instancediscoverytasks.push(
  3002. ((pa)=>{
  3003. var p = pa;
  3004. return function(){
  3005. return hasElxr(p).then((value)=>{
  3006. if(value) return p
  3007. // PB : TODO -- Using throw like this is not friendly with any...
  3008. throw Object.assign( new Error('Benign Failure in Batch')
  3009. , { value : false, benign : true });
  3010. })
  3011. }
  3012. })(pp)
  3013. )
  3014. pp = parent;
  3015. parent = path.dirname(parent);
  3016. }
  3017. var instanceroot = null
  3018. var detectInstanceRoot = any(instancediscoverytasks, true, true).then( ir => {
  3019. if(ir.error) { instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ; }
  3020. else instanceroot = ir.pVal
  3021. return instanceroot
  3022. }).catch(()=>{
  3023. instanceroot = path.normalize(thisscriptdir) === path.normalize(launchpath) ? path.normalize(thisscriptdir + '/..') : launchpath ;
  3024. })
  3025. // We first load the default and then override with a runconfig if it exists else we override with the interactive prompts.
  3026. // Then acquire and reload and replace this default.
  3027. var hasElxr = function(path, options, cb) {
  3028. // PB : TOOD -- Navigate up the folder chain to discover the relevant .elxr directory.
  3029. options = options || {};
  3030. var tasks = [
  3031. '/elxr' // Is there a subfolder named elxr
  3032. , '/elxr/.git' // which is self git repository
  3033. // , '/elxr/.elxr' // and has .elxr subfolder we now store this in the instanceroot.
  3034. , '/elxr/' + __ALIAS__STAMP__ // Which has our stamp.
  3035. ]
  3036. if(options.sync) { return tasks.earlyreduce((acc, tpath)=>{
  3037. var value = existsFolderSync(path + tpath);
  3038. return { value, done : acc && !value };
  3039. }).value }
  3040. if(cb) return cb(null, tasks.earlyreduce((acc, tpath)=>{
  3041. var value = existsFolderSync(path + tpath);
  3042. return { value, done : acc && !value };
  3043. }).value );
  3044. return Promise.resolve(tasks.earlyreduce((acc, tpath)=>{
  3045. var value = existsFolderSync(path + tpath);
  3046. return { value, done : acc && !value };
  3047. }).value);
  3048. }
  3049. var hasElxrSync = function(path){ return hasElxr(path, { sync :true}); }
  3050. var detectfromroot = function(root){
  3051. return { root, node_env : path.basename(root), instanceName : path.basename( path.dirname(root) ) }
  3052. }
  3053. var detectLocalInstances = function () {
  3054. console.log(`launchpath = ${launchpath}`)
  3055. console.log(`thisscriptdir = ${thisscriptdir}`)
  3056. // PB : TODO -- !Postpone this.
  3057. console.log(`instanceroot = ${instanceroot}`) // Not yet confirmed...
  3058. // Note : Paths should already be normalized fefore this.
  3059. var root = instanceroot;
  3060. var detected = { root };
  3061. var instanceoptions = [clioverrides]
  3062. return hasElxr(launchpath).then( (elxrCliExists) => {
  3063. // We need a reference to the root director for elxr cli to be properly oriented.
  3064. if (( elxrCliExists && path.normalize(launchpath + '/elxr')) === thisscriptdir) {
  3065. // We were run from the proper root with elxr cli in the subfolder.
  3066. instanceroot = root = launchpath;
  3067. instanceoptions.splice( 0, 0, detected = { root })
  3068. instanceoptions.splice( 0, 0, detectfromroot(root))
  3069. }
  3070. else {
  3071. if(path.normalize(launchpath + '/elxr') === thisscriptdir) {
  3072. // elxrCliExists is false -- and yet thiscriptdir is still proper.
  3073. // PB : TODO -- Maybe a warning / abort if for some reason this scriptdir should not be taken over...
  3074. console.error('Warning : detected thisscriptdir as elxr subfolder but not recognized as elixir. git updates might fail.')
  3075. instanceroot = root = launchpath;
  3076. instanceoptions.splice( 0, 0, detected = { root })
  3077. instanceoptions.splice( 0, 0, detectfromroot(root))
  3078. }
  3079. else if (launchpath === thisscriptdir) {
  3080. var parentHasElxr = hasElxrSync(launchpath + '/..')
  3081. // PB : TODO -- verify if we have .elxr folder in the parent...
  3082. if(!parentHasElxr) {
  3083. // ! thisscriptdir is not elxr.
  3084. console.error('Invalid run location in subfolder that looks like elxr. We should probably abort as elxr will not sync.')
  3085. }
  3086. // Same directory doesn't mean we are being run from elxr sub directory.
  3087. // In standalone build script we may or not be in the same location.
  3088. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  3089. // Unbuilt therefore we are in the elxr sub directory.
  3090. instanceroot = root = path.normalize(launchpath + '/..');
  3091. instanceoptions.splice( 0, 0, detected = { root });
  3092. instanceoptions.splice( 0, 0, detectfromroot(root));
  3093. }
  3094. else {
  3095. // Built version.
  3096. // We could have been run from the elxr subfolder. Highly likely that the built version isn't the full elxr.
  3097. if(parentHasElxr) {
  3098. // Built version was run from the full elxr subfolder. Should work
  3099. // PB : TODO -- but we should switch to the full version...
  3100. instanceroot = root = path.normalize(launchpath + '/..');
  3101. instanceoptions.splice( 0, 0, detected = { root })
  3102. instanceoptions.splice( 0, 0, detectfromroot(root))
  3103. }
  3104. else {
  3105. instanceroot = root = launchpath;
  3106. instanceoptions.splice( 0, 0, detected = { root })
  3107. instanceoptions.splice( 0, 0, detectfromroot(root))
  3108. // Assume current launchpath is a new instance and create.
  3109. // Figure out the instnace name and environment from parent folders as an alternative option with confirmation if not provided in the arguments.
  3110. // if(clioverrides.instanceName) {
  3111. // if(clioverrides.node_env) {
  3112. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + clioverrides.node_env)
  3113. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : clioverrides.node_env })
  3114. // // instanceoptions.splice( 0, 0, detectfromroot(root)) // This can be an option but is unnecessary unless a confirmation is provided.
  3115. // // also folder names may have no relation to the actual instanceName and instanceType coz we need to have many
  3116. // // eg : floder name can be elixir01 but instance name is elixr
  3117. // }
  3118. // else {
  3119. // instanceroot = root = path.normalize(launchpath + '/' + clioverrides.instanceName + '/' + 'development')
  3120. // instanceoptions.splice( 0, 0, detected = { root, instanceName : clioverrides.instanceName, node_env : 'development' })
  3121. // instanceoptions.splice( 0, 0, detectfromroot(root)) // A recessive option only.
  3122. // }
  3123. // }
  3124. // else {
  3125. // instanceroot = root = launchpath;
  3126. // if(clioverrides.node_env) {
  3127. // instanceoptions.splice( 0, 0, detected = { root, node_env : clioverrides.node_env })
  3128. // instanceoptions.splice( 0, 0, detectfromroot(root))
  3129. // }
  3130. // else {
  3131. // // Nothing was specified... We only have one option from root.
  3132. // instanceoptions.splice( 0, 0, detected = detectfromroot(launcpath))
  3133. // }
  3134. // }
  3135. }
  3136. }
  3137. }
  3138. else {
  3139. if(elxrCliExists) {
  3140. instanceroot = root = launchpath;
  3141. instanceoptions.splice( 0, 0, detected = { root })
  3142. instanceoptions.splice( 0, 0, detectfromroot(root))
  3143. }
  3144. }
  3145. }
  3146. instanceroot = detected.root
  3147. __default.root = root;
  3148. clioverrides.root = clioverrides.root || root;
  3149. // Resolves empty array when No known instances detected.
  3150. return Promise.resolve(instanceoptions)
  3151. })
  3152. }
  3153. var getReconfirmAll = ()=>{return { instanceName : true, instanceType : true, reposerver : true, username : true, password : true } }
  3154. if(clioverrides.reconfirm) {
  3155. var reconfirm = getReconfirmAll()
  3156. }
  3157. else { var reconfirm = {}; }
  3158. var shouldPrompt = function(k, possiblePrompts, target){
  3159. return ((possiblePrompts[k] !== undefined && possiblePrompts[k] !== null) && target[k] !== possiblePrompts[k]
  3160. || (possiblePrompts[k] === undefined || possiblePrompts[k] === null) && (target[k] === undefined || target[k] === null)
  3161. || reconfirm[k])
  3162. }
  3163. var getBoundEachPrompt = function(target, possiblePrompts, promptables, choices, promptsfilter) {
  3164. return function(prompts, k, i, a){
  3165. // Reducer for all prompts on targets.
  3166. // No local instances config found. We use a default initialized instance available in selectedinstance
  3167. // Confirm those that were not supplied as user choices in runtime args and proceed to reattempt.
  3168. // PB : TODO -- selectedinstance === __default check to prompt everything...
  3169. if( shouldPrompt(k, possiblePrompts, target) ) {
  3170. delete reconfirm[k];
  3171. // console.log(k)
  3172. // console.dir(possiblePrompts); //console.dir(target)
  3173. prompts.push(async ()=>{
  3174. // PB : NOTE -- Important in async cases when this {{target}} needs to be in the same state as when it was invoked.
  3175. // We need to take a snapshot... Shallow.. !! If required deep should be used based on use case.
  3176. // var asyncthis = Object.assign(this);
  3177. // By default Latest altered state is provided which is an implicit reference directly.
  3178. promptables[k].choices = choices[k]
  3179. Object.defineProperty(target, k, getPromptableAsyncPropDescriptor(k, promptables[k]));
  3180. return await target[k]
  3181. })
  3182. }
  3183. delete possiblePrompts[k] // PB : TODO We should keep this around instead of deleting so we can do a second pass if required.
  3184. return prompts
  3185. }
  3186. }
  3187. var __interactive_prompts = function( target, choices, promptsfilter ){
  3188. Object.defineProperty(target, 'node_env', { get : function(){ return this.instanceType } });
  3189. var interactionpoints = {
  3190. runchoice : {
  3191. label :
  3192. `Choose an option :
  3193. d) Install the default chess instance.
  3194. => elxr i chess node_env=development --default
  3195. n) Create your custom new instance interactively
  3196. => elxr i {{instanceName}} node_env={{environment}}
  3197. i) Choose an instance and environment to install
  3198. => elxr i {{instanceName}} node_env={{environment}}
  3199. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  3200. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  3201. h) Help
  3202. q) Quit
  3203. : `
  3204. , choices : []
  3205. , defaultchoice : 'c'
  3206. , selectedchoice : target.runchoice
  3207. , interpret : function(choice){
  3208. var interpret_map = {
  3209. d : function(){
  3210. processedArgs._[0] = 'i'
  3211. target.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  3212. target.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  3213. target.reposerver = 'https://git.bbh.org.in'
  3214. }
  3215. , n : function() { processedArgs._[0] = 'i' }
  3216. , i : function() {
  3217. processedArgs._[0] = 'i'
  3218. // processedArgs._[1] = target.instanceName || processedArgs._[1] || 'chess';
  3219. }
  3220. , c : async function() {
  3221. // this here will always be the target.
  3222. Object.defineProperty(this, 'cmd', getPromptableAsyncPropDescriptor('cmd', {
  3223. label : `Enter cmd :
  3224. p) pull
  3225. Default <= p
  3226. : `
  3227. , defaultchoice : 'pull'
  3228. }
  3229. ));
  3230. var cmd = await target['cmd'];
  3231. if (!cmd || cmd === 'p') { target['cmd'] = processedArgs._[0] = 'pull' }
  3232. else target['cmd'] = processedArgs._[0] = cmd
  3233. return cmd;
  3234. }
  3235. , h : function() { console.log(elxr.help()); process.exit() } // PB : TODO -- Why do we need log.
  3236. , q : function() { process.exit() }
  3237. }
  3238. if(Promise.resolve(choice) === choice){
  3239. return choice.then( resolvedchoice => {
  3240. return (interpret_map[choice] || interpret_map['c']).call(target)
  3241. })
  3242. }
  3243. else return Promise.resolve( (interpret_map[choice] || interpret_map['c']).call(target) )
  3244. // var __interpreter = interpret_map[choice] || interpret_map['c']
  3245. // if(!choice) return interpret_map['c']() // This should not happen prompter should always give us a default choice.
  3246. // if(interpret_map[choice]) __interpreter = interpret_map[choice];
  3247. // return __interpreter.call(target)
  3248. }
  3249. }
  3250. , instanceName : { label : `Enter Instance Name ( <= ${target.instanceName || 'chess'} ) : `
  3251. , choices : choices['instanceName'], defaultchoice : 'chess'
  3252. , selectedchoice : target.instanceName
  3253. }
  3254. , instanceType : { label : `Enter Instance Type ( <= ${target.instanceType || 'development'} ) : `
  3255. , choices : choices['instanceType'], defaultchoice : 'development'
  3256. , selectedchoice : target.instanceType || 'development'
  3257. }
  3258. , reposerver : { label : `Enter Repo Server Base Url ( <= ${target.reposerver || 'https://git.bbh.org.in'} ) : `
  3259. , get choices() {
  3260. choices['reposerver'].forEach( rs => {
  3261. var __rs = new URL(rs);
  3262. __rs.hostname = __rs.host;
  3263. __rs.path = '/'
  3264. __rs.method = 'GET'
  3265. RESTAPI.get(__rs, function(data){ rs.accessibility = 'unaccessible' }
  3266. , function(error){ rs.accessibility = 'unaccessible' } )
  3267. })
  3268. return choices['reposerver']
  3269. }
  3270. , defaultchoice : 'https://git.bbh.org.in'
  3271. , selectedchoice : target.reposerver
  3272. }
  3273. , 'upstream-remote' : { label : `Enter Remote Name ( <= ${target['upstream-remote'] || 'chess'} ) : `
  3274. , get choices() {
  3275. var reposerver = target['reposerver']
  3276. var remotes = []
  3277. var trs = target.reposervers || []
  3278. trs.forEach(rs => {
  3279. if(rs.server === reposerver){
  3280. remotes.push(remote)
  3281. // PB : TODO -- Sort and display highest priority target.remotes.sort( )
  3282. }
  3283. })
  3284. return remotes
  3285. }
  3286. , defaultchoice : 'userfork'
  3287. , selectedchoice : target['upstream-remote'] || 'userfork'
  3288. // Just using getters resolves dependencies..., dependencies : [ ()=>{ return target['reposerver'] } ]
  3289. }
  3290. , 'remote-type' : { label : `Enter Remote Type ( <= ${target['remote-type'] || 'public'} ) : `
  3291. , get choices() {
  3292. return ['public', 'private', 'github', 'unc']
  3293. }
  3294. , defaultchoice : 'public'
  3295. , selectedchoice : target['remote-type'] || 'public'
  3296. // Just using getters resolves dependencies..., dependencies : [ ()=>{ return target['reposerver'] } ]
  3297. }
  3298. , 'selectedremotes' : { label : `Chose Remote Names ( <= ${target['selectedremotes'] || 'chess'} ) : `
  3299. , get choices() {
  3300. var reposerver = target['reposerver'] // PB : TODO -- We need options to work with multiple selected reposervers at the same time..
  3301. var remotenames = []
  3302. Object.entries(target.remotes || []).forEach( ([rname, r]) => {
  3303. if(r.server === reposerver && r.accessibility.find( target[ 'remote-type' ] )){
  3304. remotes.push(rname)
  3305. // PB : TODO -- Sort and display highest priority target.remotes.sort( )
  3306. }
  3307. })
  3308. // PB : TODO -- Need to generate all possible permuted choices nP( 1 -> n )
  3309. // Currenty handles all combinations without any priority order.
  3310. var _remotechoices = [] // Array of arrays of choices.
  3311. remotenames.forEach( r => {
  3312. var __rcs = []
  3313. _remotechoices.forEach(rc => {
  3314. __rcs.push( rc.concat(r) )
  3315. })
  3316. Array.prototype.push.apply( _remotechoices, __rcs)
  3317. _remotechoices.push(r)
  3318. })
  3319. return _remotechoices
  3320. }
  3321. , defaultchoice : ['userfork-public', 'chess-public']
  3322. , selectedchoice : target['selectedremotes'] || ['userfork-public', 'chess-public']
  3323. // , defaultchoice : { 'userfork-public' : target.remotes['userfork-public'] , 'chess-public' : target.remotes['chess-public'] }
  3324. // , selectedchoice : target['selectedremotes'] || { 'userfork-public' : target.remotes['userfork-public'] , 'chess-public' : target.remotes['chess-public'] }
  3325. // Info : Just using getters resolves dependencies..., dependencies : [ ()=>{ return target['reposerver'] } ]
  3326. }
  3327. , get username() { return { label : `Enter User Id for ${target.reposerver} ( <= ${target.username || 'chess'} ) : `
  3328. , choices : choices['username'], defaultchoice : 'chess', selectedchoice : target.username } }
  3329. , get password() { return { label : `Enter Password for ${target.username} @ ${target.reposerver} ( <= ${target.password || ''} ) : `
  3330. , choices : choices['password'], defaultchoice : '***', selectedchoice : target.password } }
  3331. , get email() { return { label : `Enter Email for ${target.username} @ ${target.reposerver} ( <= ${target.email || ''} ) : `
  3332. , choices : choices['email'], defaultchoice : 'guest@bbh.org.in', selectedchoice : target.email } }
  3333. }
  3334. function getPromptKeys() {
  3335. if(! (processedArgs.label || processedArgs._[0]) ) return Object.assign({}, interactionpoints);
  3336. return promptkeys
  3337. }
  3338. var eachPrompt = getBoundEachPrompt( target, getPromptKeys() , interactionpoints, choices, promptsfilter)
  3339. return Object.keys(promptsfilter || interactionpoints).reduce(eachPrompt, [])
  3340. }
  3341. var downloadsdir = '../Downloads';
  3342. var prerequisites = [
  3343. {
  3344. shellcmd: 'git',
  3345. name : 'git',
  3346. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  3347. , installer: 'Git-2.31.0-64-bit.exe'
  3348. , installcmd: ['cmd', ['/c', 'start',
  3349. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  3350. , '/VERYSILENT'
  3351. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  3352. ]]
  3353. , preinstallsteps: function() {
  3354. var steps = [
  3355. () => {
  3356. if (!existsSync(downloadsdir + '/' + this.installer)) {
  3357. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  3358. }
  3359. else return Promise.resolve(true)
  3360. }
  3361. ]
  3362. var prompts = this.getuser(null, ()=>{
  3363. // console.log('preinstallsteps')
  3364. // var gitUser = 'guest';
  3365. // var gitEmail = 'guest@bbh.org.in';
  3366. // var prompts = [];
  3367. // prompts.push( ()=>{ return cli.prompt(choices['username'], 'git user name').then(gituser => gitUser = gituser) } )
  3368. // prompts.push( ()=>{ return cli.prompt(choices['useremail'], 'git user email').then(gitemail => gitEmail = gitemail) } )
  3369. // console.log('prompting in preinstallsteps')
  3370. // return any(prompts).then(()=>{
  3371. // var steps = [
  3372. // ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  3373. // , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  3374. // ]
  3375. // return any(steps.map(getshelltask)).then(() => {
  3376. // })
  3377. // });
  3378. return Promise.resolve(true)
  3379. })
  3380. return any([any(steps), prompts])
  3381. }
  3382. , installsteps: function () {
  3383. return any([this.installcmd].map(getshelltask))
  3384. }
  3385. , postinstallsteps: function(err, users){
  3386. return this.getuser(null, (err, data)=>{
  3387. // ignore err and proceed with data as guest.
  3388. console.dir(data)
  3389. if(data && data.length === 1 && !shouldPrompt('username', promptkeys, selectedinstance) ) {
  3390. return username = data[0];
  3391. }
  3392. data = data || ['guest']
  3393. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  3394. console.log('prompting in postinstallsteps')
  3395. var username = 'guest';
  3396. var email = 'guest@bbh.org.in';
  3397. var password = '***';
  3398. return any( getInteractionPoints(selectedinstance, promptkeys, { username, password, email}) ).then(()=>{
  3399. if(!data.find(e => e === selectedinstance.username)) {
  3400. var steps = [
  3401. ['git', ['config', '--global', '--add', 'user.name', `${username}`]]
  3402. , ['git', ['config', '--global', '--add', 'user.email', `${email}`]]
  3403. ]
  3404. return any(steps.map(getshelltask)).then(() => {
  3405. })
  3406. }
  3407. else {
  3408. return Promise.resolve(true)
  3409. }
  3410. });
  3411. })
  3412. }
  3413. , install: function () {
  3414. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  3415. }
  3416. , verifyAndInstall : function(){
  3417. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  3418. if(exists) {
  3419. // return any(['git', ['config', '--global', '-l']].map(getshelltask))
  3420. return this.postinstallsteps.bind(this)()
  3421. }
  3422. return this.install();
  3423. });
  3424. }
  3425. , getuser : function(repo, onResult){
  3426. var __onResult = onResult || function(e, data){
  3427. data = data || []
  3428. choices['username'] = Array.from( new Set( data.concat( (choices['username'] || []) )) )
  3429. // console.dir(choices)
  3430. return data[0]
  3431. }
  3432. var globalOrLocal = '--global';
  3433. if(repo) globalOrLocal = '--local'
  3434. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(getshelltask)).then((result)=>{
  3435. // not yet configured.
  3436. if(!result.success) return __onResult(result)
  3437. else {
  3438. var users = result.messages[0].trim().split('\n');
  3439. if(users.length === 0 ||
  3440. users.length === 1 && users[0] === 'guest') {
  3441. return __onResult(result)
  3442. }
  3443. else {
  3444. return __onResult(null, Array.from( new Set( users ) ) ); }// PB : TODO == We should probably prompt with all the users available for selection !
  3445. }
  3446. })
  3447. .catch((e)=>{
  3448. console.log(e)
  3449. return __onResult(e)
  3450. })
  3451. }
  3452. }
  3453. ,
  3454. {
  3455. shellcmd: 'node',
  3456. name : 'node',
  3457. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  3458. , installer: 'node-v14.16.0-x64.msi'
  3459. , installcmd: ['MSIEXEC.exe', ['/i'
  3460. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  3461. , 'ACCEPT=YES', '/passive']]
  3462. , install : function() { return any([this.installcmd].map(getshelltask)).then(() => { }) }
  3463. }
  3464. ]
  3465. for(var i=0; i<prerequisites.length; i++) {
  3466. prerequisites[prerequisites[i].name] = prerequisites[i];
  3467. }
  3468. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  3469. function ensureDirectoryExistence(filePath) {
  3470. var dirname = path.dirname(filePath);
  3471. if (fs.existsSync(dirname)) {
  3472. return filePath;
  3473. }
  3474. ensureDirectoryExistence(dirname);
  3475. fs.mkdirSync(dirname);
  3476. return filePath;
  3477. }
  3478. var mainTasks = [];
  3479. function verifyAndInstallPrerequisites() {
  3480. var downloadtasks = [];
  3481. var installtasks = [];
  3482. prerequisites.forEach(preq => {
  3483. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  3484. if (exists) console.log(`${preq.shellcmd} exists`)
  3485. else {
  3486. console.log(`${preq.shellcmd} is not installed`)
  3487. return preq.preinstallsteps.call(preq).then(() => {
  3488. installtasks.push(preq.install.bind(preq))
  3489. })
  3490. }
  3491. }))
  3492. })
  3493. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  3494. }
  3495. var getPromptableAsyncPropDescriptor = function(propName, promptable){
  3496. return {
  3497. get (){
  3498. return any( promptable.dependencies || [] ).then(()=>{
  3499. return cli.prompt( promptable.choices, promptable.label, promptable.defaultchoice, promptable.selectedchoice ).then(propValue => {
  3500. var asyncprop = Promise.resolve(propValue)
  3501. if(promptable.interpret){
  3502. asyncprop = promptable.interpret(propValue)
  3503. }
  3504. return asyncprop.then(
  3505. ()=>{
  3506. Object.defineProperty(this, propName, {
  3507. value: propValue,
  3508. writable: true,
  3509. configurable : true,
  3510. enumerable : true
  3511. });
  3512. return propValue
  3513. }
  3514. )
  3515. })
  3516. } )
  3517. }
  3518. // , set (propValue){
  3519. // Object.defineProperty(this, propName, {
  3520. // value: propValue,
  3521. // writable: true, // PB : TODO -- Use this to fix value permanently until run is over.
  3522. // configurable : true,
  3523. // enumerable : true
  3524. // })
  3525. // return propValue;
  3526. // }
  3527. , configurable : true
  3528. , enumerable : true
  3529. }
  3530. }
  3531. function acquirelocalinstances(selected){
  3532. // utils.assign is used to cleanup duplicates... assuming chessinstances.js is probably not clean.
  3533. var chessinstances = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  3534. , require(path.normalize(selected.root + '/chessinstances.js')));
  3535. return chessinstances
  3536. }
  3537. function findlocalinstances(chessinstances, instanceoptions){
  3538. // We can expect a .elxr at each level.
  3539. ['' /* instanceroot */, '../' /* instanceTypes or node_env */, '../..' /* instanceNames */].
  3540. earlyreduce( ( value, p, i, a )=>{
  3541. var localinstancesPath = `${instanceroot}/${p}.elxr`;
  3542. if(existsSync( localinstancesPath )) {
  3543. try {
  3544. var chessinstances = acquirelocalinstances( { localinstancesPath } )
  3545. return Object.keys(chessinstances).earlyreduce( ( value, instanceName) => {
  3546. return Object.keys(chessinstances[instanceName]).earlyreduce( (value, instanceType) => {
  3547. if( path.normalize(chessinstances[instanceName][instanceType].root) === path.normalize( instanceroot) ) {
  3548. instanceoptions.splice( 0, 0, chessinstances[instanceName][instanceType])
  3549. return {
  3550. value : chessinstances[instanceName][instanceType]
  3551. , done : true
  3552. };
  3553. }
  3554. })
  3555. })
  3556. }
  3557. catch(e){
  3558. return { }
  3559. }
  3560. }
  3561. else return { }
  3562. }
  3563. )
  3564. }
  3565. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  3566. var runconfig = null;
  3567. var chessinstances = { current_run : {} };
  3568. var promptkeys = {
  3569. cmd : processedArgs._[0] || 'pull'
  3570. // Try not to prompt anything unless absolutely necessary or reconfirm is forced.
  3571. // 'instanceName' : true
  3572. // , 'node_env' : true
  3573. // , username : ''
  3574. // , runchoice : 'c'
  3575. }
  3576. // promptkeys.runchoice = promptkeys.cmd ? 'c' : undefined
  3577. function createLocalChessInstance( cfg ){
  3578. // return createInstance(cfg)
  3579. reconfirm = getReconfirmAll()
  3580. var inst = {};
  3581. var __new = Object.assign({}, __default, cfg)
  3582. inst[cfg.node_env] = __new; return inst;
  3583. }
  3584. var choices = {
  3585. 'instanceName' : []
  3586. , 'reposerver' : []
  3587. , 'upstream-remote' : []
  3588. , 'instanceType' : []
  3589. , username : ['guest', 'chessdemo', 'demo']
  3590. }
  3591. var getInteractionPoints = function(detectedinstanceoptions, possiblePrompts, promptsfilter){
  3592. var instances = []
  3593. var reposervers = [];
  3594. var remotes = [];
  3595. var instanceNames = []
  3596. var instanceTypes = ['development', 'production'];
  3597. Object.keys( chessinstances).forEach(instanceName => {
  3598. if(instanceName === 'current_run') return;
  3599. Object.keys( chessinstances[instanceName] ).forEach(node_env=>{
  3600. var instance = chessinstances[instanceName][node_env];
  3601. reposervers = reposervers.concat(instance.reposervers)
  3602. if(instance.reposerver) reposervers.push(instance.reposerver)
  3603. instances.push(instance)
  3604. instanceTypes.push(instance.node_env)
  3605. instanceNames.push(instance.instanceName)
  3606. var otherremotes = instance?.reposerverinstances
  3607. if(otherremotes) otherremotes = otherremotes[instance?.reposerver]?.remotes
  3608. otherremotes = otherremotes || {}
  3609. Array.prototype.push.apply(remotes, Object.keys(otherremotes))
  3610. })
  3611. })
  3612. instances = instances.concat(detectedinstanceoptions)
  3613. if(selectedinstance['instanceName']) instanceNames.push(selectedinstance['instanceName'])
  3614. if(possiblePrompts['instanceName']) instanceNames.push(possiblePrompts['instanceName'])
  3615. if(selectedinstance['reposervers']) reposervers = reposervers.concat(selectedinstance['reposervers'])
  3616. choices['instanceName'] = Array.from( new Set(instanceNames.concat(choices['instanceName'])) )
  3617. choices['reposerver'] = Array.from( new Set(reposervers.concat(choices['reposerver'])) )
  3618. // choices['upstream-remote'] = Array.from( new Set(remotes.concat(choices['upstream-remote'])) )
  3619. choices['instanceType'] = Array.from( new Set(instanceTypes.concat(choices['instanceType'])) )
  3620. return __interactive_prompts(selectedinstance, choices, promptsfilter)
  3621. }
  3622. var detection_state = {
  3623. localInstanceDetected : false
  3624. }
  3625. const https = require('https')
  3626. const http = require('http');
  3627. const { resolve } = require('path');
  3628. const { Console } = require('console');
  3629. const RESTAPI = (function(){
  3630. // Singleton
  3631. function RESTAPI(){}
  3632. // RESTAPI.create = RESTAPI; // Returns the one singe instance which is the class itself
  3633. // const options = {
  3634. // hostname: 'whatever.com',
  3635. // port: 443,
  3636. // path: '/todos',
  3637. // method: 'POST',
  3638. // headers: {
  3639. // 'Content-Type': 'application/json',
  3640. // 'Content-Length': data.length
  3641. // }
  3642. // }
  3643. RESTAPI.method = function(options, resolve, reject){
  3644. var __method = function() {
  3645. options.headers = options.headers || { 'Content-Type': 'application/json' }
  3646. if(options.payload) {
  3647. const data = new TextEncoder().encode( JSON.stringify(options.payload) )
  3648. options.headers = options.headers || {
  3649. 'Content-Type': 'application/json',
  3650. 'Content-Length': data.length
  3651. }
  3652. }
  3653. if(!options.authenticatepost) options.headers.Authorization = `token ${usertokens[options.username]}`
  3654. var acquirer = getHTTPorS(options)
  3655. const req = acquirer.request(options, res => {
  3656. if (res.statusCode < 200 || res.statusCode >= 300) {
  3657. return reject(new Error('statusCode=' + res.statusCode));
  3658. }
  3659. var body = [];
  3660. // res.setEncoding('utf8');
  3661. res.on('data', function(chunk) {
  3662. body.push(chunk);
  3663. });
  3664. res.on('end', function() {
  3665. try {
  3666. body = JSON.parse(Buffer.concat(body).toString());
  3667. } catch(e) {
  3668. reject(e);
  3669. }
  3670. resolve(body);
  3671. });
  3672. });
  3673. req.on('error', error => {
  3674. console.error(error)
  3675. reject(error)
  3676. })
  3677. if(options.payload) req.write(data)
  3678. req.end()
  3679. }
  3680. if(!options.authenticatepost && !usertokens[options.username]) {
  3681. RESTAPI.authenticate(options, function(tokenresp){
  3682. usertokens[options.username] = tokenresp.sha1
  3683. __method(options, resolve, reject)
  3684. },
  3685. function(err){ throw err}
  3686. )
  3687. }
  3688. else __method(options, resolve, reject)
  3689. }
  3690. RESTAPI.post = RESTAPI.method
  3691. var usertokens = {}
  3692. RESTAPI.authenticate = function(options, resolve, reject){
  3693. options.headers = options.headers || { 'Content-Type': 'application/json' }
  3694. if(!usertokens[options.username]) {
  3695. // Authenticate and acquire token.
  3696. // https://git.bbh/api/v1/users/<username>/tokens
  3697. // curl -XPOST -H "Content-Type: application/json" -k -d '{"name":"demo"}' -u demo:demo123 http://git.bbh/api/v1/users/demo/tokens
  3698. var _options = Object.assign({}, options)
  3699. // _options.username = 'demo'
  3700. // _options.password = 'demo123'
  3701. _options.method = 'POST'
  3702. _options.headers.Authorization = `Basic ${Buffer.from(`${_options.username}:${_options.password}`).toString('base64')}`
  3703. _options.path = `/api/v1/users/${_options.username}/tokens`
  3704. _options.authenticatepost = true
  3705. var postoptions = { name : _options.username }
  3706. delete _options.username
  3707. delete _options.password
  3708. _options.payload = postoptions
  3709. RESTAPI.post( _options, function(tokenresp){
  3710. // tokenresp = JSON.parse(tokenresp)
  3711. usertokens[options.username] = tokenresp.sha1
  3712. resolve(tokenresp)
  3713. },
  3714. function(err){ reject(err) }
  3715. )
  3716. }
  3717. else resolve(tokenresp.sha1)
  3718. }
  3719. RESTAPI.get = RESTAPI.post = RESTAPI.method
  3720. return RESTAPI
  3721. })();
  3722. var getHTTPorS = function(options){ return options.protocol.startsWith('https') ? https : http; }
  3723. const GITEA = (function(){
  3724. function GITEA(){}
  3725. GITEA.repository = {
  3726. fork( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  3727. // forkoptions = { owner : httpoptions.username, repo : {{reoptoFork}} }
  3728. // giteaoptions = {
  3729. // organization string
  3730. // --- organization name, if forking into an organization
  3731. // }
  3732. // http://try.gitea.io/api/v1/repos/{owner}/{repo}/forks
  3733. httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}/forks`
  3734. httpoptions.method = 'POST'
  3735. httpoptions.payload = giteaoptions;
  3736. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  3737. }
  3738. , updateattributes( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  3739. httpoptions.path = `/api/v1/repos/${cmdoptions.owner}/${cmdoptions.repo}`
  3740. httpoptions.method = 'PATCH'
  3741. httpoptions.payload = giteaoptions;
  3742. return RESTAPI.post(httpoptions, resolve || function(){}, reject || function(){} )
  3743. }
  3744. }
  3745. GITEA.user = {
  3746. getuser( httpoptions, cmdoptions, giteaoptions, resolve, reject ){
  3747. // ​/users​/{username} // Get a user
  3748. httpoptions.path = `/api/v1/users/${httpoptions.username}`
  3749. httpoptions.method = 'GET'
  3750. return RESTAPI.get(httpoptions, giteaoptions, resolve || function(){}, reject || function(){} )
  3751. }
  3752. }
  3753. return GITEA
  3754. })();
  3755. // Wrapper for Git shell operations. Some meta operations will map to a bunch of GIT commands.
  3756. const GIT = (function(){
  3757. function GIT(){}
  3758. Object.assign(GIT, {
  3759. 'switch user'(username){
  3760. var server = new URL(selectedinstance.reposerver);
  3761. return GITEA.user.getuser({ hostname : server.host, protocol : server.protocol
  3762. , username : selectedinstance.username, password : selectedinstance.password
  3763. }).then(()=>{
  3764. return nodeShellExec('git', ['config', '--replace-all', 'user.name', username],
  3765. {
  3766. inherit: true, shell: true,
  3767. env: process.env
  3768. , cwd: instanceroot + '/' + repo
  3769. , runas: processedArgs.runas
  3770. , title: `'git', ${['config', '--replace-all', 'user.name', username].join(' ')}`
  3771. })
  3772. }
  3773. )
  3774. .catch(e => {
  3775. console.error(e + 'Could not switch. Probably no such user.')
  3776. })
  3777. }
  3778. })
  3779. return GIT
  3780. })();
  3781. function createInstanceData(target, source) {
  3782. var sourceinstance = source || target;
  3783. console.dir(sourceinstance)
  3784. var args = {
  3785. remotebase : sourceinstance.reposerver + '/chess/'
  3786. , sourcerepo : sourceinstance.repo || 'chess-data'
  3787. , targetrepo : `${target.instanceName}-data-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  3788. }
  3789. if(sourceinstance.local) {
  3790. var options = {
  3791. inherit: true, shell: true,
  3792. env: process.env
  3793. , cwd : instanceroot
  3794. , runas: processedArgs.runas
  3795. }
  3796. var cmdseq = [
  3797. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  3798. ]
  3799. return any(cmdseq.map(getshelltask)).then(() => { return true })
  3800. }
  3801. else {
  3802. // http://try.gitea.io/api/v1/org/{org}/repos
  3803. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  3804. throw 'createInstanceData is possible only within the same repository server.'
  3805. }
  3806. var server = new URL(target.reposerver);
  3807. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  3808. , username : target.username, password : target.password
  3809. }
  3810. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  3811. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  3812. return GITEA.repository.updateattributes( {
  3813. hostname : server.host, protocol : server.protocol
  3814. , username : target.username, password : target.password
  3815. }
  3816. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  3817. , { name : `${args.targetrepo}`}
  3818. )
  3819. }
  3820. )
  3821. }
  3822. // GITEA.repository.updateattributes( {
  3823. // hostname : server.host, protocol : server.protocol
  3824. // , username : selectedinstance.username, password : selectedinstance.password
  3825. // }
  3826. // , { repo : `chess-config`, owner : selectedinstance.username }
  3827. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  3828. // )
  3829. // return selectedinstance
  3830. }
  3831. function createInstance(target, source) {
  3832. var sourceinstance = source || target;
  3833. console.dir(sourceinstance)
  3834. var args = {
  3835. remotebase : sourceinstance.reposerver + '/chess/'
  3836. , sourcerepo : sourceinstance.repo || 'chess-config'
  3837. , targetrepo : `${target.instanceName}-config-${target.instanceType}${target.nodeName ? ('-' + target.nodeName) : ''}`
  3838. }
  3839. if(sourceinstance.local) {
  3840. var options = {
  3841. inherit: true, shell: true,
  3842. env: process.env
  3843. , cwd : instanceroot
  3844. , runas: processedArgs.runas
  3845. }
  3846. var cmdseq = [
  3847. ['git', ['clone', `${args.remotebase}${args.sourcerepo}`, `${args.targetrepo}`], options]
  3848. ]
  3849. return any(cmdseq.map(getshelltask)).then(() => { return true })
  3850. }
  3851. else {
  3852. // http://try.gitea.io/api/v1/org/{org}/repos
  3853. if(source.reposerver !== target.reposerver && source.username !== target.username) {
  3854. throw 'createInstance is possible only within the same repository server.'
  3855. }
  3856. var server = new URL(target.reposerver);
  3857. return GITEA.repository.fork( { hostname : server.host, protocol : server.protocol
  3858. , username : target.username, password : target.password
  3859. }
  3860. // , { repo : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}`}
  3861. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }, {}, function( repository ){
  3862. return GITEA.repository.updateattributes( {
  3863. hostname : server.host, protocol : server.protocol
  3864. , username : target.username, password : target.password
  3865. }
  3866. , { repo : `${args.sourcerepo}`, owner : `${target.username}` }
  3867. , { name : `${args.targetrepo}`}
  3868. )
  3869. }
  3870. )
  3871. }
  3872. // GITEA.repository.updateattributes( {
  3873. // hostname : server.host, protocol : server.protocol
  3874. // , username : selectedinstance.username, password : selectedinstance.password
  3875. // }
  3876. // , { repo : `chess-config`, owner : selectedinstance.username }
  3877. // , { name : `${selectedinstance.instanceName}-config-${selectedinstance.instanceType}${selectedinstance.nodeName ? '-' + selectedinstance.nodeName : ''}`}
  3878. // )
  3879. // return selectedinstance
  3880. }
  3881. var skipprerequisites = false;
  3882. function initinstances(selected_overrides) {
  3883. var root = selected_overrides.root // We should always have this coz we are running at some place which is fixed by detectLocalInstances.
  3884. var instanceName = selected_overrides.instanceName
  3885. || clioverrides.instanceName
  3886. // || processedArgs._[1]
  3887. || chessinstances.current_run.instanceName
  3888. var node_env = selected_overrides.node_env
  3889. || clioverrides.node_env
  3890. // || processedArgs.node_env
  3891. || chessinstances.current_run.node_env
  3892. var reposerver = selected_overrides.reposerver
  3893. || clioverrides.reposerver
  3894. // || processedArgs.node_env
  3895. || chessinstances.current_run.reposerver
  3896. if(!instanceName) {
  3897. promptkeys['instanceName'] = instanceName = chessinstances.current_run.instanceName = promptkeys['instanceName'] || __default.instanceName;
  3898. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  3899. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  3900. }
  3901. if(!node_env) {
  3902. promptkeys['node_env'] = node_env = chessinstances.current_run.node_env = promptkeys['node_env'] || __default.node_env;
  3903. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  3904. }
  3905. if(!reposerver) {
  3906. promptkeys['reposerver'] = reposerver = chessinstances.current_run.reposerver = promptkeys['reposerver'] || __default.reposervers[0];
  3907. }
  3908. chessinstances[instanceName] = chessinstances[instanceName] || createLocalChessInstance( {
  3909. instanceName, node_env, root : selected_overrides.root, reposerver : selected_overrides.reposerver /* promptkeys['reposerver'] */ } );
  3910. chessinstances['current_run'] = { instanceName: instanceName, node_env, reposerver, root }
  3911. if(path.normalize(selected_overrides.root) !== path.normalize(chessinstances[instanceName][node_env].root)) {
  3912. 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
  3913. }
  3914. // Override sequence.
  3915. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  3916. // PB : TODO -- Undefined keys are overriding and deleting values. We should not allow that.
  3917. // This is ordinary utils.assign behavior. The key should not exist as undefined in the override.
  3918. // PB : TODO -- We now have options that can be passed into assign_core to control this behavior.
  3919. if(selected_overrides.node_env === undefined) delete selected_overrides.node_env
  3920. selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  3921. , __default
  3922. , chessinstances[instanceName][node_env]
  3923. , clioverrides
  3924. , selected_overrides
  3925. // , __interactive_prompts -- Cant just override. Also need selectedinstance to be ready...
  3926. );
  3927. // chessinstances[instanceName] = chessinstances[instanceName] || {}
  3928. // chessinstances[instanceName][node_env] = chessinstances[instanceName][node_env] || {}
  3929. // if(!selectedinstance.repos || selectedinstance.instanceName) {
  3930. // // Brand New.
  3931. // selectedinstance = Object.assign( __default, selectedinstance )
  3932. // }
  3933. if(selectedinstance?.repos && !selectedinstance?.repos[0]?.repo) {
  3934. console.warn('repo manifest has obsolete format. Attempting upgrade.')
  3935. selectedinstance.repos = selectedinstance.repos.map(function(repo){ return { repo } })
  3936. }
  3937. if(selectedinstance?.elevated && !selectedinstance?.elevated[0]?.repo) {
  3938. console.warn('elevated repo manifest has obsolete format. Attempting upgrade.')
  3939. selectedinstance.elevated = selectedinstance.elevated.map(function(repo){ return { repo } })
  3940. }
  3941. // Config from server always override merges into selection except for the current selection.
  3942. // PB : TODO -- utils.assign Array merges are non-distinct...
  3943. chessinstances[instanceName][node_env] = selectedinstance;
  3944. // chessinstances[selectedinstance.instanceName][selectedinstance.node_env] = selectedinstance;
  3945. cacheWriteInstanceConfig(chessinstances)
  3946. // PB : TODO -- We should probably write the new server config also...
  3947. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  3948. return chessinstances
  3949. }
  3950. var skipprereqs = {}
  3951. var maintask = () => {
  3952. // Default cmd to run !
  3953. processedArgs._[0] === processedArgs._[0] || 'pull';
  3954. // selectedinstance.reposerver = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available.
  3955. if(!noprerequisites[processedArgs._[0]]
  3956. && !skipprereqs[processedArgs._[0]]
  3957. ) {
  3958. return prerequisites.git.verifyAndInstall().then(()=>{
  3959. var e = { message : 'verifyAndInstall', success : true}
  3960. var inittasks = []
  3961. var commontask = () => { preworkerconfig(); return elxrworker(true) }
  3962. if(!detection_state.localInstanceDetected) {
  3963. var t1 = ()=>{ return createInstance(selectedinstance) };
  3964. t1.statuslog = statuslog
  3965. var specifictask = shell_verse.getNonElevatedTask(t1)
  3966. }
  3967. else {
  3968. var t2 = ()=>{ return acquireConfig(selectedinstance) };
  3969. t2.statuslog = statuslog
  3970. var specifictask = shell_verse.getNonElevatedTask(t2)
  3971. }
  3972. inittasks.push( specifictask().catch((err) => {
  3973. e = err;
  3974. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  3975. console.error(err)
  3976. }).then( commontask )
  3977. // .finally(()=>{
  3978. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  3979. // if(!e.success) fs.writeFileSync('run.done', 'error');
  3980. // // return process.exit()
  3981. // }))
  3982. )
  3983. return any(inittasks)
  3984. })
  3985. }
  3986. else {
  3987. console.log('cmd has no preqs or has been configured to skip preqs')
  3988. preworkerconfig()
  3989. return elxrworker()
  3990. }
  3991. }
  3992. function generateDependencies(){
  3993. // PB : TODO -- Keep only the last n runs...
  3994. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  3995. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
  3996. fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
  3997. // PB : TODO include and build from files... using rollup..
  3998. var downloadbatch =
  3999. `::**************************************************************************
  4000. :Download_ <url> <File>
  4001. Powershell.exe ^
  4002. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  4003. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  4004. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  4005. exit /b
  4006. ::**************************************************************************`
  4007. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch)
  4008. var windowselevate =
  4009. `
  4010. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  4011. <script language="vbscript">
  4012. document.title = "elxr control panel"
  4013. self.ResizeTo 200,600
  4014. Sub Window_Onload
  4015. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  4016. End Sub
  4017. Set objShell = CreateObject("WScript.Shell")
  4018. Set objENV = objShell.Environment("Process")
  4019. dim NODE_ENV
  4020. NODE_ENV = objENV("NODE_ENV")
  4021. </script>
  4022. <script language="javascript">
  4023. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  4024. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  4025. // alert(windowselevate.commandLine)
  4026. var args = windowselevate.commandLine.split('"').slice(3);
  4027. // alert(args)
  4028. var processedArgs = { _ : [] }
  4029. var namedArgs = [];
  4030. namedArgs.push('--wd=' + objENV('wd'))
  4031. // alert(namedArgs)
  4032. for(var item in args){
  4033. if(args[item].charAt(0) === '-'){
  4034. namedArgs.push(args[item])
  4035. var split = args[item].split('=');
  4036. processedArgs[split[0].slice(2)] = split[1] || true;
  4037. }
  4038. else processedArgs._.push(args[item]);
  4039. }
  4040. // args = args.forEach(function(item){ })
  4041. // alert('processedArgs._ : ' + processedArgs._);
  4042. // alert(processedArgs.runas);
  4043. // alert(objENV('wd'))
  4044. // PB : TODO -- Convert all the cli args back to string.
  4045. // __filename will sure we are launhed using the same entry point.
  4046. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' ${__filename.replace(/\\/g, '\\\\')} ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  4047. var shell = new ActiveXObject('shell.application');
  4048. // alert('launching node privilged. ' + processedArgs['nodepath'])
  4049. // shell.ShellExecute('cmd.exe', '/k where node', '', '', 10);
  4050. // shell.ShellExecute('cmd.exe', '/k notepad.exe', '', 'runas', 1);
  4051. // shell.ShellExecute('cmd.exe ', '/k node ', '', 'runas', 1);
  4052. // shell.ShellExecute('cmd.exe ', '/k node ' + cargs + '', '', 'runas', 1);
  4053. shell.ShellExecute('node', cargs, '', 'runas', 1);
  4054. // alert('/k node ' + cargs + '')
  4055. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  4056. var fso = new ActiveXObject('Scripting.FileSystemObject');
  4057. window.onload = function() {
  4058. document.body.style.backgroundColor = 'black';
  4059. document.body.style.fontFamily = 'arial';
  4060. var log = document.createElement('div');
  4061. log.innerHTML='Please Wait';
  4062. function l(msg){ log.innerHTML+= msg; };
  4063. log.style.color = 'blue';
  4064. log.style.width = '95%';
  4065. log.id = 'log';
  4066. document.body.appendChild(log);
  4067. l('<Br/>Current config : ')
  4068. l('<Br/>NODE_ENV = ' + NODE_ENV)
  4069. l('<Br/>cmd = ' + processedArgs._[0])
  4070. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  4071. l('<Br/><Br/>')
  4072. // alert(fso.GetAbsolutePathName("."))
  4073. var timer = function(){
  4074. l('.');
  4075. if(fso.FileExists("run.done")) {
  4076. fso.DeleteFile('run.done') // PB : TODO -- IPC through files is needed only for windows we need to do it per run...
  4077. close();
  4078. }
  4079. else window.setTimeout(timer, 1000);
  4080. };
  4081. window.setTimeout(timer, 3000);
  4082. };
  4083. </script>
  4084. </html>
  4085. `
  4086. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate)
  4087. }
  4088. var startElxr = function() {
  4089. const retaincount = 2
  4090. var min = runtimestamp;
  4091. var collect = []
  4092. if(reconfirmcmds[processedArgs.label || processedArgs._[0]]) {
  4093. reconfirm = getReconfirmAll()
  4094. }
  4095. return detectLocalInstances().then((detectedinstanceoptions)=>{
  4096. detectedinstanceoptions.splice(0,0, __default)
  4097. var cmdinstance = cmds[clioverrides.cmd]
  4098. var cmdprompts = cmdinstance.getPossiblePrompts()
  4099. selectedinstance.node_env ? selectedinstance.node_env : selectedinstance.node_env = clioverrides.node_env
  4100. // PB : TODO -- Most recent should be at the tip ! at index 0 so utils.reverseassign is required !!!
  4101. selectedinstance = __g.selectedinstance = utils.assign_core( { arraymergetype : utils.assign_core.DISTINCT_UNION }
  4102. , ...detectedinstanceoptions.slice(-2), promptkeys )
  4103. // promptkeys = utils.assign(promptkeys, clioverrides)
  4104. // startElxr requires instance // Independent cmds should have already been bypassed.
  4105. // if(cmdprompts.instanceName) {
  4106. // not an instanceless cmd.
  4107. console.dir(selectedinstance)
  4108. try {
  4109. chessinstances = acquirelocalinstances(selectedinstance);
  4110. findlocalinstances(chessinstances, detectedinstanceoptions)
  4111. initinstances(selectedinstance) // use the local instances for defaults if at all possible.
  4112. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  4113. var inst = initinstances(selectedinstance)
  4114. detection_state.localInstanceDetected = true;
  4115. return inst;
  4116. })
  4117. }
  4118. catch (e) {
  4119. // PB : TODO -- verbose mode warning.. console.warn(e) // Missing chessinstances is not an error...
  4120. var todo = any( getInteractionPoints(detectedinstanceoptions, promptkeys) ).then(()=>{
  4121. return initinstances(selectedinstance)
  4122. })
  4123. // if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  4124. // // Weve not been told what to do.
  4125. // todo = todo.then(() => { return acquireChoices(selectedinstance) })
  4126. // }
  4127. todo = todo.then(() => {
  4128. try {
  4129. chessinstances = acquirelocalinstances(selectedinstance)
  4130. findlocalinstances(chessinstances, detectedinstanceoptions)
  4131. detectedinstanceoptions.splice(0,0, __default)
  4132. initinstances(selectedinstance)
  4133. detection_state.localInstanceDetected = true;
  4134. }
  4135. catch (e) {
  4136. // console.error(e)
  4137. console.log('No local instances config found in current root = ' + selectedinstance.root);
  4138. console.log('A config will be createed with the instance and environment chosen...')
  4139. // return (async ()=>{return await __default.reposerver})().then(()=>{
  4140. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  4141. // return selectedinstance = Object.assign(__default, selectedinstance);
  4142. // })
  4143. detection_state.localInstanceDetected = false;
  4144. return selectedinstance
  4145. }
  4146. })
  4147. }
  4148. return todo.then( ()=>{
  4149. // PB : TODO -- Embed this in the build instead of inlining it.
  4150. // Also attepmt to load from ../chess-config/...
  4151. var __repo_manifest = (require(path.normalize(instanceroot + '/elxr/repo-manifest.js')))(
  4152. 'defaultmanifest' // name
  4153. , { utils, username : selectedinstance.username, instanceName : selectedinstance.instanceName
  4154. , node_env : selectedinstance.node_env, reposerver : 'https://git.bbh.org.in' } // options
  4155. )
  4156. __default = Object.assign(__default, __repo_manifest, {
  4157. // Common baseline repos for all chess instances.
  4158. repos : (()=> {
  4159. var __repos = [
  4160. { repo : 'ember-masonry-grid' /*, branch : master*/ } // Default need not be specified.
  4161. , { repo : 'bbhverse' }
  4162. , { repo : 'clientverse' }
  4163. , { repo : 'serververse' }
  4164. , { repo : 'elxr' }
  4165. , { repo : 'ember-searchable-select' }
  4166. , { repo : 'loopback-component-jsonapi' }
  4167. , { repo : 'loopback-jsonapi-model-serializer' }
  4168. , { repo : 'loopback-connector-mysql' }
  4169. , { repo : 'loopback-connector-ds' }
  4170. , { repo : 'ember-service-worker' }
  4171. , { repo : 'ember-service-worker-asset-cache' }
  4172. , { repo : 'ember-service-worker-cache-fallback' }
  4173. , { repo : 'ember-service-worker-index' }
  4174. , { repo : 'ember-sw-client-route' }
  4175. , { repo : 'global-this' }
  4176. ]
  4177. Array.prototype.push.apply( __repos, __repo_manifest.repos)
  4178. return __repos;
  4179. })()
  4180. // Requires elevation only in windows
  4181. , elevated : [ { repo : 'chess-server-lib', requiresElevation : true } ]
  4182. , exludeMergeRepos : { }
  4183. })
  4184. initinstances(selectedinstance)
  4185. return selectedinstance
  4186. })
  4187. // }
  4188. // else return Promise.resolve(true)
  4189. })
  4190. .then(()=>{
  4191. runconfig = { NODE_ENV: selectedinstance.node_env }
  4192. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  4193. generateDependencies();
  4194. if(noprerequisites[processedArgs._[0]]
  4195. || skipprereqs[processedArgs._[0]]
  4196. ) {
  4197. return elxrworker()
  4198. }
  4199. var neTask = ()=>{
  4200. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/${__ALIAS__STAMP__}`)
  4201. // collect garbage
  4202. return dirs( (dir)=>{
  4203. var matches = /run-(.*)/gm.exec(dir.name)
  4204. if(matches) {
  4205. if(+(matches[1]) < min) {
  4206. min = matches[1]
  4207. collect.splice( 0, 0, matches[1] )
  4208. }
  4209. else collect.push(matches[1])
  4210. }
  4211. return Promise.resolve(collect);
  4212. }, `${selectedinstance.root}/.elxr` )
  4213. .then(()=>{
  4214. // delete garbage
  4215. if(collect.length > retaincount) {
  4216. var asyncs = [];
  4217. while((collect.length - asyncs.length) > retaincount) {
  4218. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  4219. }
  4220. return Promise.all(asyncs)
  4221. }
  4222. else return true
  4223. })
  4224. .catch(e => {
  4225. console.error
  4226. })
  4227. }
  4228. neTask.statuslog = statuslog
  4229. shell_verse.getNonElevatedTask( neTask )()
  4230. var commonTask = ()=>{
  4231. verifyAndInstallPrerequisites.statuslog = statuslog
  4232. if((!skipprerequisites || processedArgs.forceprereqs)) mainTasks.push(verifyAndInstallPrerequisites);
  4233. mainTasks.push(maintask)
  4234. return any(mainTasks);
  4235. }
  4236. return commonTask()
  4237. })
  4238. }
  4239. var __default = {}; // PB : TODO -- Use initialized instance instead of default everywhere.
  4240. // PB : TODO -- In windows if we are run from an elevated shell we never move forward and simply exits !?.
  4241. // -- Currently workaround in windows is to always run from a non-elevated shell.
  4242. shell_verse.acquireElevationState().then((elevationstate) => {
  4243. return detectInstanceRoot.then(()=>{
  4244. var cmdobj = cmds[clioverrides.cmd]
  4245. return Promise.all((cmdobj.requires || []).map( (r) => utils.promisify(null, r) ) ).then(()=>{
  4246. if(cmdobj.independentcmd) {
  4247. if(cmdobj.requiresElevation) {
  4248. return cmdobj.cmdFn()
  4249. }
  4250. else return cmdobj.cmdFn()
  4251. }
  4252. else return startElxr()
  4253. })
  4254. .catch(e => {
  4255. if(typeof e === 'symbol') console.log('error : ' + 'symbol')
  4256. else console.log('error : ' + e)
  4257. })
  4258. })
  4259. })
  4260. // .then( () => {
  4261. // console.log(process._getActiveHandles());
  4262. // console.log(process._getActiveRequests());
  4263. // })
  4264. // detect if alread installed -> Take no action.
  4265. // download if no installer avalable -> next()
  4266. // install
  4267. function chackandinstall(items) {
  4268. var tasks = []
  4269. items.forEach(item => {
  4270. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  4271. })
  4272. return Promise.all(tasks).then(existances => {
  4273. existances.forEach((exists, i) => {
  4274. if (!exists) {
  4275. return downloadandinstall([items[i]])
  4276. }
  4277. })
  4278. })
  4279. }
  4280. function downloadandinstall(items) {
  4281. var tasks = []
  4282. items.forEach(item => {
  4283. tasks.push(getTaskDownload(item))
  4284. })
  4285. return Promise.all(tasks)
  4286. }
  4287. // Sample instances config.
  4288. // var instances = {
  4289. // "elixir": {
  4290. // "production": {
  4291. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  4292. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  4293. // , "exludeMergeRepos": {
  4294. // "elixir-config-development": true, "elixir-config-test": true
  4295. // , "elixir-config-production": true, "elixir-data": true
  4296. // }
  4297. // , "instanceName": "elixir", "node_env": "production"
  4298. // }
  4299. // },
  4300. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  4301. // }
  4302. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...