Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

index.js 177KB

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