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.

index.js 60KB

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