Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

index.js 117KB

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