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

index.js 62KB

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