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