555
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

index.js 71KB

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