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年前
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年前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689
  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 = ['bbhverse', 'serververse', 'elixir-server'
  687. // , 'client'
  688. // ];
  689. var rmtasks = []
  690. var repotasks = []
  691. gitRepos.forEach(repo => {
  692. rmtasks.push(
  693. // () => {
  694. // console.log(`--------------------rm package-lock.json for ${repo}--------------------`)
  695. // return nodeShellExec(`"${gitbash}"`, ['-c', '"rm package-lock.json"'], {
  696. nodeShellExec('rm', ['package-lock.json'], {
  697. inherit: true, shell: true
  698. , cwd: instanceroot + '/' + repo
  699. , env: process.env
  700. , title: `rm 'package-lock.json' for ${repo}`
  701. })
  702. .then(()=>{
  703. console.log(`--------------------rm package-lock.json for ${repo}--------------------`)
  704. }).catch((e) => { console.error(e) })
  705. // }
  706. )
  707. if (npmbuildrepos.indexOf(repo) < 0) {
  708. repotasks.push(
  709. () => {
  710. console.log(`--------------------npm i for ${repo}--------------------`)
  711. var p = nodeShellExec('npm', ['i --force'], {
  712. inherit: true, shell: true
  713. , cwd: instanceroot + '/' + repo
  714. , env: process.env
  715. , title: `npm i for ${repo}`
  716. }).then(Tasq.then).catch(Tasq.catch)
  717. return p;
  718. })
  719. }
  720. })
  721. // PB : TODO -- npm i for client is for some reason not complete so bower doesn't get installed !!!
  722. // Second time try also doesnt work.
  723. // repotasks.push(
  724. // () => {
  725. // console.log(`--------------------second time npm i for client--------------------`)
  726. // var p = nodeShellExec('npm', ['i --force'], {
  727. // inherit: true, shell: true
  728. // , cwd: instanceroot + '/' + 'client'
  729. // , env: process.env
  730. // , title: `npm i for client`
  731. // }).then(Tasq.then).catch(Tasq.catch)
  732. // return p;
  733. // })
  734. var bowerRepos = ['client']
  735. bowerRepos.forEach(repo => {
  736. repotasks.push(() => {
  737. console.log(instanceroot + '/' + repo + '/node_modules/bower/bin/bower')
  738. var p = nodeShellExec('node_modules/bower/bin/bower', ['install'], {
  739. // var p = nodeShellExec(`"${gitbash}"`, ['-c', '"node_modules/bower/bin/bower i"'], {
  740. inherit: true, shell: true
  741. , cwd: instanceroot + '/' + repo
  742. , env: process.env
  743. , title: `bower i for ${repo}`
  744. }).then(Tasq.then).catch(Tasq.catch)
  745. return p;
  746. })
  747. })
  748. // console.log('rmtasks.length : ' + rmtasks.length)
  749. return Promise.all(rmtasks).then(() => any(repotasks));
  750. }).catch(e => {
  751. }).finally(statuslog.finally)
  752. }
  753. , 'start': (label) => {
  754. console.log('Starting Elixir Server.');
  755. var env = Object.assign({}, process.env); // Shallow clone it.
  756. // console.dir(env)
  757. env.NODE_ENV = process.env.NODE_ENV || 'development';
  758. env.DEBUG = 'loopback:connector:' + dbForLabel(label)
  759. var cmd = env.NODE_ENV === 'development' ? 'nodemon' : 'node';
  760. // cmd = 'node'
  761. cmd = [cmd, ['--inspect=9228', 'elixir/server.js']]
  762. var childPromise = nodeShellExec(...cmd, {
  763. // inherit : true,
  764. shell: true,
  765. detached: true,
  766. stdio: 'ignore',
  767. cwd: instanceroot + '/' + 'elixir-server'
  768. , env: env
  769. })
  770. var child = childPromise.process;
  771. if (typeof child.pid !== 'undefined') {
  772. console.log(`started Elixir Server PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  773. fs.writeFileSync('.elixir-server.elixir.server.pid', child.pid, {
  774. encoding: 'utf8'
  775. })
  776. }
  777. // nodeShellExec('node', ['--inspect=9226', ' bin/www'], {
  778. // inherit : true,
  779. // shell: true, detached: true,
  780. // cwd : 'qms/server',
  781. // env: env,
  782. // shell : true
  783. // })
  784. // nodeShellExec('ember', ['s'], {
  785. // // inherit : true,
  786. // shell: true, detached: true,
  787. // cwd : 'client/',
  788. // env: env
  789. // })
  790. console.log('Starting Elixir Client Host.');
  791. var cmd = ['ember', ['s']]
  792. var childPromise = nodeShellExec(...cmd, {
  793. // var childPromise = nodeShellExec('node', ['--inspect=9227', './node_modules/.bin/ember', 's'], {
  794. // PB : TODO -- ember debugging.
  795. // inherit : true,
  796. shell: true,
  797. detached: true,
  798. stdio: 'ignore',
  799. cwd: instanceroot + '/' + 'client'
  800. , env: env
  801. })
  802. // .catch(e=>console.error(e))
  803. child = childPromise.process;
  804. if (typeof child.pid !== 'undefined') {
  805. console.log(`started Elixir Client Host PID(${child.pid}) : NODE_ENV=${process.NODE_ENV} ${cmd}`);
  806. fs.writeFileSync('.client.server.pid', child.pid, {
  807. encoding: 'utf8'
  808. })
  809. }
  810. }
  811. , 'stop': (label) => {
  812. const kill = require('tree-kill');
  813. var serverPid = fs.readFileSync('.elixir-server.elixir.server.pid', {
  814. encoding: 'utf8'
  815. })
  816. fs.unlinkSync('.elixir-server.elixir.server.pid')
  817. console.log(serverPid)
  818. kill(serverPid)
  819. serverPid = fs.readFileSync('.client.server.pid', {
  820. encoding: 'utf8'
  821. })
  822. fs.unlinkSync('.client.server.pid')
  823. console.log(serverPid)
  824. kill(serverPid)
  825. }
  826. , 'use': () => {
  827. // use a certain named instance.
  828. // Eg :
  829. // 1) elxr use elixir
  830. // 2) elxr use cihsr
  831. // If environment is not specified defaults to development.
  832. // 1) NODE=test elxr use elixir
  833. /*// Steps
  834. 1) Delete Config and Data symlinks
  835. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  836. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  837. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  838. 5) Iterates all repos and merge from source configured in mergeSource. 'git', ['merge', mergeSource],
  839. */
  840. var runconfig = { NODE_ENV: repomanifest.node_env }
  841. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  842. if ((!processedArgs.runas || processedArgs.runas !== 'self') &&
  843. runconfig.NODE_ENV && runconfig.NODE_ENV === (repomanifest.node_env || runconfig.NODE_ENV) &&
  844. repomanifest.instanceName && runconfig.use === repomanifest.instanceName) {
  845. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  846. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  847. return
  848. }
  849. var tasks = [
  850. () => {
  851. if (existsSync('config')) {
  852. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  853. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  854. return p;
  855. }
  856. else return Promise.resolve(true);
  857. },
  858. () => {
  859. if (existsSync('data')) {
  860. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  861. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  862. return p;
  863. }
  864. else return Promise.resolve(true);
  865. },
  866. ];
  867. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  868. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  869. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  870. // console.log(process.env.cwd)
  871. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  872. // Maps an environment to a branch. Not required if the branch is appropriately named.
  873. var checkoutMap = { 'development': 'master' }
  874. // cant use git checkout -b it fails with branch already exists.
  875. var performCheckout = (repo, branch) => {
  876. if (!branch) return Promise.resolve({ 'skipped': true })
  877. if (excludeCheckouts[repo]) return Promise.resolve({ 'skipped': true })
  878. return nodeShellExec('git', ['checkout', branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  879. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  880. // inherit : true, shell: true,
  881. cwd: repoinstanceroot + '/' + repo
  882. // , stdio : ignore // Use when we want to silcence output completely.
  883. , runas: processedArgs.runas
  884. , title: `git checkout ${branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${repo}`
  885. }).catch((e) => { console.error(e); return { error: true, message: repo } })
  886. }
  887. if (runconfig.NODE_ENV === 'development') performCheckout = () => { return Promise.resolve(true) }
  888. var performPullAll = (repo) => {
  889. if (excludeCheckouts[repo]) return Promise.resolve({ 'skipped': true })
  890. return nodeShellExec('git', ['pull', '--all'], {
  891. // inherit : true, shell: true,
  892. cwd: instanceroot + '/' + repo
  893. , runas: processedArgs.runas
  894. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${repo}`
  895. }).catch((e) => { console.error(e); return { error: true, message: repo } })
  896. }
  897. var mergeSources = {
  898. 'development': null,
  899. 'test': 'master',
  900. 'production': 'master'
  901. }
  902. var excludeCheckouts = Object.assign(exludeMergeRepos)
  903. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  904. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  905. var mergeSource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  906. var performMerge = (repo) => {
  907. if (exludeMergeRepos[repo]) return Promise.resolve({ 'skipped': true })
  908. return nodeShellExec('git', ['merge', mergeSource], {
  909. inherit: true, shell: true,
  910. cwd: instanceroot + '/' + repo
  911. , runas: processedArgs.runas
  912. }).catch((e) => { console.error(e) })
  913. }
  914. if (runconfig.NODE_ENV === 'development') performMerge = () => { return Promise.resolve(true) }
  915. return any(tasks).then(() => {
  916. if (!processedArgs.runas) return op['runas']()
  917. tasks = [
  918. () => {
  919. // Use junctions to avoid npm package issues
  920. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  921. inherit: true, shell: true
  922. , cwd : instanceroot
  923. , env: process.env
  924. }).catch((e) => { console.error(e) })
  925. return p;
  926. }
  927. ];
  928. if (processedArgs._[1]) {
  929. tasks = tasks.concat(
  930. [
  931. () => {
  932. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  933. inherit: true, shell: true
  934. , cwd : instanceroot
  935. , env: process.env
  936. }).catch((e) => { console.error(e) })
  937. return p;
  938. }
  939. ]
  940. )
  941. }
  942. return any(tasks)
  943. //target is the env is we specify in elxr use command. Default is dev
  944. .then( //Switch to target branch
  945. () => any([any(gitRepos.map((repo) => performCheckout(repo, process.env.NODE_ENV || 'development')))
  946. , any(elevatedRunasRepos.map((repo) => performCheckout(repo, process.env.NODE_ENV || 'development')))]))
  947. .then( //PULL from target branch
  948. () => any([any(gitRepos.map((repo) => performPullAll(repo))), any(elevatedRunasRepos.map((repo) => performPullAll(repo)))]))
  949. .then( //Switch to merge source branch
  950. () => any([any(gitRepos.map((repo) => performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'])))
  951. , any(elevatedRunasRepos.map((repo) => performCheckout(repo, mergeSources[process.env.NODE_ENV || 'development'])))]))
  952. .then( //Pull on merge source branch
  953. () => any([any(gitRepos.map((repo) => performPullAll(repo))), any(elevatedRunasRepos.map((repo) => performPullAll(repo)))]))
  954. .then( //Switch to target branch
  955. () => any([any(gitRepos.map((repo) => performCheckout(repo, process.env.NODE_ENV || 'development')))
  956. , any(elevatedRunasRepos.map((repo) => performCheckout(repo, process.env.NODE_ENV || 'development')))]))
  957. .then( //Merge source branch to target branch
  958. () => any([any(gitRepos.map((repo) => performMerge(repo))).catch(err => { console.error('error in performMerge ' + err) }),
  959. any(elevatedRunasRepos.map((repo) => performMerge(repo))).catch(err => { console.error('error in performMerge ' + err) })]))
  960. .then(() => {
  961. // Move test config from dev.
  962. // if(process.env.NODE_ENV === 'test'){
  963. // var devcfgreponame = runconfig.use + '-config' + '-development';
  964. // var testcfgreponame = runconfig.use + '-config' + '-test';
  965. // var testcfgdir = path.dirname(__dirname) + '/' + testcfgreponame + '/'
  966. // var devcfgdir = path.dirname(__dirname) + '/' + devcfgreponame + '/' //eg (elxr/../elixir-config.development)
  967. // return any([
  968. // ()=>{
  969. // return nodeShellExec('git', ['checkout', 'test'], {
  970. // inherit : true, shell: true,
  971. // cwd : testcfgdir
  972. // // , env: process.env
  973. // , runas : processedArgs.runas
  974. // , title : `git checkout test for ${testcfgreponame}`
  975. // }).catch((e)=>{ console.error(e) })
  976. // }
  977. // , ()=> {
  978. // return nodeShellExec('git', ['checkout', 'master'], {
  979. // inherit : true, shell: true,
  980. // cwd : devcfgdir
  981. // // , env: process.env
  982. // , runas : processedArgs.runas
  983. // , title : `git checkout master for ${devcfgreponame}`
  984. // }).catch((e)=>{ console.error(e) })
  985. // }
  986. // , ()=> {
  987. // globSync( '**/*.test.js', {cwd : devcfgdir}).map((filename) => {
  988. // console.log('File found : ' + devcfgdir + filename)
  989. // fs.copyFileSync(devcfgdir + filename, testcfgdir+ filename);
  990. // })
  991. // return nodeShellExec('git', ['checkout', 'test'], {
  992. // inherit : true, shell: true,
  993. // cwd : devcfgdir
  994. // // , env: process.env
  995. // , runas : processedArgs.runas
  996. // , title : `git checkout test for ${devcfgreponame}`
  997. // }).catch((e)=>{ console.error(e) })
  998. // }
  999. // ])
  1000. // }
  1001. // else {
  1002. return Promise.resolve(true)
  1003. // }
  1004. })
  1005. .then(() => {
  1006. fs.writeFileSync('run.done', 'success')
  1007. }).catch(() => {
  1008. fs.writeFileSync('run.done', 'error')
  1009. })
  1010. }).catch(() => {
  1011. fs.writeFileSync('run.done', 'error')
  1012. })
  1013. // Antibiotic stewardship program.
  1014. // 1st use is fine.
  1015. // Max vials dispense
  1016. // 2nd use Pharmacy needs justification Form.
  1017. // Approval after a certain period of time.
  1018. }
  1019. , 'g': () => {
  1020. if (processedArgs.h) {
  1021. console.log('elxr g [modelname] => generate a model named [modelname]');
  1022. console.log('elxr g => regenerate all known models');
  1023. return
  1024. }
  1025. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1026. // console.log('Starting directory: ' + process.cwd());
  1027. // try {
  1028. // child = child.on('close', () => { process.chdir(label) } );
  1029. // console.log('New directory: ' + process.cwd());
  1030. // }
  1031. // catch (err) {
  1032. // console.log('chdir: ' + err);
  1033. // }
  1034. // child.on('close', function(){
  1035. // var options = {
  1036. // shell : true
  1037. // , inherit : true
  1038. // // , cwd : '' + process.cwd
  1039. // // , env : process.env
  1040. // };
  1041. // nodeShellExec('git', ['init'], { inherit : true});
  1042. if (0) {
  1043. // PB : TODO -- Special google chrome profile for tests etc.
  1044. nodeShellExec('pwd', { inherit: true });
  1045. // /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"
  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" http://localhost:4200/admin/crud/create/item
  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/tests/index.html?grep=loopback
  1048. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1049. "--profile-directory=Profile 1"
  1050. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1051. }
  1052. // nodeShellExec('npm', ['init', '-y'], options);
  1053. // nodeShellExec('npm', ['init', '-y'], options);
  1054. // })
  1055. var g = {
  1056. 'client': () => {
  1057. console.info('Creating new ember client named : ' + processedArgs._[2]);
  1058. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1059. stdio: ['pipe', process.stdout, process.stderr],
  1060. inherit: true,
  1061. shell: true,
  1062. cwd: path.dirname(__dirname),
  1063. env: env
  1064. })
  1065. },
  1066. 'modelr': () => {
  1067. var tasks = [
  1068. () => {
  1069. var p = nodeShellExec('"ember"', [
  1070. 'g'
  1071. , 'modelr'
  1072. , processedArgs._[2]], {
  1073. inherit: true, shell: true, env: process.env
  1074. }).then(() => {
  1075. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  1076. return true;
  1077. }).catch((e) => { console.error(e) })
  1078. return p;
  1079. },
  1080. () => {
  1081. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1082. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  1083. chromeprefs = JSON.parse(chromeprefs)
  1084. var previous = chromeprefs.download.default_directory;
  1085. var parentDir = path.dirname(__dirname);
  1086. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1087. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1088. // PB : TODO -- detect where chrome is installed.
  1089. // PB : TODO -- set the download dir to the place where files are needed.
  1090. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1091. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1092. , '--profile-directory="chess"'
  1093. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1094. inherit: true, shell: true
  1095. , env: process.env
  1096. }).then(() => {
  1097. chromeprefs.download.default_directory = previous;
  1098. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1099. return true;
  1100. }).catch((e) => { console.error(e) })
  1101. return p;
  1102. }
  1103. ,
  1104. () => {
  1105. console.log('Browser process should have closed here....')
  1106. return true;
  1107. }
  1108. ]
  1109. any(tasks)
  1110. }
  1111. }
  1112. g[processedArgs._[1]]();
  1113. }
  1114. }
  1115. var util = require('util')
  1116. var cliname = 'elxr';
  1117. var ver = '1.1';
  1118. var help = `# list of commands... please refer dveloper documentation for ${cliname}
  1119. ${
  1120. // util.inspect(
  1121. [Object.keys(op)]
  1122. // )
  1123. }
  1124. `;
  1125. var elxr = {
  1126. help() {
  1127. return chalk.cyanBright(`
  1128. -------------------------------------------------------------------------------
  1129. *** BBH Elixir ***
  1130. -------------------------------------------------------------------------------
  1131. elxr ${ver}
  1132. A cli tool for chess
  1133. ${help}
  1134. -------------------------------------------------------------------------------
  1135. `)
  1136. }
  1137. , info() {
  1138. return chalk.cyanBright(`
  1139. -------------------------------------------------------------------------------
  1140. *** BBH Elixir ***
  1141. -------------------------------------------------------------------------------
  1142. elxr ${ver}
  1143. A cli tool for chess
  1144. -------------------------------------------------------------------------------
  1145. `)
  1146. }
  1147. }
  1148. // The main elxr cli process
  1149. function elxrworker(hasconfig) {
  1150. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  1151. gitRepos = repomanifest.repos
  1152. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  1153. elevatedRunasRepos = repomanifest.elevated
  1154. // Repos that should excluded from merge for releases...
  1155. exludeMergeRepos = repomanifest.exludeMergeRepos
  1156. var env = Object.assign({}, process.env); // Shallow clone it.
  1157. var __runcmd = function (label) {
  1158. return op[label] ? op[label]() : null;
  1159. }
  1160. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  1161. // mysql -u root -p db_name < drop_all_tables.sql
  1162. var mysql = '../xampp/mysql/bin/mysql'
  1163. var mysqldump = '../xampp/mysql/bin/mysqldump'
  1164. // --runas
  1165. if (processedArgs.runas) {
  1166. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  1167. return __runcmd('runas')
  1168. }
  1169. else return __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  1170. }
  1171. var getManifest = function () {
  1172. // Once choices are made we need to load config according to those choices.
  1173. // No trace of a previous run...
  1174. // Default Config...
  1175. return repomanifest = selectedinstance;
  1176. }
  1177. function acquireChoices(selectedinstance) {
  1178. var hasconfig = false;
  1179. console.warn(chalk.yellow(`
  1180. -------------------------------------------------------------------------------
  1181. Warning : Cannot locate your preferred configuration since it was not specified
  1182. You should fork the default chess configuration to customize and make it
  1183. your own instance with a named config as
  1184. {{yourowninstancename}}-config-{{yourcurrentenvironment}}
  1185. And then run this tool as follows
  1186. NODE_ENV={{yourenvironment}} elxr i {{yourowninstancename}}
  1187. OR
  1188. Run this tool with the following command to use a quick start default.
  1189. node elxr --default
  1190. OR
  1191. Choose the the option to create a new instance for you interactively.
  1192. We will run your choice of default or create your own at the next prompt.
  1193. -------------------------------------------------------------------------------
  1194. `))
  1195. var prompt = cli.prompt;
  1196. return prompt.ask(`Choose an option :
  1197. d) Install the default chess instance.
  1198. => elxr i chess node_env=development --default
  1199. n) Create your custom new instance interactively
  1200. => elxr i {{instanceName}} node_env={{environment}}
  1201. i) Choose an instance and environment to install
  1202. => elxr i {{instanceName}} node_env={{environment}}
  1203. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  1204. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  1205. h) Help
  1206. q) Quit
  1207. Default <= d
  1208. : `).then((choice) => {
  1209. prompt.close();
  1210. if (choice && choice === 'd' || !choice) {
  1211. processedArgs._[0] = 'i'
  1212. selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  1213. selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  1214. defaultRepoServer = 'https://git.bbh.org.in'
  1215. getManifest() // PB : TODO -- acquire the manifest directly from http url instead of clone before cloning the config. Since
  1216. // This is because the manifest at any server location can redirect to the preferred server..
  1217. }
  1218. else if (choice === 'h') {
  1219. processedArgs._[0] = 'h'
  1220. fs.writeFileSync('run.done', 'noop help');
  1221. console.log(elxr.help()); process.exit()
  1222. }
  1223. else if (choice === 'n' || choice === 'i') {
  1224. var p1 = cli.prompt;
  1225. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1226. processedArgs._[0] = 'i'
  1227. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  1228. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1229. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1230. if (choice === 'n') {
  1231. defaultRepoServer = 'https://git.bbh.org.in'
  1232. console.warn(
  1233. chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  1234. process.exit();
  1235. }
  1236. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1237. p1.close()
  1238. defaultRepoServer = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1239. })
  1240. })
  1241. })
  1242. } else if (choice === 'c') {
  1243. var p1 = cli.prompt;
  1244. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1245. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  1246. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1247. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1248. return p1.ask(`Enter cmd :
  1249. p) pull
  1250. Default <= p
  1251. : `).then(function (cmd) {
  1252. if (!cmd || cmd === 'p') {
  1253. processedArgs._[0] = 'pull'
  1254. }
  1255. else processedArgs._[0] = cmd
  1256. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1257. defaultRepoServer = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1258. p1.close()
  1259. })
  1260. })
  1261. })
  1262. })
  1263. } else {
  1264. 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.`));
  1265. fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  1266. fs.writeFileSync('run.done', 'noop quit');
  1267. process.exit()
  1268. }
  1269. })
  1270. }
  1271. var acquireConfig = function (selected, chessinstances) {
  1272. var configrepo = selected.instanceName + '-config-' + selected.node_env;
  1273. return performPull(configrepo).then(() => {
  1274. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  1275. repomanifest = require(manifestpath)()
  1276. chessinstances = chessinstances || {};
  1277. chessinstances[selected.instanceName] = chessinstances[selected.instanceName] || {}
  1278. chessinstances[selected.instanceName][selected.node_env] = chessinstances[selected.instanceName][selected.node_env] || {}
  1279. chessinstances['current_run'] = { instanceName: selected.instanceName, node_env: selected.node_env }
  1280. // Config from server always override merges into selection ecept for the current selection.
  1281. selectedinstance = utils.assign(chessinstances[selected.instanceName][selected.node_env], selected, repomanifest)
  1282. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances) + '', { 'flag': 'w' })
  1283. // PB : TODO -- We should probably write the new server config also...
  1284. defaultRepoServer = selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  1285. ENV.NODE_ENV = selectedinstance.node_env;
  1286. })
  1287. .catch((e) => {
  1288. console.error(e)
  1289. console.error('Config acquisition failed.')
  1290. })
  1291. }
  1292. var launchpath = process.cwd().replace(/\\/, '/')
  1293. var thisscriptdir = __dirname
  1294. var instanceroot = launchpath;
  1295. var detectInstance = function () {
  1296. console.log(`launchpath = ${launchpath}`)
  1297. console.log(`thisscriptdir = ${thisscriptdir}`)
  1298. var root = launchpath;
  1299. // We need a reference to the root director for elxr cli to be properly oriented.
  1300. if ((launchpath + path.normalize('/elxr')) === thisscriptdir) {
  1301. // We ran unbuilt from the proper root with elxr subfolder.
  1302. console.log(`Instance Path : ${root}`)
  1303. }
  1304. else {
  1305. if (launchpath === thisscriptdir) {
  1306. // Same directory doesn't mean we are being run from elxr directory or the root directory.
  1307. // It could be a standalone elxr build which may or maynot be in the proper location.
  1308. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  1309. // Unbuilt therefore we are in the elxr directory.
  1310. root = path.normalize(launchpath + '/..');
  1311. }
  1312. else {
  1313. // Built version.
  1314. // check if we have a elxr subfolder.
  1315. if (fs.existsSync(launchpath + '/..' + path.normalize('/elxr'))) {
  1316. // Probably in the right place.
  1317. root = path.normalize(launchpath + '/..');
  1318. }
  1319. else {
  1320. // Assume launchpath is meaningless.
  1321. // Figure it out from the input instance name and environment parameters if we are in the right location.
  1322. root = path.normalize(launchpath + '/' + processedArgs._[1] + '/' + processedArgs.node_env)
  1323. }
  1324. }
  1325. }
  1326. }
  1327. instanceroot = root.replace(/\\/, '/');
  1328. var __default = {
  1329. // Default is public server only.
  1330. reposervers: ['https://git.bbh.org.in']
  1331. // All public repos are by default available.
  1332. , repos: [
  1333. 'setup'
  1334. , 'elxr'
  1335. , 'loopback-connector-mysql'
  1336. , 'loopback-jsonapi-model-serializer'
  1337. , 'loopback-component-jsonapi'
  1338. , 'ember-service-worker'
  1339. , 'ember-service-worker-asset-cache'
  1340. , 'ember-service-worker-cache-fallback'
  1341. , 'ember-service-worker-index'
  1342. , 'ember-sw-client-route'
  1343. ]
  1344. , elevated: []
  1345. , exludeMergeRepos: {}
  1346. , instanceName: 'chess'
  1347. // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
  1348. , node_env: 'development'
  1349. }
  1350. return Object.assign({ root }, __default);
  1351. }
  1352. var gitUser = 'chessdemo';
  1353. var gitEmail = 'chessdemo@bbh.org.in'
  1354. var downloadsdir = '../Downloads';
  1355. var prerequisites = [
  1356. {
  1357. shellcmd: 'git',
  1358. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  1359. , installer: 'Git-2.31.0-64-bit.exe'
  1360. , installcmd: ['cmd', ['/c', 'start',
  1361. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  1362. , '/VERYSILENT'
  1363. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  1364. ]]
  1365. , preinstallsteps: () => {
  1366. var prompt = cli.prompt;
  1367. var steps = [
  1368. () => {
  1369. if (!existsSync(downloadsdir + '/' + preq.installer)) {
  1370. return nodeShellExec('download.bat', [preq.url, downloadsdir + '/' + preq.installer])
  1371. }
  1372. else return Promise.resolve(true)
  1373. }
  1374. ]
  1375. var prompts = [
  1376. () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
  1377. , () => prompt.ask(`git user name : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
  1378. ]
  1379. return Promise.all([any(steps), any(prompts)]).finally(() => { prompt.close() })
  1380. }
  1381. , installsteps: function () {
  1382. return any([this.installcmd].map(callsheltask))
  1383. }
  1384. , postinstallsteps: () => {
  1385. var steps = [
  1386. ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  1387. , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  1388. ]
  1389. return any(steps.map(callsheltask)).then(() => { })
  1390. }
  1391. , install: function () {
  1392. return any([ /*this.preinstallsteps,*/ this.installsteps, this.postinstallsteps])
  1393. }
  1394. }
  1395. ,
  1396. {
  1397. shellcmd: 'node',
  1398. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  1399. , installer: 'node-v14.16.0-x64.msi'
  1400. , installcmd: ['MSIEXEC.exe', ['/i'
  1401. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  1402. , 'ACCEPT=YES', '/passive']]
  1403. }
  1404. ]
  1405. function ensureDirectoryExistence(filePath) {
  1406. var dirname = path.dirname(filePath);
  1407. if (fs.existsSync(dirname)) {
  1408. return filePath;
  1409. }
  1410. ensureDirectoryExistence(dirname);
  1411. fs.mkdirSync(dirname);
  1412. return filePath;
  1413. }
  1414. var mainTasks = [];
  1415. function verifyAndInstallPrerequisites() {
  1416. fs.writeFileSync(ensureDirectoryExistence(path.normalize(downloadsdir + '/readme.txt')), `${getVersion()} Your local downloads for this instance`)
  1417. var downloadbatch =
  1418. `::**************************************************************************
  1419. :Download_ <url> <File>
  1420. Powershell.exe ^
  1421. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  1422. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  1423. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  1424. exit /b
  1425. ::**************************************************************************`
  1426. fs.writeFileSync('download.bat', downloadbatch)
  1427. var downloadtasks = [];
  1428. var installtasks = [];
  1429. prerequisites.forEach(preq => {
  1430. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  1431. if (exists) console.log(`${preq.shellcmd} exists`)
  1432. else {
  1433. console.log(`${preq.shellcmd} is not installed`)
  1434. return preq.preinstallsteps().then(() => {
  1435. installtasks.push(task.install)
  1436. })
  1437. }
  1438. }))
  1439. })
  1440. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  1441. }
  1442. function initinstances(chessinstances, selected) {
  1443. chessinstances.current_run.instanceName = processedArgs._[1] = processedArgs._[1] || chessinstances.current_run.instanceName || selected.instanceName;
  1444. chessinstances.current_run.node_env = processedArgs.node_env = processedArgs.node_env || chessinstances.current_run.node_env || selected.node_env;
  1445. chessinstances[chessinstances.current_run.instanceName] = chessinstances[chessinstances.current_run.instanceName] || {}
  1446. selectedinstance = Object.assign(selected, chessinstances[chessinstances.current_run.instanceName][chessinstances.current_run.node_env], clioverrides);
  1447. repomanifest = selectedinstance
  1448. return chessinstances
  1449. }
  1450. function acquirelocalinstances(selected){
  1451. var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
  1452. return initinstances(chessinstances, selected)
  1453. }
  1454. function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  1455. var detectedInstance = detectInstance(); // From launch location etc.
  1456. var selectedinstance = detectedInstance
  1457. var clioverrides = { }
  1458. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  1459. processedArgs.node_env ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env
  1460. : (process.env.NODE_ENV && process.env.NODE_ENV.trim()) ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()): null;
  1461. var maintask = () => {
  1462. try {
  1463. // Default cmd to run !
  1464. var chessinstances = acquirelocalinstances(selectedinstance);
  1465. processedArgs._[0] === processedArgs._[0] || 'pull';
  1466. // defaultRepoServer = repomanifest.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available...
  1467. return acquireConfig(selectedinstance, chessinstances).catch((e) => {
  1468. console.error('Exisitng config Failed. Fix config and rerun or chose another.')
  1469. console.error(e);
  1470. }).then(() => { return elxrworker(true) })
  1471. }
  1472. catch (e) {
  1473. console.error(e)
  1474. // No local instances config found. We acquire user choices and proceed to reattempt.
  1475. chessinstances = {}
  1476. chessinstances.current_run = {}
  1477. initinstances(chessinstances, selectedinstance)
  1478. return acquireChoices(selectedinstance).then(() => {
  1479. try {
  1480. var chessinstances = acquirelocalinstances(selectedinstance)
  1481. }
  1482. catch (e) {
  1483. console.error(e)
  1484. console.error('No local instances config found in current root = ' + selectedinstance.root);
  1485. console.log('A config will be createed with the instance and environment chosen...')
  1486. }
  1487. finally {
  1488. return acquireConfig(selectedinstance, chessinstances).catch((e) => {
  1489. console.error('Chosen cofiguraton failed or not found')
  1490. console.error(e)
  1491. }).then(() => { return elxrworker(true) })
  1492. .finally(()=>{
  1493. fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  1494. fs.writeFileSync('run.done', 'error');
  1495. // return process.exit()
  1496. })
  1497. }
  1498. })
  1499. }
  1500. }
  1501. acquireElevationState().then(() => {
  1502. var skipprerequisites = false
  1503. if (!skipprerequisites && !__isElevated) mainTasks.push(verifyAndInstallPrerequisites);
  1504. mainTasks.push(maintask)
  1505. return any(mainTasks);
  1506. })
  1507. // detect if alread installed -> Take no action.
  1508. // download if no installer avalable -> next()
  1509. // install
  1510. function chackandinstall(items) {
  1511. var tasks = []
  1512. items.forEach(item => {
  1513. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  1514. })
  1515. return Promise.all(tasks).then(existances => {
  1516. existances.forEach((exists, i) => {
  1517. if (!exists) {
  1518. return downloadandinstall([items[i]])
  1519. }
  1520. })
  1521. })
  1522. }
  1523. function downloadandinstall(items) {
  1524. var tasks = []
  1525. items.forEach(item => {
  1526. tasks.push(getTaskDownload(item))
  1527. })
  1528. return Promise.all(tasks)
  1529. }
  1530. // Sample instances config.
  1531. // var instances = {
  1532. // "elixir": {
  1533. // "production": {
  1534. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  1535. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  1536. // , "exludeMergeRepos": {
  1537. // "elixir-config-development": true, "elixir-config-test": true
  1538. // , "elixir-config-production": true, "elixir-data": true
  1539. // }
  1540. // , "instanceName": "elixir", "node_env": "production"
  1541. // }
  1542. // },
  1543. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  1544. // }