Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

index.js 63KB

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