You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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