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

index.js 77KB

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