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

index.js 64KB

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