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

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