555
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

elxr_linux.js 148KB

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