555
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

index.js 63KB

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