555
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

index.js 151KB

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