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

index.js 68KB

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