555
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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