555

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