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

index.js 67KB

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