Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

index.js 70KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914
  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. , 'use' : () => {
  852. // use a certain named instance.
  853. // Eg :
  854. // 1) elxr use elixir
  855. // 2) elxr use cihsr
  856. // If environment is not specified defaults to development.
  857. // 1) NODE=test elxr use elixir
  858. /*// Steps
  859. 1) Delete Config and Data symlinks
  860. 2) Make Links for config ({{name}}-config-{{node_env}}) and data with the NODE_ENV specified or default to dev
  861. 3) Iterates all repos and pull all. 'git', ['pull', '--all'].
  862. 4) Iterates all repos and checkout to the ENV specified. 'git', ['checkout', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  863. 5) Iterates all repos and merge from source configured in mergesource. 'git', ['merge', mergesource],
  864. */
  865. var runconfig = { NODE_ENV: repomanifest.node_env }
  866. try { runconfig = Object.assign(runconfig, require(instanceroot + '/run.js')) } catch (e) { }
  867. if ((!processedArgs.runas || processedArgs.runas !== 'self' && !processedArgs.force) &&
  868. runconfig.NODE_ENV && runconfig.NODE_ENV === (repomanifest.node_env || runconfig.NODE_ENV) &&
  869. repomanifest.instanceName && runconfig.use === repomanifest.instanceName) {
  870. console.log(`No change detected. Already using requested specs : ${runconfig.NODE_ENV} ${runconfig.use}`)
  871. if (processedArgs.runas) { fs.writeFileSync('run.done', 'success') }
  872. return
  873. }
  874. var tasks = [
  875. () => {
  876. if (existsSync('config')) {
  877. var p = nodeShellExec('rmdir', ['config'], { inherit: true, shell: true, env: process.env }
  878. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  879. return p;
  880. }
  881. else return Promise.resolve(true);
  882. },
  883. () => {
  884. if (existsSync('data')) {
  885. var p = nodeShellExec('rmdir', ['data'], { inherit: true, shell: true, env: process.env }
  886. ).catch((err) => { console.log('Ignoring benign error : ' + err); return true; })
  887. return p;
  888. }
  889. else return Promise.resolve(true);
  890. },
  891. ];
  892. runconfig.NODE_ENV = process.env.NODE_ENV = process.env.NODE_ENV || runconfig.NODE_ENV || 'development';
  893. if (processedArgs._[1] && runconfig.use !== processedArgs._[1]) runconfig.use = processedArgs._[1];
  894. if (!runconfig.use) { throw 'unspecifed use not allowed. Please specify chess instance name.' }
  895. // console.log(process.env.cwd)
  896. fs.writeFileSync(instanceroot + '/run.js', 'module.exports = ' + JSON.stringify(runconfig))
  897. // Maps an environment to a branch. Not required if the branch is appropriately named.
  898. var checkoutMap = { 'development': 'master' }
  899. var branch = checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV
  900. var performPullOrCloneForBranch = (def)=>{
  901. var promise = Promise.resolve(true)
  902. if (!branch) {
  903. var dscoverbranchcmd = gitops.getdiscoverbranchcmd(repo)
  904. promise = nodeShellExec.apply(null, dscoverbranchcmd(repo)).then(__branch=>{ branch = __branch})
  905. .catch((e) => { console.error(e); return { error: true, message: repo } })
  906. }
  907. return promise = promise.then(()=>{ return elxr.getpulltask(def)() }).catch(e => { console.error( 'performPullOrCloneForBranch : Failed ' + e )})
  908. }
  909. // cant use git checkout -b it fails when branch already exists.
  910. var performCheckout = (def) => {
  911. if (excludeCheckouts[repo]) return Promise.resolve({ 'skipped': true })
  912. return performPullOrCloneForBranch(def)().then(()=>{
  913. nodeShellExec('git', ['checkout', def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  914. // return nodeShellExec('git', ['switch', '-m', '-C', checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV], {
  915. // inherit : true, shell: true,
  916. cwd: instanceroot + '/' + def.repo
  917. // , stdio : ignore // Use when we want to silence output completely.
  918. , runas: processedArgs.runas
  919. , title: `git checkout ${def.branch || checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} for ${def.repo}`
  920. }).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 } })
  921. })
  922. }
  923. var enqueueCheckout = function(def){ enqueue(elevatedqueue, performCheckout, def) }
  924. var enqueueMerge = function(def){ enqueue(elevatedqueue, performMerge, def) }
  925. var elevatedqueue = [];
  926. var enqueueOnce = (queue, task, def) => {
  927. var found = queue.find(element => {
  928. var keys = Object.keys( element )
  929. for(var k=0; k < keys.length; k++) {
  930. if(element[keys[k]] !== def[k]) return false;
  931. }
  932. })
  933. queue.push(function(){ return task(this)}.bind(def));
  934. }
  935. var enqueue = (queue, task, def) => {
  936. queue.push(function(){ return task(def)}.bind(def));
  937. }
  938. if (runconfig.NODE_ENV === 'development') performCheckout = (def) => { return performPullOrCloneForBranch(def) }
  939. var performPullAll = (def) => {
  940. if (excludeCheckouts[def.repo]) return Promise.resolve({ 'skipped': true })
  941. return nodeShellExec('git', ['pull', '--all'], {
  942. // inherit : true, shell: true,
  943. cwd: instanceroot + '/' + def.repo
  944. , runas: processedArgs.runas
  945. , title: `git pull -all for ${checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV} ${def.repo}`
  946. }).catch((e) => { console.error(e); return { error: true, message: def.repo } })
  947. }
  948. var mergeSources = {
  949. 'development': null,
  950. 'test': 'master',
  951. 'production': 'master'
  952. }
  953. var excludeCheckouts = Object.assign(exludeMergeRepos)
  954. delete excludeCheckouts[`elixir-config-${runconfig.NODE_ENV}`]
  955. delete excludeCheckouts[`cihsr-config-${runconfig.NODE_ENV}`]
  956. var mergesource = mergeSources[checkoutMap[runconfig.NODE_ENV] || runconfig.NODE_ENV]
  957. var performMerge = (def) => {
  958. if (exludeMergeRepos[def.repo]) return Promise.resolve({ 'skipped': true })
  959. return nodeShellExec('git', ['merge', mergesource], {
  960. inherit: true, shell: true,
  961. cwd: instanceroot + '/' + def.repo
  962. , runas: processedArgs.runas
  963. }).catch((e) => { console.error(e) })
  964. }
  965. if (runconfig.NODE_ENV === 'development') performMerge = () => { return Promise.resolve(true) }
  966. var performRepoOperation = function(def) {
  967. elevatedRunasRepos.map((repo) => enqueueCheckout({ repo, branch: def.branch, requiresElevation : true }))
  968. return any(gitRepos.map((repo) => performCheckout({ repo, branch: def.branch})))
  969. }
  970. return any(tasks).then(() => {
  971. var pr = Promise.resolve(true)
  972. if (!__isElevated) {
  973. pr = op['runas']()
  974. return pr.then(()=>{
  975. //target is the env is we specify in elxr use command. Default is dev
  976. //Switch to target branch
  977. return any(gitRepos.map((repo) => performCheckout({ repo, branch})))
  978. // pull or clone target branch
  979. .then(() => any(gitRepos.map((repo) => performPullAll({repo}))) )
  980. // switch to source branch
  981. .then( () => {
  982. if(mergesource) return any(gitRepos.map((repo) => performCheckout({ repo, branch: mergesource})))
  983. else return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  984. })
  985. //Pull on merge source branch
  986. .then( () => {
  987. if(!mergesource) return Promise.resolve(true)
  988. return any(gitRepos.map((repo) => performPullAll({repo})))
  989. })
  990. //Switch to target branch
  991. .then( () => {
  992. if(!mergesource) return Promise.resolve(true)
  993. return any(elevatedRunasRepos.map((repo) => performCheckout({ repo, branch})))
  994. })
  995. .then( //Merge source branch to target branch
  996. () => {
  997. if(!mergesource) return Promise.resolve(true)
  998. return any(gitRepos.map((repo) => performMerge({ repo }))).catch(err => { console.error('error in performMerge ' + err) })
  999. })
  1000. })
  1001. }
  1002. else {
  1003. tasks = [
  1004. () => {
  1005. // Use junctions to avoid npm package issues
  1006. var p = nodeShellExec('mklink', ['/J', 'config', runconfig.use + '-config' + '-' + process.env.NODE_ENV], {
  1007. inherit: true, shell: true
  1008. , cwd : instanceroot
  1009. , env: process.env
  1010. }).catch((e) => { console.error(e) })
  1011. return p;
  1012. }
  1013. ];
  1014. if (processedArgs._[1]) {
  1015. tasks = tasks.concat(
  1016. [
  1017. () => {
  1018. var p = nodeShellExec('mklink', ['/J', 'data', runconfig.use + '-data'], {
  1019. inherit: true, shell: true
  1020. , cwd : instanceroot
  1021. , env: process.env
  1022. }).catch((e) => { console.error(e) })
  1023. return p;
  1024. }
  1025. ]
  1026. )
  1027. }
  1028. return any(tasks).then(()=>{
  1029. return any(elevatedRunasRepos.map((repo) => performCheckout({ repo, branch})))
  1030. // pull or clone target branch
  1031. .then( () => any(elevatedRunasRepos.map((repo) => performPullAll({repo}))) )
  1032. // switch to source branch
  1033. .then( () => {
  1034. if(mergesource) return any(elevatedRunasRepos.map((repo) => performCheckout({ repo, branch: mergesource})))
  1035. else return Promise.resolve(true) // Dont do anything if there is no source to merge from.
  1036. })
  1037. //Pull on merge source branch
  1038. .then( () => {
  1039. if(!mergesource) return Promise.resolve(true)
  1040. return any(elevatedRunasRepos.map((repo) => performPullAll({repo})))
  1041. })
  1042. //Switch to target branch
  1043. .then( () => {
  1044. if(!mergesource) return Promise.resolve(true)
  1045. return any(elevatedRunasRepos.map((repo) => performCheckout({ repo, branch})))
  1046. })
  1047. .then( //Merge source branch to target branch
  1048. () => {
  1049. if(!mergesource) return Promise.resolve(true)
  1050. return any(elevatedRunasRepos.map((repo) => performMerge({ repo }))).catch(err => { console.error('error in performMerge ' + err) })
  1051. })
  1052. .then(() => {
  1053. fs.writeFileSync('run.done', 'success')
  1054. }).catch(() => {
  1055. fs.writeFileSync('run.done', 'error')
  1056. })
  1057. })
  1058. }
  1059. }).catch(() => {
  1060. fs.writeFileSync('run.done', 'error')
  1061. })
  1062. // Antibiotic stewardship program.
  1063. // 1st use is fine.
  1064. // Max vials dispense
  1065. // 2nd use Pharmacy needs justification Form.
  1066. // Approval after a certain period of time.
  1067. }
  1068. , 'g': () => {
  1069. if (processedArgs.h) {
  1070. console.log('elxr g [modelname] => generate a model named [modelname]');
  1071. console.log('elxr g => regenerate all known models');
  1072. return
  1073. }
  1074. // var child = nodeShellExec('mkdir', ['-p', label], { inherit : true} );
  1075. // console.log('Starting directory: ' + process.cwd());
  1076. // try {
  1077. // child = child.on('close', () => { process.chdir(label) } );
  1078. // console.log('New directory: ' + process.cwd());
  1079. // }
  1080. // catch (err) {
  1081. // console.log('chdir: ' + err);
  1082. // }
  1083. // child.on('close', function(){
  1084. // var options = {
  1085. // shell : true
  1086. // , inherit : true
  1087. // // , cwd : '' + process.cwd
  1088. // // , env : process.env
  1089. // };
  1090. // nodeShellExec('git', ['init'], { inherit : true});
  1091. if (0) {
  1092. // PB : TODO -- Special google chrome profile for tests etc.
  1093. nodeShellExec('pwd', { inherit: true });
  1094. // /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"
  1095. // "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
  1096. // "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
  1097. nodeShellExec("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", [
  1098. "--profile-directory=Profile 1"
  1099. , 'http://localhost:4200/tests/index.html?grep=model convert ember to loopback' + '&filter=none' /*+ '&filter=model convert ember to loopback'*/]);
  1100. }
  1101. // nodeShellExec('npm', ['init', '-y'], options);
  1102. // nodeShellExec('npm', ['init', '-y'], options);
  1103. // })
  1104. var g = {
  1105. 'client': () => {
  1106. console.info('Creating new ember client named : ' + processedArgs._[2]);
  1107. var step1 = nodeShellExec('cmd', ['/c', 'ember', 'new', processedArgs._[2]], {
  1108. stdio: ['pipe', process.stdout, process.stderr],
  1109. inherit: true,
  1110. shell: true,
  1111. cwd: path.dirname(__dirname),
  1112. env: env
  1113. })
  1114. },
  1115. 'modelr': () => {
  1116. var tasks = [
  1117. () => {
  1118. var p = nodeShellExec('"ember"', [
  1119. 'g'
  1120. , 'modelr'
  1121. , processedArgs._[2]], {
  1122. inherit: true, shell: true, env: process.env
  1123. }).then(() => {
  1124. console.log('Blueprint generation complete for : ' + processedArgs._[2])
  1125. return true;
  1126. }).catch((e) => { console.error(e) })
  1127. return p;
  1128. },
  1129. () => {
  1130. var chromePrefsFile = "C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data\\chess\\Preferences";
  1131. var chromeprefs = fs.readFileSync(chromePrefsFile, { encoding: 'utf8' })
  1132. chromeprefs = JSON.parse(chromeprefs)
  1133. var previous = chromeprefs.download.default_directory;
  1134. var parentDir = path.dirname(__dirname);
  1135. chromeprefs.download.default_directory = parentDir + "\\client\\app\\templates\\components\\resource";
  1136. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1137. // PB : TODO -- detect where chrome is installed.
  1138. // PB : TODO -- set the download dir to the place where files are needed.
  1139. var p = nodeShellExec('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe"', [
  1140. '--user-data-dir="C:\\chess\\instances\\elixir_01\\data\\Google\\Chrome\\User Data"'
  1141. , '--profile-directory="chess"'
  1142. , 'http://localhost:4200/admin/crud/create/' + processedArgs._[2]], {
  1143. inherit: true, shell: true
  1144. , env: process.env
  1145. }).then(() => {
  1146. chromeprefs.download.default_directory = previous;
  1147. fs.writeFileSync(chromePrefsFile, JSON.stringify(chromeprefs))
  1148. return true;
  1149. }).catch((e) => { console.error(e) })
  1150. return p;
  1151. }
  1152. ,
  1153. () => {
  1154. console.log('Browser process should have closed here....')
  1155. return true;
  1156. }
  1157. ]
  1158. any(tasks)
  1159. }
  1160. }
  1161. g[processedArgs._[1]]();
  1162. }
  1163. }
  1164. var util = require('util')
  1165. var cliname = 'elxr';
  1166. var ver = '1.1';
  1167. var help = `# list of commands... please refer dveloper documentation for ${cliname}
  1168. ${
  1169. // util.inspect(
  1170. [Object.keys(op)]
  1171. // )
  1172. }
  1173. `;
  1174. var elxr = {
  1175. help() {
  1176. return chalk.cyanBright(`
  1177. -------------------------------------------------------------------------------
  1178. *** BBH Elixir ***
  1179. -------------------------------------------------------------------------------
  1180. elxr ${ver}
  1181. A cli tool for chess
  1182. ${help}
  1183. -------------------------------------------------------------------------------
  1184. `)
  1185. }
  1186. , info() {
  1187. return chalk.cyanBright(`
  1188. -------------------------------------------------------------------------------
  1189. *** BBH Elixir ***
  1190. -------------------------------------------------------------------------------
  1191. elxr ${ver}
  1192. A cli tool for chess
  1193. -------------------------------------------------------------------------------
  1194. `)
  1195. }
  1196. , getpulltask(def){
  1197. console.log(`-------------------Processing pull for : ${def.repo} ${def.branch}`)
  1198. console.dir(def)
  1199. var env = Object.assign({}, process.env); // Shallow clone it.
  1200. console.log('Running exlr pull : ' + path.dirname(__dirname))
  1201. var useGitPull = processedArgs.useGitPull || false;
  1202. if(def.elevatedRepos || def.reqularRepos) {
  1203. if(def.elevatedRepos) def.requiresElevation = true;
  1204. else delete def.requiresElevation;
  1205. }
  1206. else {
  1207. if(def.requiresElevation) def.elevatedRepos = [def]
  1208. else def.reqularRepos = [def]
  1209. }
  1210. var elevatedpulltasks = null;
  1211. var regularpulltasks = function(){ return Promise.resolve(true) }
  1212. if(def.elevatedRepos){
  1213. elevatedpulltasks = function() {
  1214. return any(def.elevatedRepos.map((def) => performPull(def.repo))).then(() => {
  1215. fs.writeFileSync('run.done', 'success')
  1216. return true;
  1217. }).catch(() => { fs.writeFileSync('run.done', 'error') })
  1218. }
  1219. }
  1220. if(def.reqularRepos) {
  1221. var regularpulltasks = function(){
  1222. var pendingpulls = [];
  1223. def.reqularRepos.forEach((def) => { pendingpulls.push(performPull(def.repo)) })
  1224. return Promise.all(pendingpulls).finally(Traq.finally)
  1225. }
  1226. }
  1227. if(elevatedpulltasks) return getTaskWithElevation( { elevatedpulltasks, regularpulltasks} )
  1228. else return getTaskWithoutElevation({ regularpulltasks})
  1229. }
  1230. }
  1231. // The main elxr cli process
  1232. function elxrworker() {
  1233. // Everything runs after this check is completed. Elevation occurs out of process when needed.
  1234. gitRepos = repomanifest.repos
  1235. // gitRepos = ['chess-server-lib'];
  1236. // Repositiories that have symlinks that require elevated priviletes in windows to create symlinks
  1237. elevatedRunasRepos = repomanifest.elevated
  1238. // Repos that should excluded from merge for releases...
  1239. exludeMergeRepos = repomanifest.exludeMergeRepos
  1240. var env = Object.assign({}, process.env); // Shallow clone it.
  1241. var __runcmd = function (label) {
  1242. return op[label] ? op[label]() : null;
  1243. }
  1244. // mysqldump --add-drop-table --no-data -u root -p db_name | grep 'DROP TABLE' ) > drop_all_tables.sql
  1245. // mysql -u root -p db_name < drop_all_tables.sql
  1246. var mysql = '../xampp/mysql/bin/mysql'
  1247. var mysqldump = '../xampp/mysql/bin/mysqldump'
  1248. // --runas
  1249. if (processedArgs.runas) {
  1250. // Weve been asked to run in priviledged mode. Check if we already are privileged.
  1251. return __runcmd('runas')
  1252. }
  1253. else return __runcmd(processedArgs.label || processedArgs._[0] || 'h');
  1254. }
  1255. var getManifest = function () {
  1256. // Once choices are made we need to load config according to those choices.
  1257. // No trace of a previous run...
  1258. // Default Config...
  1259. return repomanifest = selectedinstance;
  1260. }
  1261. function acquireChoices(selectedinstance) {
  1262. var hasconfig = false;
  1263. console.warn(chalk.yellow(`
  1264. -------------------------------------------------------------------------------
  1265. Warning : Cannot locate your preferred configuration since it was not specified
  1266. You should fork the default chess configuration to customize and make it
  1267. your own instance with a named config as
  1268. {{yourowninstancename}}-config-{{yourcurrentenvironment}}
  1269. And then run this tool as follows
  1270. NODE_ENV={{yourenvironment}} elxr i {{yourowninstancename}}
  1271. OR
  1272. Run this tool with the following command to use a quick start default.
  1273. node elxr --default
  1274. OR
  1275. Choose the the option to create a new instance for you interactively.
  1276. We will run your choice of default or create your own at the next prompt.
  1277. -------------------------------------------------------------------------------
  1278. `))
  1279. var prompt = cli.prompter;
  1280. return prompt.ask(`Choose an option :
  1281. d) Install the default chess instance.
  1282. => elxr i chess node_env=development --default
  1283. n) Create your custom new instance interactively
  1284. => elxr i {{instanceName}} node_env={{environment}}
  1285. i) Choose an instance and environment to install
  1286. => elxr i {{instanceName}} node_env={{environment}}
  1287. c) Choose a command to run ( pull, use, i, npmi ... ) <= pull
  1288. => elxr {{cmd}} {{instanceName}} node_env={{environment}}
  1289. h) Help
  1290. q) Quit
  1291. Default <= d
  1292. : `).then((choice) => {
  1293. prompt.close();
  1294. if (choice && choice === 'd' || !choice) {
  1295. processedArgs._[0] = 'i'
  1296. selectedinstance.instanceName = processedArgs._[1] = processedArgs._[1] || 'chess'
  1297. selectedinstance.node_env = processedArgs.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env || 'development'
  1298. selectedinstance.reposerver = 'https://git.bbh.org.in'
  1299. getManifest() // PB : TODO -- acquire the manifest directly from http url instead of clone before cloning the config. Since
  1300. // This is because the manifest at any server location can redirect to the preferred server..
  1301. }
  1302. else if (choice === 'h') {
  1303. processedArgs._[0] = 'h'
  1304. fs.writeFileSync('run.done', 'noop help');
  1305. console.log(elxr.help()); process.exit()
  1306. }
  1307. else if (choice === 'n' || choice === 'i') {
  1308. var p1 = cli.prompter;
  1309. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1310. processedArgs._[0] = 'i'
  1311. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName;
  1312. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1313. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1314. if (choice === 'n') {
  1315. selectedinstance.reposerver = 'https://git.bbh.org.in'
  1316. console.warn(
  1317. chalk.magenta('No Option Available. Your account may not have privileges. You can request here http://git.bbh.org.in/chess'))
  1318. process.exit();
  1319. }
  1320. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1321. p1.close()
  1322. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1323. })
  1324. })
  1325. })
  1326. } else if (choice === 'c') {
  1327. var p1 = cli.prompter;
  1328. return p1.ask(`Enter Instance Name ( <= ${selectedinstance.instanceName} ) : `).then(function (instanceName) {
  1329. selectedinstance.instanceName = processedArgs._[1] = instanceName || selectedinstance.instanceName
  1330. return p1.ask(`Enter Environment ( <= ${selectedinstance.node_env} ) : `).then(function (node_env) {
  1331. selectedinstance.node_env = processedArgs.node_env = node_env || selectedinstance.node_env
  1332. return p1.ask(`Enter cmd :
  1333. p) pull
  1334. Default <= p
  1335. : `).then(function (cmd) {
  1336. if (!cmd || cmd === 'p') {
  1337. processedArgs._[0] = 'pull'
  1338. }
  1339. else processedArgs._[0] = cmd
  1340. return p1.ask(`Enter preferred repo server ( <= ${selectedinstance.reposerver || selectedinstance.reposervers[0]} ) : `).then(function (reposerver) {
  1341. selectedinstance.reposerver = reposerver || selectedinstance.reposervers[0] || 'https://git.bbh.org.in'
  1342. p1.close()
  1343. })
  1344. })
  1345. })
  1346. })
  1347. } else {
  1348. 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.`));
  1349. fs.writeFileSync('run.log', ', ' + JSON.stringify({ success: 'quit without execution' }), { 'flag': 'a+' })
  1350. fs.writeFileSync('run.done', 'noop quit');
  1351. process.exit()
  1352. }
  1353. })
  1354. }
  1355. var acquireConfig = function (selected, chessinstances) {
  1356. var configrepo = selected.instanceName + '-config-' + selected.node_env;
  1357. return performPull(configrepo).then(() => {
  1358. var manifestpath = path.normalize(selected.root + '/' + selected.instanceName + '-config-' + selected.node_env + '/repo-manifest');
  1359. repomanifest = require(manifestpath)()
  1360. chessinstances = chessinstances || {};
  1361. chessinstances[selected.instanceName] = chessinstances[selected.instanceName] || {}
  1362. chessinstances[selected.instanceName][selected.node_env] = chessinstances[selected.instanceName][selected.node_env] || {}
  1363. chessinstances['current_run'] = { instanceName: selected.instanceName, node_env: selected.node_env }
  1364. // Config from server always override merges into selection ecept for the current selection.
  1365. selectedinstance = utils.assign(chessinstances[selected.instanceName][selected.node_env], selected, repomanifest)
  1366. fs.writeFileSync(instanceroot + '/chessinstances.js', 'module.exports = ' + JSON.stringify(chessinstances, null, 2) + '', { 'flag': 'w' })
  1367. // PB : TODO -- We should probably write the new server config also...
  1368. selectedinstance.reposerver = selectedinstance.reposerver || selectedinstance.reposervers[0] // PB : TODO -- Attempt first one that is available and online...
  1369. ENV.NODE_ENV = selectedinstance.node_env;
  1370. })
  1371. .catch((e) => {
  1372. console.error(e)
  1373. console.error('Config acquisition failed.')
  1374. })
  1375. }
  1376. var launchpath = process.cwd().replace(/\\/, '/')
  1377. var thisscriptdir = __dirname
  1378. var instanceroot = launchpath;
  1379. var detectInstance = function () {
  1380. console.log(`launchpath = ${launchpath}`)
  1381. console.log(`thisscriptdir = ${thisscriptdir}`)
  1382. var root = launchpath;
  1383. // We need a reference to the root director for elxr cli to be properly oriented.
  1384. if ((launchpath + path.normalize('/elxr')) === thisscriptdir) {
  1385. // We ran unbuilt from the proper root with elxr subfolder.
  1386. console.log(`Instance Path : ${root}`)
  1387. }
  1388. else {
  1389. if (launchpath === thisscriptdir) {
  1390. // Same directory doesn't mean we are being run from elxr directory or the root directory.
  1391. // It could be a standalone elxr build which may or maynot be in the proper location.
  1392. if (BUILD_VERSION.indexOf('Version: {version} - built on {date}') > -1) {
  1393. // Unbuilt therefore we are in the elxr directory.
  1394. root = path.normalize(launchpath + '/..');
  1395. }
  1396. else {
  1397. // Built version.
  1398. // check if we have a elxr subfolder.
  1399. if (fs.existsSync(launchpath + '/..' + path.normalize('/elxr'))) {
  1400. // Probably in the right place.
  1401. root = path.normalize(launchpath + '/..');
  1402. }
  1403. else {
  1404. // Assume launchpath is meaningless.
  1405. // Figure it out from the input instance name and environment parameters if we are in the right location.
  1406. root = path.normalize(launchpath + '/' + processedArgs._[1] + '/' + processedArgs.node_env)
  1407. }
  1408. }
  1409. }
  1410. }
  1411. instanceroot = root.replace(/\\/, '/');
  1412. __default.root = root;
  1413. return Promise.resolve(__default);
  1414. }
  1415. //
  1416. var __default = {
  1417. // Default is public server only.
  1418. // All public repos are by default available.
  1419. reposervers: ['https://git.bbh.org.in']
  1420. , repos: [
  1421. 'setup'
  1422. , 'elxr'
  1423. , 'loopback-connector-mysql'
  1424. , 'loopback-jsonapi-model-serializer'
  1425. , 'loopback-component-jsonapi'
  1426. , 'ember-service-worker'
  1427. , 'ember-service-worker-asset-cache'
  1428. , 'ember-service-worker-cache-fallback'
  1429. , 'ember-service-worker-index'
  1430. , 'ember-sw-client-route'
  1431. ]
  1432. , elevated: []
  1433. , exludeMergeRepos: {}
  1434. , instanceName: 'chess'
  1435. // Runas windowshta clobbers and removes the NODE_ENV !!! We therefore pass it in.
  1436. , node_env: 'development'
  1437. }
  1438. var __interactve_promts = {
  1439. get reposerver(){
  1440. return cli.prompt(this.reposervers, 'git default repo').then(reposerver => {
  1441. Object.defineProperty(this, 'reposerver', {
  1442. value: reposerver,
  1443. writable: false,
  1444. configurable : true
  1445. });
  1446. return reposerver
  1447. })
  1448. }
  1449. , set reposerver(reposerver){
  1450. Object.defineProperty(this, 'reposerver', {
  1451. value: reposerver,
  1452. writable: false,
  1453. configurable : true
  1454. });
  1455. return reposerver
  1456. }
  1457. }
  1458. var downloadsdir = '../Downloads';
  1459. var prerequisites = [
  1460. {
  1461. shellcmd: 'git',
  1462. url: 'https://github.com/git-for-windows/git/releases/download/v2.31.0.windows.1/Git-2.31.0-64-bit.exe'
  1463. , installer: 'Git-2.31.0-64-bit.exe'
  1464. , installcmd: ['cmd', ['/c', 'start',
  1465. '/WAIT', path.resolve(downloadsdir + '/' + 'Git-2.31.0-64-bit.exe')
  1466. , '/VERYSILENT'
  1467. // , '/MERGETASKS=!runcode' // This is required only for vscode...
  1468. ]]
  1469. , preinstallsteps: function() {
  1470. var prompt = cli.prompter;
  1471. var steps = [
  1472. () => {
  1473. if (!existsSync(downloadsdir + '/' + this.installer)) {
  1474. return nodeShellExec('download.bat', [this.url, downloadsdir + '/' + this.installer])
  1475. }
  1476. else return Promise.resolve(true)
  1477. }
  1478. ]
  1479. var prompts = [
  1480. () => prompt.ask(`git user name : ( <= ${gitUser} )`).then((user) => { gitUser = user; })
  1481. , () => prompt.ask(`git email : ( <= ${gitEmail} )`).then((email) => { gitEmail = email; })
  1482. ]
  1483. return any([any(steps), any(prompts)]).then(() => { prompt.close() })
  1484. }
  1485. , installsteps: function () {
  1486. return any([this.installcmd].map(callsheltask))
  1487. }
  1488. , postinstallsteps: function(){
  1489. var prompt = cli.prompter;
  1490. var gitUser = 'guest';
  1491. var gitEmail = 'guest@bbh.org.in';
  1492. var prompts = [];
  1493. prompts.push(
  1494. ()=>{
  1495. var choices = { 0 : 'guest', 1 : 'chessdemo' }
  1496. return cli.prompt(choices, 'git user name').then(gituser => gitUser = gituser)
  1497. }
  1498. )
  1499. prompts.push(
  1500. ()=>{
  1501. var choices = { 0 : 'guest@bbh.org.in', 1 : 'chessdemo@bbh.org.in' }
  1502. return cli.prompt(choices, 'git user email').then(gitemail => gitEmail = gitemail)
  1503. }
  1504. )
  1505. return any(prompts).then(()=>{
  1506. var steps = [
  1507. ['git', ['config', '--global', '--add', 'user.name', `${gitUser}`]]
  1508. , ['git', ['config', '--global', '--add', 'user.email', `${gitEmail}`]]
  1509. ]
  1510. return any(steps.map(callsheltask)).then(() => {
  1511. })
  1512. });
  1513. }
  1514. , install: function () {
  1515. return any([ /*this.preinstallsteps,*/ this.installsteps.bind(this), this.postinstallsteps.bind(this)])
  1516. }
  1517. , verifyAndInstall : function(){
  1518. return getTaskCheckExists(this.shellcmd, { ignorefailures: true })().then((exists) => {
  1519. if(exists) {
  1520. // return any(['git', ['config', '--global', '-l']].map(callsheltask))
  1521. return this.getUser(null, this.postinstallsteps.bind(this))
  1522. }
  1523. return this.install();
  1524. });
  1525. }
  1526. , getUser : function(repo, onNoResult){
  1527. onNoResult = onNoResult || function(){return false}
  1528. var globalOrLocal = '--global';
  1529. if(!repo) globalOrLocal = '--global';
  1530. else globalOrLocal = '--local'
  1531. return any([['git', ['config', globalOrLocal, '--get-all', 'user.name']]].map(callsheltask)).then((result)=>{
  1532. // not yet configured.
  1533. if(!result.success) return onNoResult()
  1534. else {
  1535. var users = result.messages[0].trim().split('\n');
  1536. if(users.length === 0 ||
  1537. users.length === 1 && users[0] === 'guest') {
  1538. return onNoResult()
  1539. }
  1540. else return users[0]; // PB : TODO == We should probably prompt with all the users available for selection !
  1541. }
  1542. })
  1543. .catch((e)=>{
  1544. console.log(e)
  1545. return onNoResult()
  1546. })
  1547. }
  1548. }
  1549. ,
  1550. {
  1551. shellcmd: 'node',
  1552. url: 'https://nodejs.org/dist/v14.16.0/node-v14.16.0-x64.msi'
  1553. , installer: 'node-v14.16.0-x64.msi'
  1554. , installcmd: ['MSIEXEC.exe', ['/i'
  1555. , path.resolve(downloadsdir + '/' + 'node-v14.16.0-x64.msi')
  1556. , 'ACCEPT=YES', '/passive']]
  1557. , install : function() { return any([this.installcmd].map(callsheltask)).then(() => { }) }
  1558. }
  1559. ]
  1560. prerequisites.forEach(p=>{ prerequisites[p.shellcmd] = p })
  1561. function ensureDirectoryExistence(filePath) {
  1562. var dirname = path.dirname(filePath);
  1563. if (fs.existsSync(dirname)) {
  1564. return filePath;
  1565. }
  1566. ensureDirectoryExistence(dirname);
  1567. fs.mkdirSync(dirname);
  1568. return filePath;
  1569. }
  1570. var mainTasks = [];
  1571. function verifyAndInstallPrerequisites() {
  1572. fs.writeFileSync(ensureDirectoryExistence(path.normalize(downloadsdir + '/readme.txt')), `${getVersion()} Your local downloads for this instance`)
  1573. var downloadbatch =
  1574. `::**************************************************************************
  1575. :Download_ <url> <File>
  1576. Powershell.exe ^
  1577. $AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'; ^
  1578. [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols; ^
  1579. (New-Object System.Net.WebClient).DownloadFile('%1','%2')
  1580. exit /b
  1581. ::**************************************************************************`
  1582. fs.writeFileSync('download.bat', downloadbatch)
  1583. var downloadtasks = [];
  1584. var installtasks = [];
  1585. prerequisites.forEach(preq => {
  1586. downloadtasks.push(getTaskCheckExists(preq.shellcmd, { ignorefailures: true })().then((exists) => {
  1587. if (exists) console.log(`${preq.shellcmd} exists`)
  1588. else {
  1589. console.log(`${preq.shellcmd} is not installed`)
  1590. return preq.preinstallsteps.call(preq).then(() => {
  1591. installtasks.push(preq.install.bind(preq))
  1592. })
  1593. }
  1594. }))
  1595. })
  1596. return Promise.all(downloadtasks).then(() => { return any(installtasks) })
  1597. }
  1598. // function updateselection(selected) { selectedinstance = utils.assign(selectedinstance, selected) }
  1599. var selectedinstance = null;
  1600. var chessinstances = { current_run : {} };
  1601. acquireElevationState().then(() => {
  1602. var skipprerequisites = false;
  1603. var clioverrides = { }
  1604. function initinstances(chessinstances, selected) {
  1605. chessinstances.current_run.instanceName = processedArgs._[1] = processedArgs._[1] || chessinstances.current_run.instanceName || selected.instanceName;
  1606. chessinstances.current_run.node_env = processedArgs.node_env = processedArgs.node_env || chessinstances.current_run.node_env || selected.node_env;
  1607. chessinstances[chessinstances.current_run.instanceName] = chessinstances[chessinstances.current_run.instanceName] || {}
  1608. // Override sequence.
  1609. // __default, chessinstances[current_run], instanceName-config-development, cliargs, interactve_promts
  1610. selectedinstance = Object.assign(
  1611. selected
  1612. , chessinstances[chessinstances.current_run.instanceName][chessinstances.current_run.node_env]
  1613. , clioverrides
  1614. // , __interactve_promts -- Cant just override. Also need selectedinstance to be ready...
  1615. );
  1616. repomanifest = selectedinstance
  1617. return chessinstances
  1618. }
  1619. function acquirelocalinstances(selected){
  1620. var chessinstances = utils.assign(require(path.normalize(selected.root + '/chessinstances.js')));
  1621. return chessinstances
  1622. }
  1623. var maintask = () => {
  1624. // Default cmd to run !
  1625. processedArgs._[0] === processedArgs._[0] || 'pull';
  1626. // selectedinstance.reposerver = repomanifest.reposervers[0] // PB : TODO -- Attempt first one that is available and online from all that are available...
  1627. return prerequisites.git.verifyAndInstall().then(()=>{
  1628. var e = { message : 'verifyAndInstall', success : true}
  1629. return acquireConfig(selectedinstance, chessinstances).catch((err) => {
  1630. e = err;
  1631. console.error('Chosen cofiguraton failed or not found. Fix config and rerun or chose another.')
  1632. console.error(err)
  1633. }).then(() => { return elxrworker(true) })
  1634. // .finally(()=>{
  1635. // fs.writeFileSync('run.log', ', ' + JSON.stringify({ error: e.message }), { 'flag': 'a+' })
  1636. // if(!e.success) fs.writeFileSync('run.done', 'error');
  1637. // // return process.exit()
  1638. // })
  1639. })
  1640. }
  1641. return detectInstance().then((detectedInstance)=>{
  1642. processedArgs._[1] ? clioverrides.instanceName = processedArgs._[1]: null;
  1643. processedArgs.node_env ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()) || processedArgs.node_env
  1644. : (process.env.NODE_ENV && process.env.NODE_ENV.trim()) ? clioverrides.node_env = (process.env.NODE_ENV && process.env.NODE_ENV.trim()): null;
  1645. selectedinstance = Object.assign(detectedInstance, clioverrides);
  1646. var todo = Promise.resolve(true);
  1647. try {
  1648. chessinstances = acquirelocalinstances(selectedinstance);
  1649. initinstances(chessinstances, selectedinstance)
  1650. }
  1651. catch (e) {
  1652. console.error(e)
  1653. // No local instances config found. We acquire user choices and proceed to reattempt.
  1654. initinstances(chessinstances, selectedinstance)
  1655. var prompts = [];
  1656. Object.keys(__interactve_promts).forEach(k => {
  1657. if(!selectedinstance[k]) {
  1658. prompts.push(async ()=>{
  1659. Object.defineProperty(selectedinstance, k, Object.getOwnPropertyDescriptor(__interactve_promts, k));
  1660. return await selectedinstance[k]
  1661. })
  1662. }
  1663. })
  1664. todo = any(prompts).then(()=>{ return selectedinstance })
  1665. if(!processedArgs._[0] || !selectedinstance.node_env || !selectedinstance.instanceName){
  1666. // Weve been told what to do.
  1667. todo = acquireChoices(selectedinstance)
  1668. }
  1669. todo = todo.then(() => {
  1670. try {
  1671. chessinstances = acquirelocalinstances(selectedinstance)
  1672. initinstances(chessinstances, selectedinstance)
  1673. }
  1674. catch (e) {
  1675. console.error(e)
  1676. console.log('No local instances config found in current root = ' + selectedinstance.root);
  1677. console.log('A config will be createed with the instance and environment chosen...')
  1678. // return (async ()=>{return await __default.reposerver})().then(()=>{
  1679. // // selectedinstance = Object.assign(detectedInstance, clioverrides);
  1680. // return selectedinstance = Object.assign(__default, selectedinstance);
  1681. // })
  1682. return selectedinstance
  1683. }
  1684. })
  1685. }
  1686. return todo
  1687. }).then(()=>{
  1688. if (!skipprerequisites && !__isElevated) mainTasks.push(verifyAndInstallPrerequisites);
  1689. mainTasks.push(maintask)
  1690. return any(mainTasks);
  1691. })
  1692. })
  1693. // detect if alread installed -> Take no action.
  1694. // download if no installer avalable -> next()
  1695. // install
  1696. function chackandinstall(items) {
  1697. var tasks = []
  1698. items.forEach(item => {
  1699. tasks.push(getTaskCheckExists(item.shellcommand || prerequisites[item]))
  1700. })
  1701. return Promise.all(tasks).then(existances => {
  1702. existances.forEach((exists, i) => {
  1703. if (!exists) {
  1704. return downloadandinstall([items[i]])
  1705. }
  1706. })
  1707. })
  1708. }
  1709. function downloadandinstall(items) {
  1710. var tasks = []
  1711. items.forEach(item => {
  1712. tasks.push(getTaskDownload(item))
  1713. })
  1714. return Promise.all(tasks)
  1715. }
  1716. // Sample instances config.
  1717. // var instances = {
  1718. // "elixir": {
  1719. // "production": {
  1720. // "reposervers": ["http://git.bbh", "https://git.bbh.org.in"]
  1721. // , "repos": ["ember-masonry-grid", "client", "elixir-client"]
  1722. // , "exludeMergeRepos": {
  1723. // "elixir-config-development": true, "elixir-config-test": true
  1724. // , "elixir-config-production": true, "elixir-data": true
  1725. // }
  1726. // , "instanceName": "elixir", "node_env": "production"
  1727. // }
  1728. // },
  1729. // "current_run": { "instanceName": "elixir", "node_env": "production" }
  1730. // }