Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

index.js 63KB

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