555
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 118KB

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