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.

elxr.js 145KB

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