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

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