選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

index.js 76KB

3年前
3年前
3年前
3年前
3年前
5年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
5年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
5年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
3年前
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069
  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 BUILD_VERSION = '[VI]Version: {version} - built on {date}[/VI]';
  12. const runtimestamp = (new Date()).getTime();
  13. function getVersion() { return BUILD_VERSION; }
  14. console.log(getVersion())
  15. // 'use strict';
  16. // PB : TODO -- make sure folder context is proper coz we can now run elxr from anywhere.
  17. // PB : TODO --
  18. // runas bypass non elevated tasks when we request privelege
  19. // runas message is always error needs to be fixed.
  20. // runas wait needs to be parallelized.
  21. // suppress elevation check error messages
  22. // support runas lauched directly from shell.
  23. // pass in environment in hta to shellexecute.
  24. const { existsSync } = require('fs');
  25. const fs = require('fs')
  26. const cliargs = utils.cliargs;
  27. const processedArgs = cliargs(process.argv.slice(2));
  28. console.dir(processedArgs)
  29. var globSync = require('glob').sync;
  30. var ENV = Object.assign({}, process.env); // Shallow clone it.
  31. const { readdir } = require("fs").promises
  32. // Directory shallow walk and do perform on each dir.
  33. const dirs = async (perform, path) => {
  34. for (const dir of await readdir(path || process.cwd(), { withFileTypes: true })) {
  35. if (dir.isDirectory()) perform(dir)
  36. }
  37. }
  38. var getShellTask = (command, args, options) => {
  39. options = options || {}
  40. return () => {
  41. var p = nodeShellExec.apply(null, [command, args, Object.assign({
  42. inherit: true, shell: true, env: ENV, title: `${command} ${args}`
  43. }, options)
  44. ])
  45. if (options.ignorefailures) {
  46. return p.catch(e => {
  47. // Ignore. Not a major error.
  48. })
  49. }
  50. else return p;
  51. }
  52. }
  53. var callsheltask = (args) => { return () => { return nodeShellExec.apply(null, args) } }
  54. var getTaskCheckExists = (command, options) => {
  55. options = options || {}
  56. return () => {
  57. var p = nodeShellExec.apply(null, ['where', [command]])
  58. if (options.ignorefailures) {
  59. return p.then(() => { return true }).catch(e => { // Ignore. Not a major error.
  60. return false;
  61. })
  62. }
  63. else return p.then(() => { return true });
  64. }
  65. }
  66. var getTaskWithElevation = function(tasdef){
  67. return ()=>{
  68. if (__isElevated) {
  69. return tasdef.elevatedpulltasks();
  70. }
  71. else {
  72. // PB : TODO -- Rename op['runas'] to 'elevate'
  73. return op['runas']().then(() => { return true; })
  74. .catch((e) => {
  75. console.error(e)
  76. })
  77. .finally(() => {
  78. if (!processedArgs.runas) { return tasdef.regularpulltasks(); }
  79. })
  80. }
  81. }
  82. }
  83. var getTaskWithoutElevation = function(tasdef){
  84. return ()=>{
  85. if(!processedArgs.runas) { return tasdef.regularpulltasks(); }
  86. else Promise.resolve(true)
  87. }
  88. }
  89. var gitops = {
  90. getdiscoverbranchcmd : function(repo){
  91. var parameters = ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  92. var cmd = [gitbash
  93. , ['-c', 'branch=`git rev-parse --abbrev-ref HEAD`;for i in `git remote`; do git pull $i $branch; done;']
  94. , { cwd: instanceroot + '/' + repo, title: 'pull all origins for ' + repo + ' ' + parameters.join(' ') }]
  95. return cmd
  96. }
  97. }
  98. var getPullCmd = (repo, branch) => {
  99. // console.log(useGitPull)var getPullCmd = (repo, branch) => {
  100. // console.log(useGitPull)
  101. if(branch) {
  102. var parameters = ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  103. var pullCmd = [ gitbash
  104. , ['-c', 'for i in `git remote`; do git pull $i ' + branch + '; done;']
  105. , { cwd: instanceroot + '/' + repo, title : 'pull all origins for ' + branch + ' ' + repo + ' ' + parameters.join(' ') }]
  106. }
  107. else {
  108. console.warn('No branch was specified detecting from working client.')
  109. var pullCmd = gitops.getdiscoverbranchcmd(repo)
  110. }
  111. // var pullCmd = ['pullall', [], { cwd : repo }]
  112. if (useGitPull) pullCmd = ['git', ['pull'], {
  113. inherit: true, shell: true,
  114. cwd: instanceroot + '/' + repo
  115. // , env: process.env
  116. , runas: processedArgs.runas
  117. , title: `git pull ${repo}`
  118. }]
  119. return pullCmd
  120. }
  121. var performPull = (repo, branch) => {
  122. // PB : TODO -- Handle no branch passed in case.
  123. // if(!branch) { throw 'No branch specified' }
  124. if (existsSync(instanceroot + '/' + repo)) {
  125. var branchprint = branch ? ' branch :' + branch : '';
  126. console.log('pulling ' + instanceroot + '/' + repo + branchprint )
  127. return nodeShellExec.apply(null, getPullCmd(repo, branch)).then(() => {
  128. if (__isElevated) {
  129. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  130. }
  131. else statuslog.statuslog(null, repo)
  132. return true;
  133. })
  134. .catch((e) => {
  135. e.repo = repo;
  136. if (__isElevated) {
  137. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  138. }
  139. else statuslog.statuslog(e); console.error(e)
  140. })
  141. }
  142. else {
  143. console.log('cloning ' + repo)
  144. // PB : TODO -- detect if a clonable repo exists in currentGitAuthUser
  145. return nodeShellExec('git', ['clone', '-c', 'core.symlinks=true', selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'],
  146. {
  147. inherit: true, shell: true,
  148. env: process.env
  149. , cwd : instanceroot
  150. , runas: processedArgs.runas
  151. }).catch((e) => {
  152. throw e;
  153. }).then(() => {
  154. return nodeShellExec('git', ['config', '--replace-all', 'core.symlinks', true],
  155. {
  156. inherit: true, shell: true,
  157. env: process.env
  158. , cwd: instanceroot + '/' + repo
  159. , runas: processedArgs.runas
  160. , title: `git core.symlinks --replace-all true for ${selectedinstance.reposerver + `/${defaultRepoOwner}/` + repo + '.git'}`
  161. })
  162. .then(() => {
  163. if (__isElevated) {
  164. fs.writeFileSync('run.log', ', ' + JSON.stringify({ repo, success: true }), { 'flag': 'a+' })
  165. }
  166. else statuslog.statuslog(null, repo)
  167. })
  168. .catch((e) => {
  169. e.repo = repo;
  170. if (__isElevated) {
  171. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  172. }
  173. else statuslog.statuslog(e);
  174. })
  175. })
  176. .catch(e => {
  177. e.repo = repo;
  178. if (__isElevated) {
  179. fs.writeFileSync('run.log', ', ' + JSON.stringify(e), { 'flag': 'a+' })
  180. }
  181. else statuslog.statuslog(e);
  182. })
  183. }
  184. }
  185. // PB : TODO -- If we are run from an elevated shell it never moves forward and simply exits.
  186. // -- Currently workaround is to always run from a non-elevated shell.
  187. var __isElevated = null; // We assume non-Elevated until someone evaluates and sets this variable.
  188. var acquireElevationState = () => {
  189. if (__isElevated === null) {
  190. return nodeShellExec("fsutil", ["dirty", "query", "C:"], {
  191. inherit: true
  192. // , shell: true
  193. , stdio: 'ignore'
  194. , env: process.env
  195. , title: `check privileged execution mode using "fsutil dirty query C:"`
  196. }).then((exitcode) => {
  197. console.log('Elevated')
  198. __isElevated = true;
  199. return true;
  200. }).catch(() => {
  201. __isElevated = false;
  202. console.log('Not Elevated');
  203. return false;
  204. });
  205. }
  206. else return Promise.resolve(__isElevated);
  207. }
  208. var repomanifest = null;
  209. var currentGitAuthUser; // nodeShellExec('git', ['config', 'user.email']) ... PB : TODO-- get the current gittea username
  210. var defaultRepoOwner = 'chess';
  211. var elevatedRunasRepos = null
  212. var gitRepos = null
  213. // grep -qxF 'alias elxr="node elxr/index.js"' ~/.bash_profile || echo 'alias elxr="node elxr/index.js"' >> ~/.bash_profile
  214. // nodeShellExec('echo', ['elxr'], { inherit : true}) //, {stdio: "inherit"}
  215. var dbForLabel = function (label) {
  216. var dbsForLabel = {
  217. devmysql: 'mysql'
  218. , development: 'mssql'
  219. , production: 'mssql'
  220. }
  221. return dbsForLabel[label] || 'mysql'
  222. }
  223. // SAM : TODO Use nodeshellexec where to detect git installation dir
  224. var gitbash = "C:\\Program Files\\Git\\bin\\sh.exe"
  225. // var gitbash = "G:\\Installed\\Git\\bin\\sh.exe"
  226. // Relevant git repos
  227. // var repomanifest = require('../'+repomanifest.instanceName+'-config-'+ nodeenv +'/repo-manifest')()
  228. var exludeMergeRepos = [];
  229. var useGitPull = processedArgs.useGitPull || false;
  230. var configPromise = null
  231. // elxr cli operations
  232. var op = {
  233. 'h': () => { console.log(elxr.help()); return '-h' }
  234. , 'clean' : () => {
  235. // delete all node_module folders and links.
  236. var tasklist = [];
  237. dirs( (repodir)=> tasklist.push(getShellTask('rm',['-rf', 'node_modules'], { cwd : instanceroot + '/' + repodir.name })()), instanceroot )
  238. return Promise.all(tasklist)
  239. }
  240. , 'undefined': () => { return op.h(); }
  241. , 'reset': () => {
  242. // Reset NPM packages semver so major versions can be updated.
  243. const fs = require('fs')
  244. const wipeDependencies = (__package) => {
  245. const file = fs.readFileSync(__package + '/package.json')
  246. const content = JSON.parse(file)
  247. for (var devDep in content.devDependencies) {
  248. if (content.devDependencies[devDep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  249. content.devDependencies[devDep] = '*';
  250. }
  251. }
  252. for (var dep in content.dependencies) {
  253. if (content.dependencies[dep].match(/\W+\d+.\d+.\d+-?((alpha|beta|rc)?.\d+)?/g)) {
  254. content.dependencies[dep] = '*';
  255. }
  256. }
  257. fs.writeFileSync(__package + '/package.json', JSON.stringify(content))
  258. }
  259. var repos = ['client'];
  260. // repos = gitRepos;
  261. repos.forEach(wipeDependencies)
  262. // if (require.main === module) {
  263. // } else {
  264. // module.exports = wipeDependencies
  265. // }
  266. }
  267. , 'upgrade': () => {
  268. console.log('upgrade.......')
  269. var tasks = [
  270. () => {
  271. var p = nodeShellExec('npm', ['i', '-g', 'npm-upgrade'], {
  272. inherit: true, shell: true
  273. , env: process.env
  274. }).catch((e) => { console.error(e) })
  275. p.position = 1;
  276. console.log('One')
  277. return p;
  278. }
  279. , () => {
  280. var p = nodeShellExec('npm', ['cache', 'clean', '-f'], {
  281. inherit: true, shell: true
  282. , env: process.env
  283. }).catch((e) => { console.error(e) })
  284. p.position = 2;
  285. console.log('Two')
  286. return p;
  287. }
  288. , () => {
  289. var p = nodeShellExec('npm', ['install', '-g', 'n'], {
  290. inherit: true, shell: true
  291. , env: process.env
  292. }).catch((e) => { console.error(e) })
  293. p.position = 3;
  294. console.log('Three')
  295. return p;
  296. }
  297. , () => {
  298. var p = nodeShellExec('n', ['latest'], {
  299. inherit: true, shell: true
  300. , env: process.env
  301. }).catch((e) => { console.error(e) })
  302. p.position = 4;
  303. console.log('Four')
  304. return p;
  305. }
  306. ]
  307. any(tasks)
  308. console.log('.......done')
  309. console.log('Running exlr upgrade in : ' + path.dirname(__dirname))
  310. console.log('Currently only upgrades ember : ' + path.dirname(__dirname));
  311. console.info('Uninstalling existing ember globally');
  312. var step1 = nodeShellExec('cmd', ['/c', 'npm', 'uninstall', '-g', 'ember-cli'], {
  313. stdio: ['pipe', process.stdout, process.stderr],
  314. inherit: true,
  315. shell: true,
  316. cwd: path.dirname(__dirname),
  317. env: env
  318. })
  319. step1.on('close', () => {
  320. console.info('Installing ember globally');
  321. var step2 = nodeShellExec('cmd', ['/c', 'npm', 'install', '-g', 'ember-cli'], {
  322. stdio: ['pipe', process.stdout, process.stderr],
  323. inherit: true,
  324. shell: true,
  325. cwd: path.dirname(__dirname),
  326. env: env
  327. })
  328. step2.on('close', () => {
  329. nodeShellExec('cmd', ['/c', 'ember', '--version'], {
  330. stdio: ['pipe', process.stdout, process.stderr],
  331. inherit: true,
  332. shell: true,
  333. cwd: path.dirname(__dirname),
  334. env: env
  335. })
  336. })
  337. })
  338. }
  339. , 'runas': () => {
  340. console.log('Testing Elevation')
  341. if (__isElevated) {
  342. try {
  343. op[processedArgs.label || processedArgs._[0] || 'h']()
  344. }
  345. catch (e) {
  346. console.error('Error Invalid command : ' + e)
  347. fs.writeFileSync('run.done', 'error')
  348. }
  349. finally {
  350. }
  351. }
  352. else {
  353. console.log('Requesting Elevated Privileges');
  354. // Wait for the runas to complete before we read it.
  355. try {
  356. fs.unlinkSync('run.done')
  357. fs.unlinkSync('run.log')
  358. }
  359. catch (e) { } //Ignore
  360. // Find node path to send to hta.
  361. return nodeShellExec('where', ['node']).then(r => {
  362. var namedArgs = [];
  363. console.log('result : ' + JSON.stringify(r))
  364. Object.keys(processedArgs).forEach((v) => { v != '_' ? namedArgs.push('--' + v + '=' + processedArgs[v]) : null; })
  365. // PB : TODO -- Convert all the cli args back to string.
  366. var args = [`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`].concat(processedArgs._).concat(namedArgs.join(' ')); args.push('--runas=self');
  367. args.push('--nodepath=' + r[r.length - 1])
  368. if (!processedArgs.node_env) args.push('--node_env=' + ENV.NODE_ENV)
  369. if (processedArgs.debug) args.push('--debug=true') // Enable to debug elevated..
  370. return nodeShellExec('MSHTA', [`"${args.join('" "')}"`]
  371. , {
  372. inherit: true
  373. , shell: true
  374. , env: ENV
  375. , runas: 'self'
  376. , title: `runas`
  377. }
  378. ).then(() => {
  379. // runas returned.
  380. try {
  381. // PB : TODO -- Log is comma prefixed. Needs to be proper JSON.
  382. var runaslog = JSON.parse('[ { "success" : true, "result" : "started"}' + fs.readFileSync('run.log', { flags: 'a+' }) + ']');
  383. runaslog.forEach((logEntry) => {
  384. statuslog.statuslog(logEntry.success ? null : logEntry, logEntry)
  385. logEntry.success ? (console.log(['success :' + logEntry.result]), console.log((logEntry.messages || []).join(' '))) : (console.error(['error :' + logEntry.result]), console.error((logEntry.messages || []).join(' ')))
  386. })
  387. }
  388. catch (e) {
  389. // We must have a runas log
  390. statuslog.statuslog(e)
  391. console.error('Run log error probably was not created by runas : ' + e)
  392. }
  393. })
  394. .catch(err => console.error('Elevation failed : ' + err));
  395. })
  396. }
  397. }
  398. , 'push': () => {
  399. if (!processedArgs._[1]) { console.error('push all not supported. Specify repo name'); return }
  400. // init remote bare from local
  401. // pushandinitremotebare
  402. // https://www.jeffgeerling.com/blogs/jeff-geerling/push-your-git-repositories
  403. // connect to repo server -- net use 172.16.0.27
  404. // cd 172.16.0.27/repos/
  405. // mkdir repo.git
  406. // cd repo.git
  407. // git init --bare
  408. // cd localrepo
  409. // git remote rename origin githubclone
  410. // git remote add origin //172.16.0.27/repos/repo.git
  411. // git push origin master
  412. var repo = processedArgs._[1];
  413. var sequentialTaskShellCommands = [];
  414. if (!existsSync(`Z:/${repo}.git`)) {
  415. sequentialTaskShellCommands = [
  416. // ['net', ['use', 'Z:', selectedinstance.reposerver.replace('/','\\')], {
  417. // inherit : true, shell: true
  418. // , env: process.env
  419. // }]
  420. ['pwd', { cwd: 'Z:', inherit: true }]
  421. , ['mkdir', [`${repo}.git`], {
  422. cwd: `Z:`
  423. , inherit: true, shell: true
  424. , env: process.env
  425. }]
  426. , ['pwd', { cwd: `Z:/${repo}.git`, inherit: true }]
  427. , ['git', ['init', '--bare'], {
  428. cwd: `Z:/${repo}.git`
  429. , inherit: true, shell: true
  430. , env: process.env
  431. }]
  432. // PB : TODO -- Do this conditionally only...
  433. , ['git', ['remote', 'rename', 'origin', 'githubclone'], { cwd: `${instanceroot + '/' + repo}` }, (err) => {
  434. console.log('Ignoring origin rename error : ' + err); return true; //return true to continue.
  435. }] // PB ; Todo -- new repositories created locally will not have origin. Handle this failure.
  436. , ['git', ['remote', 'add', 'origin', `${selectedinstance.reposerver}/${repo}.git`], { cwd: `${instanceroot + '/' + repo}` }]
  437. // PB : TODO -- If threre is a gitbubclone origin
  438. // Set the master to pull from the local repo.
  439. ]
  440. if (!existsSync(`Z:`)) {
  441. sequentialTaskShellCommands.splice(0, 0, ['net', ['use', 'Z:', selectedinstance.reposerver.replace(/\//gm, '\\')], {
  442. inherit: true, shell: true
  443. , env: process.env
  444. }])
  445. console.warn('Adding network drive z: for repo server. ' + sequentialTaskShellCommands[0])
  446. // throw 'done'
  447. }
  448. }
  449. sequentialTaskShellCommands.push(['git', ['push', 'origin', 'master'], { cwd: `${instanceroot + '/' + repo}` }])
  450. // console.dir(sequentialTaskShellCommands);
  451. var tasks = [];
  452. sequentialTaskShellCommands.forEach(shellcmd => {
  453. // console.log(shellcmd)
  454. tasks.push(() => {
  455. var p = nodeShellExec.apply(null, shellcmd.slice(0, 3)).catch((e) => { if (shellcmd[3]) { return shellcmd[3]() } else { console.error(e); } })
  456. return p;
  457. })
  458. })
  459. any(tasks);
  460. }
  461. , 'is-git-repo': (dir) => {
  462. return nodeShellExec('git', ['-C', dir.name, 'rev-parse'], { stdio: 'ignore' })
  463. }
  464. , 'set-url': (remotename, url) => {
  465. var pushable = processedArgs.pushable || false;
  466. remotename = remotename || processedArgs._[1]
  467. url = url || processedArgs._[2]
  468. var serial_perform_git_seturl = (repo) => {
  469. var options = { cwd: instanceroot + '/' + repo }
  470. // console.log(repo)
  471. if (pushable) {
  472. return [
  473. ['git', ['remote', 'set-url', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  474. ]
  475. }
  476. else {
  477. console.error('not supported for non-pushable')
  478. }
  479. }
  480. var perform_git_seturl = (dir) => {
  481. op['is-git-repo'](dir).then((code) => {
  482. any(serial_perform_git_seturl(dir.name).map(x))
  483. }).catch((e) => {
  484. // console.log('Failed : ' + dir.name)
  485. })
  486. }
  487. dirs(perform_git_seturl)
  488. }
  489. , 'add': (remotename, url, branch) => {
  490. var pushable = processedArgs.pushable || false;
  491. remotename = remotename || processedArgs._[1]
  492. url = url || processedArgs._[2]
  493. branch = branch || processedArgs._[3]
  494. var serial_perform_git_add = (repo) => {
  495. var options = { cwd: instanceroot + '/' + repo }
  496. // console.log(repo)
  497. if (pushable) {
  498. return [
  499. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  500. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  501. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  502. ]
  503. }
  504. else {
  505. return [
  506. ['git', ['remote', 'add', remotename, url + '/' + repo], { cwd: instanceroot + '/' + repo }]
  507. , ['git', ['remote', `set-url`, '--push', remotename, 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  508. , ['git', ['pull', remotename, branch], { cwd: instanceroot + '/' + repo }]
  509. , ['git', ['branch', `--set-upstream-to=${remotename}/${branch}`, branch], { cwd: instanceroot + '/' + repo }]
  510. ]
  511. }
  512. }
  513. var x = (args) => {
  514. return () => {
  515. // console.log(args)
  516. return nodeShellExec.apply(null, args)
  517. }
  518. // return Promise.resolve(true)
  519. }
  520. var perform_git_add = (dir) => {
  521. op['is-git-repo'](dir).then((code) => {
  522. // console.log(code)
  523. if (code) {
  524. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  525. console.log('skipped : ' + dir.name + ', reason : A remote with same name already exists.')
  526. })
  527. .catch((e) => {
  528. any(serial_perform_git_add(dir.name).map(x))
  529. })
  530. }
  531. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  532. }).catch((e) => {
  533. // console.log('Failed : ' + dir.name)
  534. })
  535. }
  536. const { readdir } = require("fs").promises
  537. dirs(perform_git_add)
  538. }
  539. , 'remove': (remotename) => {
  540. remotename = remotename || processedArgs._[1]
  541. var serial_perform_git_remove = (repo) => {
  542. var options = { cwd: instanceroot + '/' + repo }
  543. // console.log(repo)
  544. return [
  545. ['git', ['remote', 'remove', remotename], { cwd: instanceroot + '/' + repo }]
  546. ]
  547. }
  548. var x = (args) => {
  549. return () => {
  550. // console.log(args)
  551. return nodeShellExec.apply(null, args)
  552. }
  553. // return Promise.resolve(true)
  554. }
  555. var perform_git_remove = (dir) => {
  556. op['is-git-repo'](dir).then((code) => {
  557. // console.log(code)
  558. // if (code) {
  559. nodeShellExec('git', ['remote', 'get-url', remotename], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  560. any(serial_perform_git_remove(dir.name).map(x))
  561. })
  562. .catch((e) => {
  563. console.log('skipped : ' + dir.name + ', reason : No remote named origin')
  564. })
  565. // }
  566. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  567. }).catch((e) => {
  568. console.log('Failed : ' + dir.name)
  569. })
  570. }
  571. const { readdir } = require("fs").promises
  572. dirs(perform_git_remove)
  573. }
  574. , 'init-gitea': (user) => {
  575. user = user || processedArgs._[1]
  576. if (!user) throw 'User name required'
  577. var serial_perform_init_gitea = (repo) => {
  578. var options = { cwd: instanceroot + '/' + repo }
  579. // console.log(repo)
  580. return [
  581. ['git', ['remote', 'add', 'chess', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  582. , ['git', ['remote', 'set-url', '--push', 'chess', 'no-pushing'], { cwd: instanceroot + '/' + repo }]
  583. , ['git', ['remote', 'set-url', 'origin', `${selectedinstance.reposerver}/${user}/${repo}.git`], { cwd: instanceroot + '/' + repo }]
  584. ]
  585. }
  586. var x = (args) => {
  587. return () => {
  588. // console.log(args)
  589. return nodeShellExec.apply(null, args)
  590. }
  591. // return Promise.resolve(true)
  592. }
  593. var perform_init_gitea = (dir) => {
  594. op['is-git-repo'](dir).then((code) => {
  595. // console.log(code)
  596. if (code) {
  597. nodeShellExec('git', ['remote', 'get-url', 'chess'], { cwd: dir.name, stdio: 'ignore' }).then(() => {
  598. console.log('skipped : ' + dir.name + ', reason : Already has remote chess ')
  599. })
  600. .catch((e) => {
  601. any(serial_perform_init_gitea(dir.name).map(x))
  602. })
  603. }
  604. // else console.log('Skipped : Not a Git Repo : ' + dir.name)
  605. }).catch((e) => {
  606. // console.log('Failed : ' + dir.name)
  607. })
  608. }
  609. const { readdir } = require("fs").promises
  610. dirs(perform_init_gitea)
  611. }
  612. , 'syncmaster': (label) => {
  613. // Usage :
  614. // elxr pull -- Defaults to run config
  615. var env = Object.assign({}, process.env); // Shallow clone it.
  616. // console.dir(env)
  617. console.log('Running exlr pull : ' + path.dirname(__dirname))
  618. if (!processedArgs.runas) gitRepos.map((def) => performPull(def.repo, def.branch || 'master'))
  619. if (__isElevated) {
  620. return any(elevatedRunasRepos.map((def) => performPull(def.repo, def.branch || 'master'))).then(() => {
  621. fs.writeFileSync('run.done', 'success')
  622. }).catch(() => {
  623. fs.writeFileSync('run.done', 'error')
  624. })
  625. }
  626. else return op['runas']()
  627. }
  628. , 'pull' : (label) => {
  629. // Usage :
  630. // elxr pull -- Defaults to run config
  631. return elxr.getpulltask()()
  632. }
  633. , 'isInstalled': () => {
  634. return nodeShellExec('where', [processedArgs._[1]], { inherit: true }).then(() => {
  635. console.log(processedArgs._[1] + ' exists.')
  636. return true;
  637. });
  638. }
  639. , 'i' : () => {
  640. var tasks = []
  641. // tasks.push(op['pull']);
  642. tasks.push(getShellTask.apply(null, ['rm', [instanceroot + '/run.js'], { ignorefailures: true }]))
  643. tasks.push(op['use'])
  644. if (!__isElevated) {
  645. tasks.push(op['npmi'])
  646. }
  647. // var tasksdefs = [
  648. // ['elxr', ['pull']]
  649. // , ['elxr', ['use', 'elixir']]
  650. // , ['elxr', ['npmi']]
  651. // ]
  652. // tasksdefs.forEach(tasksdef=>{
  653. // tasks.push( ()=> nodeShellExec.apply(null, tasksdef) )
  654. // })
  655. return any(tasks);
  656. }
  657. , 'npmi': () => {
  658. var tasks = [];
  659. // Build fails without babel...
  660. tasks.push(getShellTask(
  661. 'npm',[ 'i', '-g', 'babel-cli' ]
  662. ) )
  663. var npmbuildrepos = ['loopback-jsonapi-model-serializer']
  664. npmbuildrepos = []
  665. npmbuildrepos.forEach(repo => {
  666. tasks.push(() => {
  667. return nodeShellExec('npm', ['i --force'], {
  668. inherit: true, shell: true
  669. , cwd: instanceroot + '/' + repo
  670. , env: process.env
  671. , title: `npm i for ${repo}`
  672. }).catch((e) => {
  673. console.error('Ignoring Benign Error'); console.error(e);
  674. }).then(() => {
  675. console.log(`--npm run build for ${repo}--------------------`)
  676. return nodeShellExec('npm', ['run build'], {
  677. inherit: true, shell: true
  678. , cwd: instanceroot + '/' + repo
  679. , env: process.env
  680. , title: `npm run build for ${repo}`
  681. }).then(Tasq.then).catch(Tasq.catch)
  682. })
  683. })
  684. })
  685. any(tasks).then(() => {
  686. gitRepos.push('client/server');
  687. gitRepos = gitRepos.concat(elevatedRunasRepos);
  688. // gitRepos = [
  689. // // 'bbhverse', 'serververse', 'elixir-server',
  690. // // 'clientverse',
  691. // 'client'
  692. // ];
  693. var rmtasks = []
  694. var repotasks = []
  695. var env = Object.assign({}, process.env)
  696. delete env.NODE_ENV
  697. gitRepos.forEach(repodef => {
  698. rmtasks.push(
  699. // () => {
  700. // console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  701. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  702. nodeShellExec('rm', ['package-lock.json'], {
  703. inherit: true, shell: true
  704. , cwd: instanceroot + '/' + repodef.repo
  705. , env: process.env
  706. , title: `rm 'package-lock.json' for ${repodef.repo}`
  707. })
  708. .then(()=>{
  709. console.log(`--rm package-lock.json for ${repodef.repo}--------------------`)
  710. }).catch((e) => { console.error(e) })
  711. // }
  712. )
  713. if (npmbuildrepos.indexOf(repodef.repo) < 0) {
  714. repotasks.push(
  715. () => {
  716. console.log(`--npm i for ${repodef.repo}--------------------`)
  717. var p = nodeShellExec('npm', ['i', '--force'], {
  718. inherit: true, shell: true
  719. , cwd: instanceroot + '/' + repodef.repo
  720. , env
  721. , title: `npm i for ${repodef.repo}`
  722. }).then(Tasq.then).catch(Tasq.catch)
  723. return p;
  724. })
  725. }
  726. })
  727. // PB : NOTE -- npm i for client does not complete when NODE_ENV=production
  728. // therefore bower doesn't get installed !!! which then fails installing the bower dependenciew !!!
  729. // We work around this by running npm i for client without any NODE_ENV which probably defualts to development.
  730. // PB : TODO -- Investigate why NODE_ENF has an impact on npm i !??
  731. // Second time try also doesnt work.
  732. // repotasks.push(
  733. // () => {
  734. // var env = Object.assign({}, process.env)
  735. // delete env.NODE_ENV
  736. // console.log(`--------------------second time npm i for client--------------------`)
  737. // return nodeShellExec(`"${gitbash}"`, ['-c', '"npm i --force"'], {
  738. // // return nodeShellExec('npm', ['i --force'], {
  739. // inherit: true, shell: true
  740. // , cwd: instanceroot + '/' + 'client'
  741. // , env
  742. // , title: `npm i for client`
  743. // }).then(Tasq.then).catch(Tasq.catch)
  744. // })
  745. var bowerRepos = [{ repo : 'client'}]
  746. bowerRepos.forEach(repodef => {
  747. repotasks.push(() => {
  748. console.log(instanceroot + '/' + repodef.repo + '/node_modules/bower/bin/bower')
  749. // var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  750. var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  751. inherit: true, shell: true
  752. , cwd: instanceroot + '/' + repodef.repo
  753. , env: process.env
  754. , title: `bower i for ${repodef.repo}`
  755. }).then(Tasq.then).catch(Tasq.catch)
  756. return p;
  757. })
  758. })
  759. // console.log('rmtasks.length : ' + rmtasks.length)
  760. return Promise.all(rmtasks).then(() => any(repotasks));
  761. }).catch(e => {
  762. }).finally(statuslog.finally)
  763. }
  764. , 'start': (label) => {
  765. console.log('Starting Elixir Server.');
  766. var env = Object.assign({}, process.env); // Shallow clone it.
  767. // console.dir(env)
  768. env.NODE_ENV = process.env.NODE_ENV || 'development';
  769. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  770. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  771. // cmd = 'node'
  772. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
  773. var childPromise = nodeShellExec(...cmd, {
  774. // inherit : true,
  775. shell: true,
  776. detached: true,
  777. stdio: 'ignore',
  778. cwd: instanceroot + '/' + 'elixir-server'
  779. , env: env
  780. })
  781. var child = childPromise.process;
  782. if (typeof child.pid !== 'undefined') {
  783. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  784. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  785. encoding: 'utf8'
  786. })
  787. }
  788. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  789. // inherit : true,
  790. // shell: true, detached: true,
  791. // cwd : 'qms/server',
  792. // env: env,
  793. // shell : true
  794. // })
  795. // nodeShellExec('ember', ['s'], {
  796. // // inherit : true,
  797. // shell: true, detached: true,
  798. // cwd : 'client/',
  799. // env: env
  800. // })
  801. console.log('Starting Elixir Client Host.');
  802. var cmd = ['ember', ['s']]
  803. var childPromise = nodeShellExec(...cmd, {
  804. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  805. // PB : TODO -- ember debugging.
  806. // inherit : true,
  807. shell: true,
  808. detached: true,
  809. stdio: 'ignore',
  810. cwd: instanceroot + '/' + 'client'
  811. , env: env
  812. })
  813. // .catch(e=>console.error(e))
  814. child = childPromise.process;
  815. if (typeof child.pid !== 'undefined') {
  816. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  817. fs.writeFileSync('.client.server.pid', child.pid, {
  818. encoding: 'utf8'
  819. })
  820. }
  821. }
  822. , 'stop': (label) => {
  823. const kill = require('tree-kill');
  824. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  825. encoding: 'utf8'
  826. })
  827. fs.unlinkSync('.elixir-server.elixir.server.pid')
  828. console.log(serverPid)
  829. kill(serverPid)
  830. serverPid = fs.readFileSync('.client.server.pid', {
  831. encoding: 'utf8'
  832. })
  833. fs.unlinkSync('.client.server.pid')
  834. console.log(serverPid)
  835. kill(serverPid)
  836. }
  837. , 'model' : () => {
  838. if (__isElevated) {
  839. var tasks = [
  840. () => {
  841. var p = nodeShellExec('mklink', [ `${processedArgs._[2]}.json`
  842. , `..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`], {
  843. inherit: true, shell: true
  844. , cwd : instanceroot + `/${selectedinstance.instanceName}-server/${selectedinstance.instanceName}/models`
  845. , title: `mklink ${processedArgs._[2]}.json ..\\..\\node_modules\\chess-server-lib\\common\\models\\${processedArgs._[2]}.json`
  846. , env: process.env
  847. }).catch((e) => { console.error(e) })
  848. return p;
  849. }
  850. ];
  851. return any(tasks).then(() => {
  852. fs.writeFileSync('run.done', 'success')
  853. }).catch(() => {
  854. fs.writeFileSync('run.done', 'error')
  855. })
  856. }
  857. else return op['runas']()
  858. }
  859. , 'use' : () => {
  860. // use a certain named instance.
  861. // Eg :
  862. // 1) elxr use elixir
  863. // 2) elxr use cihsr
  864. // If environment is not specified defaults to development.
  865. // 1) NODE=test elxr use elixir
  866. /*// Steps
  867. 1) Delete Config and Data symlinks
  868. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  869. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  870. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  871. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  872. */
  873. var runconfig = { NODE_ENV: repomanifest.node_env }
  874. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  875. // We no longer need to check ruans.. ??? if we were initiated from self invoked privileged shell ?
  876. if (( /*processedArgs.runas && processedArgs.runas !== 'self' &&*/ !processedArgs.force) &&
  877. runconfig.NODE_ENV && runconfig.NODE_ENV === (repomanifest.node_env || runconfig.NODE_ENV) &&
  878. repomanifest.instanceName && runconfig.use === repomanifest.instanceName) {
  879. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  880. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  881. return
  882. }
  883. var tasks = [
  884. () => {
  885. if (existsSync('config')) {
  886. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  887. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  888. return p;
  889. }
  890. else return Promise.resolve(true);
  891. },
  892. () => {
  893. if (existsSync('data')) {
  894. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  895. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  896. return p;
  897. }
  898. else return Promise.resolve(true);
  899. },
  900. ];
  901. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  902. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  903. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  904. // console.log(process.env.cwd)
  905. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  906. // Maps an environment to a branch. Not required if the branch is appropriately named.
  907. var checkoutMap = { 'development': 'master' }
  908. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  909. var performPullOrCloneForBranch = (def)=>{
  910. var promise = Promise.resolve(true)
  911. if (!branch) {
  912. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  913. promise = nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{ branch = __branch})
  914. .catch((e) => { console.error(e); return { error: true, message: repo } })
  915. }
  916. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e )})
  917. }
  918. var performCloneAndCheckout = null;
  919. // cant use git checkout -b it fails when branch already exists.
  920. var performCheckout = performCloneAndCheckout = (def) => {
  921. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  922. return performPullOrCloneForBranch(def).then(()=>{
  923. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  924. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  925. // inherit : true, shell: true,
  926. cwd: instanceroot + '/' + def.repo
  927. // , stdio : ignore // Use when we want to silence output completely.
  928. , runas: processedArgs.runas
  929. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  930. }).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 } })
  931. })
  932. }
  933. // var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  934. // var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  935. var elevatedqueue = [];
  936. var enqueueOnce = (queue, task, def) => {
  937. var found = queue.find(element => {
  938. var keys = Object.keys( element )
  939. for(var k=0; k < keys.length; k++) {
  940. if(element[keys[k]] !== def[k]) return false;
  941. }
  942. })
  943. queue.push(function(){ return task(this)}.bind(def));
  944. }
  945. var enqueue = (queue, task, def) => {
  946. queue.push(function(){ return task(def)}.bind(def));
  947. }
  948. var mergeSources = {
  949. 'development': null,
  950. 'test': 'master',
  951. 'production': 'master'
  952. }
  953. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  954. // Checkout is reduced to pull provided the current branch is the targetbranch
  955. if(branch === mergesource) performCheckout = (def) => {
  956. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  957. return nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{
  958. if(branch === __branch) return performCloneAndCheckout(def)
  959. return performPullOrCloneForBranch(def)
  960. })
  961. .catch((e) => { console.error(e); return { error: true, message: repo } })
  962. }
  963. // else performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  964. var performPullAll = (def) => {
  965. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  966. return nodeShellExec('git', ['pull', '--all'], {
  967. // inherit : true, shell: true,
  968. cwd: instanceroot + '/' + def.repo
  969. , runas: processedArgs.runas
  970. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  971. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  972. }
  973. var excludeCheckouts = Object.assign(exludeMergeRepos)
  974. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  975. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  976. var performMerge = (def) => {
  977. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  978. return nodeShellExec('git', ['merge', mergesource], {
  979. inherit: true, shell: true,
  980. cwd: instanceroot + '/' + def.repo
  981. , runas: processedArgs.runas
  982. }).catch((e) => { console.error(e) })
  983. }
  984. if(!mergesource || branch === mergesource) performMerge = () => { return Promise.resolve(true) }
  985. // var performRepoOperation = function(def) {
  986. // elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  987. // return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  988. // }
  989. return any(tasks).then(() => {
  990. var pr = Promise.resolve(true)
  991. if (!__isElevated) {
  992. pr = op['runas']()
  993. return pr.then(()=>{
  994. //target is the env is we specify in elxr use command. Default is dev
  995. //Switch to target branch
  996. return any(gitRepos.map((repodef) => { return performCheckout({ repo : repodef.repo, branch}).catch(e=>{ console.log(e); }) } ))
  997. // pull or clone target branch
  998. .then(() => {
  999. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1000. return any(gitRepos.map((repo) => performPullAll(repo)))
  1001. })
  1002. // switch to source branch
  1003. .then( () => {
  1004. if(!mergesource || branch === mergesource ) return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  1005. return any(gitRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource})))
  1006. })
  1007. //Pull on merge source branch
  1008. .then( () => {
  1009. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1010. return any(gitRepos.map((repo) => performPullAll(repo)))
  1011. })
  1012. //Switch to target branch
  1013. .then( () => {
  1014. if(!mergesource || branch === mergesource ) return Promise.resolve(true)
  1015. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch})))
  1016. })
  1017. .then( //Merge source branch to target branch
  1018. () => {
  1019. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1020. return any(gitRepos.map((repo) => performMerge( repo ))).catch(err => { console.error('error in performMerge ' + err) })
  1021. })
  1022. })
  1023. }
  1024. else {
  1025. tasks = [
  1026. () => {
  1027. // Use junctions to avoid npm package issues
  1028. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  1029. inherit: true, shell: true
  1030. , cwd : instanceroot
  1031. , env: process.env
  1032. }).catch((e) => { console.error(e) })
  1033. return p;
  1034. }
  1035. ];
  1036. if (processedArgs._[1]) {
  1037. tasks = tasks.concat(
  1038. [
  1039. () => {
  1040. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  1041. inherit: true, shell: true
  1042. , cwd : instanceroot
  1043. , env: process.env
  1044. }).catch((e) => { console.error(e) })
  1045. return p;
  1046. }
  1047. ]
  1048. )
  1049. }
  1050. return any(tasks).then(()=>{
  1051. // checkout target branch
  1052. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1053. // pull or clone target branch
  1054. .then(() => {
  1055. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1056. return any(elevatedRunasRepos.map((repo) => performPullAll(repo)))
  1057. })
  1058. // switch to source branch
  1059. .then( () => {
  1060. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1061. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch: mergesource, requiresElevation : true})))
  1062. })
  1063. //Pull on merge source branch
  1064. .then( () => {
  1065. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1066. return any(elevatedRunasRepos.map((repodef) => performPullAll({repo : repodef.repo, requiresElevation : true })))
  1067. })
  1068. //Switch to target branch
  1069. .then( () => {
  1070. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1071. return any(elevatedRunasRepos.map((repodef) => performCheckout({ repo : repodef.repo, branch, requiresElevation : true})))
  1072. })
  1073. .then( //Merge source branch to target branch
  1074. () => {
  1075. if(!mergesource || branch === mergesource) return Promise.resolve(true)
  1076. return any(elevatedRunasRepos.map((repodef) => performMerge({ repo : repodef.repo, requiresElevation : true }))).catch(err => { console.error('error in performMerge ' + err) })
  1077. })
  1078. .then(() => {
  1079. fs.writeFileSync('run.done', 'success')
  1080. }).catch(() => {
  1081. fs.writeFileSync('run.done', 'error')
  1082. })
  1083. })
  1084. }
  1085. }).catch(() => {
  1086. fs.writeFileSync('run.done', 'error')
  1087. })
  1088. // Antibiotic stewardship program.
  1089. // 1st use is fine.
  1090. // Max vials dispense
  1091. // 2nd use Pharmacy needs justification Form.
  1092. // Approval after a certain period of time.
  1093. }
  1094. , 'g': () => {
  1095. if (processedArgs.h) {
  1096. console.log('elxr g [modelname] => generate a model named [modelname]');
  1097. console.log('elxr g => regenerate all known models');
  1098. return
  1099. }
  1100. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1101. // console.log('Starting directory: ' + process.cwd());
  1102. // try {
  1103. // child = child.on('close', () => { process.chdir(label) } );
  1104. // console.log('New directory: ' + process.cwd());
  1105. // }
  1106. // catch (err) {
  1107. // console.log('chdir: ' + err);
  1108. // }
  1109. // child.on('close', function(){
  1110. // var options = {
  1111. // shell : true
  1112. // , inherit : true
  1113. // // , cwd : '' + process.cwd
  1114. // // , env : process.env
  1115. // };
  1116. // nodeShellExec('git', ['init'], { inherit : true});
  1117. if (0) {
  1118. // PB : TODO -- Special google chrome profile for tests etc.
  1119. nodeShellExec('pwd', { inherit: true });
  1120. // /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"
  1121. // "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
  1122. // "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
  1123. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1124. "--profile-directory=Profile 1"
  1125. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1126. }
  1127. // nodeShellExec('npm', ['init', '-y'], options);
  1128. // nodeShellExec('npm', ['init', '-y'], options);
  1129. // })
  1130. var g = {
  1131. 'client': () => {
  1132. console.info('Creating new ember client named : ' + processedArgs._[2]);
  1133. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1134. stdio: ['pipe', process.stdout, process.stderr],
  1135. inherit: true,
  1136. shell: true,
  1137. cwd: path.dirname(__dirname),
  1138. env: env
  1139. })
  1140. },
  1141. 'modelr': () => {
  1142. var tasks = [
  1143. () => {
  1144. var p = nodeShellExec('"ember"', [
  1145. 'g'
  1146. , 'modelr'
  1147. , processedArgs._[2]], {
  1148. inherit: true, shell: true, env: process.env
  1149. }).then(() => {
  1150. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  1151. return true;
  1152. }).catch((e) => { console.error(e) })
  1153. return p;
  1154. },
  1155. () => {
  1156. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1157. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  1158. chromeprefs = JSON.parse(chromeprefs)
  1159. var previous = chromeprefs.download.default_directory;
  1160. var parentDir = path.dirname(__dirname);
  1161. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1162. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1163. // PB : TODO -- detect where chrome is installed.
  1164. // PB : TODO -- set the download dir to the place where files are needed.
  1165. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1166. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1167. , '--profile-directory="chess"'
  1168. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1169. inherit: true, shell: true
  1170. , env: process.env
  1171. }).then(() => {
  1172. chromeprefs.download.default_directory = previous;
  1173. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1174. return true;
  1175. }).catch((e) => { console.error(e) })
  1176. return p;
  1177. }
  1178. ,
  1179. () => {
  1180. console.log('Browser process should have closed here....')
  1181. return true;
  1182. }
  1183. ]
  1184. any(tasks)
  1185. }
  1186. }
  1187. g[processedArgs._[1]]();
  1188. }
  1189. }
  1190. var util = require('util')
  1191. var cliname = 'elxr';
  1192. var ver = '1.1';
  1193. var help = `# list of commands... please refer dveloper documentation for ${cliname}
  1194. ${
  1195. // util.inspect(
  1196. [Object.keys(op)]
  1197. // )
  1198. }
  1199. `;
  1200. var elxr = {
  1201. help() {
  1202. return chalk.cyanBright(`
  1203. -------------------------------------------------------------------------------
  1204. *** BBH Elixir ***
  1205. -------------------------------------------------------------------------------
  1206. elxr ${ver}
  1207. A cli tool for chess
  1208. ${help}
  1209. -------------------------------------------------------------------------------
  1210. `)
  1211. }
  1212. , info() {
  1213. return chalk.cyanBright(`
  1214. -------------------------------------------------------------------------------
  1215. *** BBH Elixir ***
  1216. -------------------------------------------------------------------------------
  1217. elxr ${ver}
  1218. A cli tool for chess
  1219. -------------------------------------------------------------------------------
  1220. `)
  1221. }
  1222. , getpulltask(def){
  1223. def = def || {
  1224. requiresElevation : true,
  1225. reqularRepos : gitRepos,
  1226. elevatedRepos : elevatedRunasRepos
  1227. }
  1228. console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  1229. console.dir(def)
  1230. var env = Object.assign({}, process.env); // Shallow clone it.
  1231. console.log('Running exlr pull : ' + path.dirname(__dirname))
  1232. var useGitPull = processedArgs.useGitPull || false;
  1233. if(def.elevatedRepos || def.reqularRepos) {
  1234. if(def.elevatedRepos) def.requiresElevation = true;
  1235. else delete def.requiresElevation;
  1236. }
  1237. else {
  1238. if(def.requiresElevation) def.elevatedRepos = [def]
  1239. else def.reqularRepos = [def]
  1240. }
  1241. var elevatedpulltasks = null;
  1242. var regularpulltasks = function(){ return Promise.resolve(true) }
  1243. if(def.elevatedRepos){
  1244. elevatedpulltasks = function() {
  1245. return any(def.elevatedRepos.map((def) => performPull(def.repo))).then(() => {
  1246. // fs.writeFileSync('run.done', 'success')
  1247. return true;
  1248. }).catch((e) => {
  1249. console.error(e)
  1250. fs.writeFileSync('run.done', 'error')
  1251. })
  1252. }
  1253. }
  1254. if(def.reqularRepos) {
  1255. var regularpulltasks = function(){
  1256. var pendingpulls = [];
  1257. def.reqularRepos.forEach((def) => { pendingpulls.push(performPull(def.repo)) })
  1258. return Promise.all(pendingpulls).finally(Traq.finally)
  1259. }
  1260. }
  1261. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1262. else return getTaskWithoutElevation({ regularpulltasks})
  1263. }
  1264. }
  1265. // The main elxr cli process
  1266. function elxrworker() {
  1267. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  1268. gitRepos = repomanifest.repos
  1269. // gitRepos = ['chess-server-lib'];
  1270. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  1271. elevatedRunasRepos = repomanifest.elevated
  1272. // Repos that should excluded from merge for releases...
  1273. exludeMergeRepos = repomanifest.exludeMergeRepos
  1274. var env = Object.assign({}, process.env); // Shallow clone it.
  1275. var __runcmd = function (label) {
  1276. return op[label] ? op[label]() : null;
  1277. }
  1278. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  1279. // mysql -u root -p db_name < drop_all_tables.sql
  1280. var mysql = '../xampp/mysql/bin/mysql'
  1281. var mysqldump = '../xampp/mysql/bin/mysqldump'
  1282. // --runas
  1283. if (processedArgs.runas) {
  1284. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  1285. return __runcmd('runas')
  1286. }
  1287. else return __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  1288. }
  1289. var getManifest = function () {
  1290. // Once choices are made we need to load config according to those choices.
  1291. // No trace of a previous run...
  1292. // Default Config...
  1293. return repomanifest = selectedinstance;
  1294. }
  1295. function acquireChoices(selectedinstance) {
  1296. var hasconfig = false;
  1297. console.warn(chalk.yellow(`
  1298. -------------------------------------------------------------------------------
  1299. Warning : Cannot locate your preferred configuration since it was not specified
  1300. You should fork the default chess configuration to customize and make it
  1301. your own instance with a named config as
  1302. {{yourowninstancename}}-config-{{yourcurrentenvironment}}
  1303. And then run this tool as follows
  1304. NODE_ENV={{yourenvironment}} elxr i {{yourowninstancename}}
  1305. OR
  1306. Run this tool with the following command to use a quick start default.
  1307. node elxr --default
  1308. OR
  1309. Choose the the option to create a new instance for you interactively.
  1310. We will run your choice of default or create your own at the next prompt.
  1311. -------------------------------------------------------------------------------
  1312. `))
  1313. var prompt = cli.prompter;
  1314. return prompt.ask(`Choose an option :
  1315. d) Install the default chess instance.
  1316. => elxr i chess node_env=development --default
  1317. n) Create your custom new instance interactively
  1318. => elxr i {{instanceName}} node_env={{environment}}
  1319. i) Choose an instance and environment to install
  1320. => elxr i {{instanceName}} node_env={{environment}}
  1321. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  1322. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  1323. h) Help
  1324. q) Quit
  1325. Default <= d
  1326. : `).then((choice) => {
  1327. prompt.close();
  1328. if (choice && choice === 'd' || !choice) {
  1329. processedArgs._[0] = 'i'
  1330. selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  1331. selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  1332. selectedinstance.reposerver = 'https://git.bbh.org.in'
  1333. getManifest() // PB : TODO -- acquire the manifest directly from http url instead of clone before cloning the config. Since
  1334. // This is because the manifest at any server location can redirect to the preferred server..
  1335. }
  1336. else if (choice === 'h') {
  1337. processedArgs._[0] = 'h'
  1338. fs.writeFileSync('run.done', 'noop help');
  1339. console.log(elxr.help()); process.exit()
  1340. }
  1341. else if (choice === 'n' || choice === 'i') {
  1342. var p1 = cli.prompter;
  1343. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1344. processedArgs._[0] = 'i'
  1345. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  1346. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1347. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1348. if (choice === 'n') {
  1349. selectedinstance.reposerver = 'https://git.bbh.org.in'
  1350. console.warn(
  1351. chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  1352. process.exit();
  1353. }
  1354. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1355. p1.close()
  1356. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1357. })
  1358. })
  1359. })
  1360. } else if (choice === 'c') {
  1361. var p1 = cli.prompter;
  1362. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1363. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  1364. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1365. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1366. return p1.ask(`Enter cmd :
  1367. p) pull
  1368. Default <= p
  1369. : `).then(function (cmd) {
  1370. if (!cmd || cmd === 'p') {
  1371. processedArgs._[0] = 'pull'
  1372. }
  1373. else processedArgs._[0] = cmd
  1374. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1375. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1376. p1.close()
  1377. })
  1378. })
  1379. })
  1380. })
  1381. } else {
  1382. 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.`));
  1383. fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  1384. fs.writeFileSync('run.done', 'noop quit');
  1385. process.exit()
  1386. }
  1387. })
  1388. }
  1389. var acquireConfig = function (selected, chessinstances) {
  1390. var configrepo = selected.instanceName + '-config-' + selected.node_env;
  1391. return performPull(configrepo).then(() => {
  1392. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  1393. repomanifest = require(manifestpath)()
  1394. chessinstances = chessinstances || {};
  1395. chessinstances[selected.instanceName] = chessinstances[selected.instanceName] || {}
  1396. chessinstances[selected.instanceName][selected.node_env] = chessinstances[selected.instanceName][selected.node_env] || {}
  1397. chessinstances['current_run'] = { instanceName: selected.instanceName, node_env: selected.node_env }
  1398. // Config from server always override merges into selection ecept for the current selection.
  1399. selectedinstance = utils.assign(chessinstances[selected.instanceName][selected.node_env], selected, repomanifest)
  1400. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  1401. // PB : TODO -- We should probably write the new server config also...
  1402. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  1403. ENV.NODE_ENV = selectedinstance.node_env;
  1404. })
  1405. .catch((e) => {
  1406. console.error(e)
  1407. console.error('Config acquisition failed.')
  1408. })
  1409. }
  1410. var launchpath = process.cwd().replace(/\\/, '/')
  1411. var thisscriptdir = __dirname
  1412. var instanceroot = launchpath;
  1413. var detectInstance = function () {
  1414. console.log(`launchpath = ${launchpath}`)
  1415. console.log(`thisscriptdir = ${thisscriptdir}`)
  1416. var root = launchpath;
  1417. // We need a reference to the root director for elxr cli to be properly oriented.
  1418. if ((launchpath + path.normalize('/elxr')) === thisscriptdir) {
  1419. // We ran unbuilt from the proper root with elxr subfolder.
  1420. console.log(`Instance Path : ${root}`)
  1421. }
  1422. else {
  1423. if (launchpath === thisscriptdir) {
  1424. // Same directory doesn't mean we are being run from elxr directory or the root directory.
  1425. // It could be a standalone elxr build which may or maynot be in the proper location.
  1426. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  1427. // Unbuilt therefore we are in the elxr directory.
  1428. root = path.normalize(launchpath + '/..');
  1429. }
  1430. else {
  1431. // Built version.
  1432. // check if we have a elxr subfolder.
  1433. if (fs.existsSync(launchpath + '/..' + path.normalize('/elxr'))) {
  1434. // Probably in the right place.
  1435. root = path.normalize(launchpath + '/..');
  1436. }
  1437. else {
  1438. // Assume launchpath is meaningless.
  1439. // Figure it out from the input instance name and environment parameters if we are in the right location.
  1440. root = path.normalize(launchpath + '/' + processedArgs._[1] + '/' + processedArgs.node_env)
  1441. }
  1442. }
  1443. }
  1444. }
  1445. instanceroot = root.replace(/\\/, '/');
  1446. __default.root = root;
  1447. return Promise.resolve(__default);
  1448. }
  1449. //
  1450. var __default = {
  1451. // Default is public server only.
  1452. // All public repos are by default available.
  1453. reposervers: ['https://git.bbh.org.in']
  1454. , repos: [
  1455. 'setup'
  1456. , 'elxr'
  1457. , 'loopback-connector-mysql'
  1458. , 'loopback-jsonapi-model-serializer'
  1459. , 'loopback-component-jsonapi'
  1460. , 'ember-service-worker'
  1461. , 'ember-service-worker-asset-cache'
  1462. , 'ember-service-worker-cache-fallback'
  1463. , 'ember-service-worker-index'
  1464. , 'ember-sw-client-route'
  1465. ]
  1466. , elevated: []
  1467. , exludeMergeRepos: {}
  1468. , instanceName: 'chess'
  1469. // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
  1470. , node_env: 'development'
  1471. }
  1472. var __interactve_promts = {
  1473. get reposerver(){
  1474. return cli.prompt(this.reposervers, 'git default repo').then(reposerver => {
  1475. Object.defineProperty(this, 'reposerver', {
  1476. value: reposerver,
  1477. writable: false,
  1478. configurable : true
  1479. });
  1480. return reposerver
  1481. })
  1482. }
  1483. , set reposerver(reposerver){
  1484. Object.defineProperty(this, 'reposerver', {
  1485. value: reposerver,
  1486. writable: false,
  1487. configurable : true
  1488. });
  1489. return reposerver
  1490. }
  1491. }
  1492. var downloadsdir = '../Downloads';
  1493. var prerequisites = [
  1494. {
  1495. shellcmd: 'git',
  1496. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  1497. , installer: 'Git-2.31.0-64-bit.exe'
  1498. , installcmd: ['cmd', ['/c', 'start',
  1499. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  1500. , '/VERYSILENT'
  1501. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  1502. ]]
  1503. , preinstallsteps: function() {
  1504. var prompt = cli.prompter;
  1505. var steps = [
  1506. () => {
  1507. if (!existsSync(downloadsdir + '/' + this.installer)) {
  1508. return nodeShellExec(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, [this.url, downloadsdir + '/' + this.installer])
  1509. }
  1510. else return Promise.resolve(true)
  1511. }
  1512. ]
  1513. var prompts = [
  1514. () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
  1515. , () => prompt.ask(`git email : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
  1516. ]
  1517. return any([any(steps), any(prompts)]).then(() => { prompt.close() })
  1518. }
  1519. , installsteps: function () {
  1520. return any([this.installcmd].map(callsheltask))
  1521. }
  1522. , postinstallsteps: function(){
  1523. var prompt = cli.prompter;
  1524. var gitUser = 'guest';
  1525. var gitEmail = 'guest@bbh.org.in';
  1526. var prompts = [];
  1527. prompts.push(
  1528. ()=>{
  1529. var choices = { 0 : 'guest', 1 : 'chessdemo' }
  1530. return cli.prompt(choices, 'git user name').then(gituser => gitUser = gituser)
  1531. }
  1532. )
  1533. prompts.push(
  1534. ()=>{
  1535. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  1536. return cli.prompt(choices, 'git user email').then(gitemail => gitEmail = gitemail)
  1537. }
  1538. )
  1539. return any(prompts).then(()=>{
  1540. var steps = [
  1541. ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  1542. , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  1543. ]
  1544. return any(steps.map(callsheltask)).then(() => {
  1545. })
  1546. });
  1547. }
  1548. , install: function () {
  1549. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  1550. }
  1551. , verifyAndInstall : function(){
  1552. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  1553. if(exists) {
  1554. // return any(['git', ['config', '--global', '-l']].map(callsheltask))
  1555. return this.getUser(null, this.postinstallsteps.bind(this))
  1556. }
  1557. return this.install();
  1558. });
  1559. }
  1560. , getUser : function(repo, onNoResult){
  1561. onNoResult = onNoResult || function(){return false}
  1562. var globalOrLocal = '--global';
  1563. if(!repo) globalOrLocal = '--global';
  1564. else globalOrLocal = '--local'
  1565. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(callsheltask)).then((result)=>{
  1566. // not yet configured.
  1567. if(!result.success) return onNoResult()
  1568. else {
  1569. var users = result.messages[0].trim().split('\n');
  1570. if(users.length === 0 ||
  1571. users.length === 1 && users[0] === 'guest') {
  1572. return onNoResult()
  1573. }
  1574. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  1575. }
  1576. })
  1577. .catch((e)=>{
  1578. console.log(e)
  1579. return onNoResult()
  1580. })
  1581. }
  1582. }
  1583. ,
  1584. {
  1585. shellcmd: 'node',
  1586. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  1587. , installer: 'node-v14.16.0-x64.msi'
  1588. , installcmd: ['MSIEXEC.exe', ['/i'
  1589. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  1590. , 'ACCEPT=YES', '/passive']]
  1591. , install : function() { return any([this.installcmd].map(callsheltask)).then(() => { }) }
  1592. }
  1593. ]
  1594. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  1595. function ensureDirectoryExistence(filePath) {
  1596. var dirname = path.dirname(filePath);
  1597. if (fs.existsSync(dirname)) {
  1598. return filePath;
  1599. }
  1600. ensureDirectoryExistence(dirname);
  1601. fs.mkdirSync(dirname);
  1602. return filePath;
  1603. }
  1604. var mainTasks = [];
  1605. function verifyAndInstallPrerequisites() {
  1606. fs.writeFileSync(ensureDirectoryExistence(path.normalize(`${selectedinstance.root}/${downloadsdir}/readme.txt`)), `${getVersion()} Your local downloads for this instance`)
  1607. // PB : TODO include and build from files... using rollup..
  1608. var downloadbatch =
  1609. `::**************************************************************************
  1610. :Download_ <url> <File>
  1611. Powershell.exe ^
  1612. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  1613. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  1614. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  1615. exit /b
  1616. ::**************************************************************************`
  1617. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`, downloadbatch)
  1618. var windowselevate =
  1619. `
  1620. <html><HTA:APPLICATION ID="windowselevate" icon="#"/>
  1621. <script language="vbscript">
  1622. document.title = "elxr control panel"
  1623. self.ResizeTo 200,600
  1624. Sub Window_Onload
  1625. self.MoveTo (screen.availWidth - (document.body.clientWidth + 40)),10
  1626. End Sub
  1627. Set objShell = CreateObject("WScript.Shell")
  1628. Set objENV = objShell.Environment("Process")
  1629. dim NODE_ENV
  1630. NODE_ENV = objENV("NODE_ENV")
  1631. </script>
  1632. <script language="javascript">
  1633. //WINDOWSTATE="minimize" SHOWINTASKBAR="no" SYSMENU="no" CAPTION="no"
  1634. // https://devblogs.microsoft.com/scripting/how-can-i-pass-command-line-variables-to-an-hta-when-it-starts/
  1635. // alert(windowselevate.commandLine)
  1636. var args = windowselevate.commandLine.split('"').slice(3);
  1637. // alert(args)
  1638. var processedArgs = { _ : [] }
  1639. var namedArgs = [];
  1640. for(var item in args){
  1641. if(args[item].charAt(0) === '-'){
  1642. namedArgs.push(args[item])
  1643. var split = args[item].split('=');
  1644. processedArgs[split[0].slice(2)] = split[1] || true;
  1645. }
  1646. else processedArgs._.push(args[item]);
  1647. }
  1648. // args = args.forEach(function(item){ })
  1649. // alert('processedArgs._ : ' + processedArgs._);
  1650. // alert(processedArgs.runas);
  1651. // PB : TODO -- Convert all the cli args back to string.
  1652. var cargs = (processedArgs.debug ? '--inspect-brk=9228' : '') + ' elxr ' + processedArgs._.join(' ') + ' ' + namedArgs.join(' ');
  1653. // alert(cargs)
  1654. var shell = new ActiveXObject('shell.application');
  1655. // alert('launching node privilged. ' + processedArgs['nodepath'])
  1656. // shell.ShellExecute('where', 'node', '', '', 10);
  1657. shell.ShellExecute('node', cargs, '', 'runas', 1);
  1658. // shell.ShellExecute(processedArgs['nodepath'], cargs, '', 'runas', 1);
  1659. var fso = new ActiveXObject('Scripting.FileSystemObject');
  1660. window.onload = function() {
  1661. document.body.style.backgroundColor = 'black';
  1662. document.body.style.fontFamily = 'arial';
  1663. var log = document.createElement('div');
  1664. log.innerHTML='Please Wait';
  1665. function l(msg){ log.innerHTML+= msg; };
  1666. log.style.color = 'blue';
  1667. log.style.width = '95%';
  1668. log.id = 'log';
  1669. document.body.appendChild(log);
  1670. l('<Br/>Current config : ')
  1671. l('<Br/>NODE_ENV = ' + NODE_ENV)
  1672. l('<Br/>cmd = ' + processedArgs._[0])
  1673. processedArgs._[1] === 'use' ? l('<Br/>using = ' + processedArgs._[2]) : null;
  1674. l('<Br/><Br/>')
  1675. var timer = function(){
  1676. l('.');
  1677. if(fso.FileExists("run.done")) close();
  1678. else window.setTimeout(timer, 1000);
  1679. };
  1680. window.setTimeout(timer, 3000);
  1681. };
  1682. </script>
  1683. </html>
  1684. `
  1685. fs.writeFileSync(`${selectedinstance.root}/.elxr/run-${runtimestamp}/windowselevate.hta`, windowselevate)
  1686. var downloadtasks = [];
  1687. var installtasks = [];
  1688. prerequisites.forEach(preq => {
  1689. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  1690. if (exists) console.log(`${preq.shellcmd} exists`)
  1691. else {
  1692. console.log(`${preq.shellcmd} is not installed`)
  1693. return preq.preinstallsteps.call(preq).then(() => {
  1694. installtasks.push(preq.install.bind(preq))
  1695. })
  1696. }
  1697. }))
  1698. })
  1699. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  1700. }
  1701. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  1702. var selectedinstance = null;
  1703. var chessinstances = { current_run : {} };
  1704. acquireElevationState().then(() => {
  1705. var skipprerequisites = false;
  1706. var clioverrides = { }
  1707. function initinstances(chessinstances, selected) {
  1708. chessinstances.current_run.instanceName = processedArgs._[1] = processedArgs._[1] || chessinstances.current_run.instanceName || selected.instanceName;
  1709. chessinstances.current_run.node_env = processedArgs.node_env = processedArgs.node_env || chessinstances.current_run.node_env || selected.node_env;
  1710. chessinstances[chessinstances.current_run.instanceName] = chessinstances[chessinstances.current_run.instanceName] || {}
  1711. // Override sequence.
  1712. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  1713. selectedinstance = Object.assign(
  1714. selected
  1715. , chessinstances[chessinstances.current_run.instanceName][chessinstances.current_run.node_env]
  1716. , clioverrides
  1717. // , __interactve_promts -- Cant just override. Also need selectedinstance to be ready...
  1718. );
  1719. repomanifest = selectedinstance
  1720. return chessinstances
  1721. }
  1722. function acquirelocalinstances(selected){
  1723. var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
  1724. return chessinstances
  1725. }
  1726. var maintask = () => {
  1727. // Default cmd to run !
  1728. processedArgs._[0] === processedArgs._[0] || 'pull';
  1729. // selectedinstance.reposerver = repomanifest.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available...
  1730. return prerequisites.git.verifyAndInstall().then(()=>{
  1731. var e = { message : 'verifyAndInstall', success : true}
  1732. return acquireConfig(selectedinstance, chessinstances).catch((err) => {
  1733. e = err;
  1734. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  1735. console.error(err)
  1736. }).then(() => { return elxrworker(true) })
  1737. // .finally(()=>{
  1738. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  1739. // if(!e.success) fs.writeFileSync('run.done', 'error');
  1740. // // return process.exit()
  1741. // })
  1742. })
  1743. }
  1744. const retaincount = 2
  1745. var min = runtimestamp;
  1746. var collect = []
  1747. return detectInstance().then((detectedInstance)=>{
  1748. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  1749. processedArgs.node_env ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env
  1750. : (process.env.NODE_ENV && process.env.NODE_ENV.trim()) ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()): null;
  1751. selectedinstance = Object.assign(detectedInstance, clioverrides);
  1752. var todo = Promise.resolve(true);
  1753. try {
  1754. chessinstances = acquirelocalinstances(selectedinstance);
  1755. initinstances(chessinstances, selectedinstance)
  1756. }
  1757. catch (e) {
  1758. console.error(e)
  1759. // No local instances config found. We acquire user choices and proceed to reattempt.
  1760. initinstances(chessinstances, selectedinstance)
  1761. var prompts = [];
  1762. Object.keys(__interactve_promts).forEach(k => {
  1763. if(!selectedinstance[k]) {
  1764. prompts.push(async ()=>{
  1765. Object.defineProperty(selectedinstance, k, Object.getOwnPropertyDescriptor(__interactve_promts, k));
  1766. return await selectedinstance[k]
  1767. })
  1768. }
  1769. })
  1770. todo = any(prompts).then(()=>{ return selectedinstance })
  1771. if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  1772. // Weve been told what to do.
  1773. todo = acquireChoices(selectedinstance)
  1774. }
  1775. todo = todo.then(() => {
  1776. try {
  1777. chessinstances = acquirelocalinstances(selectedinstance)
  1778. initinstances(chessinstances, selectedinstance)
  1779. }
  1780. catch (e) {
  1781. console.error(e)
  1782. console.log('No local instances config found in current root = ' + selectedinstance.root);
  1783. console.log('A config will be createed with the instance and environment chosen...')
  1784. // return (async ()=>{return await __default.reposerver})().then(()=>{
  1785. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  1786. // return selectedinstance = Object.assign(__default, selectedinstance);
  1787. // })
  1788. return selectedinstance
  1789. }
  1790. })
  1791. }
  1792. return todo
  1793. })
  1794. .then(()=>{
  1795. if(!__isElevated) {
  1796. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/readme.txt`)
  1797. // collect garbage
  1798. return dirs( (dir)=>{
  1799. var matches = /run-(.*)/gm.exec(dir.name)
  1800. if(matches) {
  1801. if(+(matches[1]) < min) {
  1802. min = matches[1]
  1803. collect.splice( 0, 0, matches[1] )
  1804. }
  1805. else collect.push(matches[1])
  1806. }
  1807. }, `${selectedinstance.root}/.elxr` ).then(()=>{
  1808. // delete garbage
  1809. if(collect.length > retaincount) {
  1810. var asyncs = [];
  1811. while((collect.length - asyncs.length) > retaincount) {
  1812. asyncs.push(getShellTask('rm',['-rf', `run-${collect[asyncs.length]}`], { cwd : `${selectedinstance.root}/.elxr` })());
  1813. }
  1814. return Promise.all(asyncs)
  1815. }
  1816. else return true
  1817. })
  1818. }
  1819. else return true;
  1820. })
  1821. .then(()=>{
  1822. // PB : TODO -- Keep only the last n runs...
  1823. // Currently it retains 2*n when proc needs to be relaunched in elevated mode !!!
  1824. ensureDirectoryExistence(`${selectedinstance.root}/.elxr/run-${runtimestamp}/download.bat`)
  1825. if (!skipprerequisites && !__isElevated) mainTasks.push(verifyAndInstallPrerequisites);
  1826. mainTasks.push(maintask)
  1827. return any(mainTasks);
  1828. })
  1829. })
  1830. // detect if alread installed -> Take no action.
  1831. // download if no installer avalable -> next()
  1832. // install
  1833. function chackandinstall(items) {
  1834. var tasks = []
  1835. items.forEach(item => {
  1836. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  1837. })
  1838. return Promise.all(tasks).then(existances => {
  1839. existances.forEach((exists, i) => {
  1840. if (!exists) {
  1841. return downloadandinstall([items[i]])
  1842. }
  1843. })
  1844. })
  1845. }
  1846. function downloadandinstall(items) {
  1847. var tasks = []
  1848. items.forEach(item => {
  1849. tasks.push(getTaskDownload(item))
  1850. })
  1851. return Promise.all(tasks)
  1852. }
  1853. // Sample instances config.
  1854. // var instances = {
  1855. // "elixir": {
  1856. // "production": {
  1857. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  1858. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  1859. // , "exludeMergeRepos": {
  1860. // "elixir-config-development": true, "elixir-config-test": true
  1861. // , "elixir-config-production": true, "elixir-data": true
  1862. // }
  1863. // , "instanceName": "elixir", "node_env": "production"
  1864. // }
  1865. // },
  1866. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  1867. // }
  1868. // ,([^\}^\S\r]*?\}) // Regexp to eliminate extra comma at the end of an array or an object...