Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

index.js 163KB

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